@@ -21,6 +21,8 @@ typedef enum MetaCommandResult_t MetaCommandResult;
21
21
22
22
enum PrepareResult_t {
23
23
PREPARE_SUCCESS ,
24
+ PREPARE_NEGATIVE_ID ,
25
+ PREPARE_STRING_TOO_LONG ,
24
26
PREPARE_SYNTAX_ERROR ,
25
27
PREPARE_UNRECOGNIZED_STATEMENT
26
28
};
@@ -33,8 +35,8 @@ const uint32_t COLUMN_USERNAME_SIZE = 32;
33
35
const uint32_t COLUMN_EMAIL_SIZE = 255 ;
34
36
struct Row_t {
35
37
uint32_t id ;
36
- char username [COLUMN_USERNAME_SIZE ];
37
- char email [COLUMN_EMAIL_SIZE ];
38
+ char username [COLUMN_USERNAME_SIZE + 1 ];
39
+ char email [COLUMN_EMAIL_SIZE + 1 ];
38
40
};
39
41
typedef struct Row_t Row ;
40
42
@@ -133,17 +135,40 @@ MetaCommandResult do_meta_command(InputBuffer* input_buffer) {
133
135
}
134
136
}
135
137
138
+ PrepareResult prepare_insert (InputBuffer * input_buffer , Statement * statement ) {
139
+ statement -> type = STATEMENT_INSERT ;
140
+
141
+ char * keyword = strtok (input_buffer -> buffer , " " );
142
+ char * id_string = strtok (NULL , " " );
143
+ char * username = strtok (NULL , " " );
144
+ char * email = strtok (NULL , " " );
145
+
146
+ if (id_string == NULL || username == NULL || email == NULL ) {
147
+ return PREPARE_SYNTAX_ERROR ;
148
+ }
149
+
150
+ int id = atoi (id_string );
151
+ if (id < 0 ) {
152
+ return PREPARE_NEGATIVE_ID ;
153
+ }
154
+ if (strlen (username ) > COLUMN_USERNAME_SIZE ) {
155
+ return PREPARE_STRING_TOO_LONG ;
156
+ }
157
+ if (strlen (email ) > COLUMN_EMAIL_SIZE ) {
158
+ return PREPARE_STRING_TOO_LONG ;
159
+ }
160
+
161
+ statement -> row_to_insert .id = id ;
162
+ strcpy (statement -> row_to_insert .username , username );
163
+ strcpy (statement -> row_to_insert .email , email );
164
+
165
+ return PREPARE_SUCCESS ;
166
+ }
167
+
136
168
PrepareResult prepare_statement (InputBuffer * input_buffer ,
137
169
Statement * statement ) {
138
170
if (strncmp (input_buffer -> buffer , "insert" , 6 ) == 0 ) {
139
- statement -> type = STATEMENT_INSERT ;
140
- int args_assigned = sscanf (
141
- input_buffer -> buffer , "insert %d %s %s" , & (statement -> row_to_insert .id ),
142
- statement -> row_to_insert .username , statement -> row_to_insert .email );
143
- if (args_assigned < 3 ) {
144
- return PREPARE_SYNTAX_ERROR ;
145
- }
146
- return PREPARE_SUCCESS ;
171
+ return prepare_insert (input_buffer , statement );
147
172
}
148
173
if (strcmp (input_buffer -> buffer , "select" ) == 0 ) {
149
174
statement -> type = STATEMENT_SELECT ;
@@ -205,6 +230,12 @@ int main(int argc, char* argv[]) {
205
230
switch (prepare_statement (input_buffer , & statement )) {
206
231
case (PREPARE_SUCCESS ):
207
232
break ;
233
+ case (PREPARE_NEGATIVE_ID ):
234
+ printf ("ID must be positive.\n" );
235
+ continue ;
236
+ case (PREPARE_STRING_TOO_LONG ):
237
+ printf ("String is too long.\n" );
238
+ continue ;
208
239
case (PREPARE_SYNTAX_ERROR ):
209
240
printf ("Syntax error. Could not parse statement.\n" );
210
241
continue ;
0 commit comments