forked from davidjmerriman/queryparser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queryparser.c
92 lines (70 loc) · 1.95 KB
/
queryparser.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "postgres.h"
#include <ctype.h>
#include <float.h>
#include <math.h>
#include <limits.h>
#include <unistd.h>
#include <sys/stat.h>
#include "utils/memutils.h"
#include "parser/parser.h"
#include "nodes/print.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFSIZE 32768
const char* progname = "queryparser";
char* readInput(void);
bool doParse(const char* query, char* (*output_fnc)(const void*) );
char* readInput() {
char buffer[BUFSIZE];
size_t inputSize = 1;
char * input = malloc(sizeof(char) * BUFSIZE);
if (input == NULL) {
perror("Could not allocate input string");
exit(1);
}
input[0] = '\0'; // C strings are null-terminated; init zero-length string
// Read until end of input (CTRL+D, CTRL+Z on Windows)
while (fgets(buffer, BUFSIZE, stdin)) {
char * old = input;
inputSize += strlen(buffer);
input = realloc(input, inputSize);
if (input == NULL) {
perror("Could not reallocate input to append buffer");
free(old);
exit(2);
}
strcat(input, buffer);
}
if (ferror(stdin)) {
perror("Error reading input");
free(input);
exit(3);
}
return input;
}
bool doParse(const char* query, char* (*output_fnc)(const void*)) {
List *tree;
tree = raw_parser(query);
if (tree != NULL) {
char *s;
s = output_fnc(tree);
printf("%s\n", s);
pfree(s);
}
return (tree != NULL);
}
int main(int argc, char **argv) {
char* line;
MemoryContextInit();
if (argc > 1 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
printf("Parse SQL query from stdin\nUSAGE: queryparser\nOPTIONS:\n\t--json: Output in JSON format\n\t--help: Show this help\n");
return 0;
}
line = readInput();
if (argc > 1 && strcmp(argv[1], "--json") == 0) {
return doParse(line, &nodeToJSONString) ? 0 : 1;
} else {
return doParse(line, &nodeToString) ? 0 : 1;
}
}