Skip to content

Instantly share code, notes, and snippets.

@liamoc
Created January 2, 2011 07:30
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save liamoc/762380 to your computer and use it in GitHub Desktop.
Save liamoc/762380 to your computer and use it in GitHub Desktop.
Creating Tables in C
#include <stdio.h>
/* BEGIN HACKERY */
typedef struct field {
enum {
TABLE_NAME,
TABLE_FIELD,
TABLE_TERMINATOR
} tag;
union {
char* table_name;
struct { char* type;
char* opts;
char* name; } field;
} val;
} Field;
#define table(_name, ...) Field _name[] = { {.tag = TABLE_NAME, .val = {.table_name = #_name}} , __VA_ARGS__ , {.tag = TABLE_TERMINATOR} }
#define field(_name,_type,_opts) {.tag = TABLE_FIELD, .val = {.field = {.type =_type, .name = #_name, .opts = _opts}}}
typedef Field* Table;
/* END HACKERY */
/* BEGIN AWESOME */
table(BlogPost,
field(Id,"INTEGER","PRIMARY KEY AUTOINCREMENT"),
field(Title, "VARCHAR(200)", ""),
field(Body, "TEXT", "")
);
/* END AWESOME */
void printTableDef(Table tableDef) {
int i;
for (i = 0; tableDef[i].tag != TABLE_TERMINATOR; i++) {
if (tableDef[i].tag == TABLE_NAME) {
printf("CREATE TABLE %s (", tableDef[i].val.table_name);
} else {
printf("%s %s %s", tableDef[i].val.field.name, tableDef[i].val.field.type, tableDef[i].val.field.opts);
printf(tableDef[i+1].tag == TABLE_TERMINATOR ? ")" : ", ");
}
}
printf(";\n");
}
int main () {
printTableDef(BlogPost);
return 0;
}
@twoolie
Copy link

twoolie commented Jan 2, 2011

what is this i don't even.....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment