/* Read an SQL statement and do a simple pretty print using commas as separator */ #include #include #include #include #include #include using namespace std; static bool is_keyword (const char *pt, const char *keyw) { bool ret = false; int len = strlen(keyw); if (strncasecmp(pt,keyw,len)==0 && !isalpha(pt[len]) && !isdigit(pt[len]) && pt[len] != '_'){ ret = true; } return ret; } static bool indent = false; static void nextline() { fputc ('\n',stdout); if (indent) fputc('\t',stdout); } static void format (FILE *fin) { char buf[100000]; int opnpar = 0; while (fgets(buf,sizeof(buf)-1,fin)!=NULL){ if (strncmp(buf,"***",3)==0){ printf ("\n%s\n",buf); opnpar = 0; continue; } const char *pt = buf; int in_function = 0; // Inside function call, we do not change line at every comma bool last_wasalpha = false; // Last characters (before the open parenthese) were alpha while (*pt != '\0'){ if (is_keyword(pt,"select") || is_keyword(pt,"update") || is_keyword(pt,"create") || is_keyword(pt,"drop") || is_keyword(pt,"insert")){ nextline(); for (int i=0; i 0) in_function--; }else{ fputc (*pt,stdout); pt++; } } } printf ("\n"); } } int main (int argc, char *argv[]) { glocal int ret = -1; glocal.ret = (argc,argv); setproginfo ("formatsql",VERSION,"Format SQL statements"); setarg ('i',"indent","Indent all the SQL",indent,false); format (stdin); return 0; int ret = -1; if (argc == 0){ usage(); }else{ for (int i=0; i return glocal.ret; }