@@ -10,6 +10,23 @@ struct InputBuffer_t {
10
10
};
11
11
typedef struct InputBuffer_t InputBuffer ;
12
12
13
+ enum MetaCommandResult_t {
14
+ META_COMMAND_SUCCESS ,
15
+ META_COMMAND_UNRECOGNIZED_COMMAND
16
+ };
17
+ typedef enum MetaCommandResult_t MetaCommandResult ;
18
+
19
+ enum PrepareResult_t { PREPARE_SUCCESS , PREPARE_UNRECOGNIZED_STATEMENT };
20
+ typedef enum PrepareResult_t PrepareResult ;
21
+
22
+ enum StatementType_t { STATEMENT_INSERT , STATEMENT_SELECT };
23
+ typedef enum StatementType_t StatementType ;
24
+
25
+ struct Statement_t {
26
+ StatementType type ;
27
+ };
28
+ typedef struct Statement_t Statement ;
29
+
13
30
InputBuffer * new_input_buffer () {
14
31
InputBuffer * input_buffer = malloc (sizeof (InputBuffer ));
15
32
input_buffer -> buffer = NULL ;
@@ -35,16 +52,66 @@ void read_input(InputBuffer* input_buffer) {
35
52
input_buffer -> buffer [bytes_read - 1 ] = 0 ;
36
53
}
37
54
55
+ MetaCommandResult do_meta_command (InputBuffer * input_buffer ) {
56
+ if (strcmp (input_buffer -> buffer , ".exit" ) == 0 ) {
57
+ exit (EXIT_SUCCESS );
58
+ } else {
59
+ return META_COMMAND_UNRECOGNIZED_COMMAND ;
60
+ }
61
+ }
62
+
63
+ PrepareResult prepare_statement (InputBuffer * input_buffer ,
64
+ Statement * statement ) {
65
+ if (strncmp (input_buffer -> buffer , "insert" , 6 ) == 0 ) {
66
+ statement -> type = STATEMENT_INSERT ;
67
+ return PREPARE_SUCCESS ;
68
+ }
69
+ if (strcmp (input_buffer -> buffer , "select" ) == 0 ) {
70
+ statement -> type = STATEMENT_SELECT ;
71
+ return PREPARE_SUCCESS ;
72
+ }
73
+
74
+ return PREPARE_UNRECOGNIZED_STATEMENT ;
75
+ }
76
+
77
+ void execute_statement (Statement * statement ) {
78
+ switch (statement -> type ) {
79
+ case (STATEMENT_INSERT ):
80
+ printf ("This is where we would do an insert.\n" );
81
+ break ;
82
+ case (STATEMENT_SELECT ):
83
+ printf ("This is where we would do a select.\n" );
84
+ break ;
85
+ }
86
+ }
87
+
38
88
int main (int argc , char * argv []) {
39
89
InputBuffer * input_buffer = new_input_buffer ();
40
90
while (true) {
41
91
print_prompt ();
42
92
read_input (input_buffer );
43
93
44
- if (strcmp (input_buffer -> buffer , ".exit" ) == 0 ) {
45
- exit (EXIT_SUCCESS );
46
- } else {
47
- printf ("Unrecognized command '%s'.\n" , input_buffer -> buffer );
94
+ if (input_buffer -> buffer [0 ] == '.' ) {
95
+ switch (do_meta_command (input_buffer )) {
96
+ case (META_COMMAND_SUCCESS ):
97
+ continue ;
98
+ case (META_COMMAND_UNRECOGNIZED_COMMAND ):
99
+ printf ("Unrecognized command '%s'\n" , input_buffer -> buffer );
100
+ continue ;
101
+ }
48
102
}
103
+
104
+ Statement statement ;
105
+ switch (prepare_statement (input_buffer , & statement )) {
106
+ case (PREPARE_SUCCESS ):
107
+ break ;
108
+ case (PREPARE_UNRECOGNIZED_STATEMENT ):
109
+ printf ("Unrecognized keyword at start of '%s'.\n" ,
110
+ input_buffer -> buffer );
111
+ continue ;
112
+ }
113
+
114
+ execute_statement (& statement );
115
+ printf ("Executed.\n" );
49
116
}
50
117
}
0 commit comments