开发者

How To Create Database Tables in C

I need to code a small/simple database application using C, for my CS degree (so using SQLite or any other available application is not an option. In other words, I do need to re-invent the wheel here).

My idea is to use a B-Tree to store the items of each table. The problem I am facing is that tables need to be flexible to hold an unknown number of columns, and each column can be either a STRING or an INT. For example, with this command:

CREATE TABLE student (STRING name, INT a开发者_JS百科ge)

I would need to create a table that holds a string and an integer. With this command instead:

CREATE TABLE grade (INT grade1, INT grade2, INT grade3)

I would need to create a table that holds three integers.

How can achieve such flexibility?

My only idea so far is to create a struct with several unions inside it, where each union can be either a STRING or an INT. I would also need to put a lot of unions inside, to be sure to accommodate all the columns requested by the table. For example:

struct table{
    union{
        int number;
        char *text;
    }column1;

    union{
        int number;
        char *text;
    }column2;

    union{
        int number;
        char *text;
    }column3;

    ....

};

Is there a better way to do this?


i can only think of two very different approaches:

  1. make a 'schema compiler' that gets the table definition, writes the structs and compiles the database engine.
  2. from the schema definition calculate the byte offset and length of each column. save and restore the records as a byte array and pick the fields using that offset/length list.

most common is #2, but #1 has the advantage that the C compiler 'knows' the table structure, and will type-check your columns.


I know this is an old question and my answer is a bit irrelevant, but I encounter the same issue when I was writing my custom database for fun. However, my solution is to write a native dynamic struct library in C++ and utilize OOP features like virtual function heavily. Maybe, you could find a way to transport it into a C library or get some inspirations to develop your own one.

For your reference, I upload my code to GitHub and here is the link c++-dynamic-type-library. I illustrate some usages in the README file, and one of them is exactly to create a struct with variable number of properties and types from input (thus could be adapted to CREATE TABLE command). I also write Serialize and Deserialize function to transform a struct into string and back forth.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜