-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstored_proc.c
3427 lines (2928 loc) · 98.9 KB
/
stored_proc.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdbool.h>
#ifdef SQLITE_DEBUG
#define XTRACE(...) printf(__VA_ARGS__)
#else
#define XTRACE(...)
#endif
#define CMD_TYPE_DECLARE 1
#define CMD_TYPE_SET 2
#define CMD_TYPE_STATEMENT 3
#define CMD_TYPE_RETURN 4
#define CMD_TYPE_RAISE 5
#define CMD_TYPE_IF 6
#define CMD_TYPE_ELSEIF 7
#define CMD_TYPE_ELSE 8
#define CMD_TYPE_ENDIF 9
#define CMD_TYPE_LOOP 10
#define CMD_TYPE_ENDLOOP 11
#define CMD_TYPE_BREAK 12
#define CMD_TYPE_CONTINUE 13
#define CMD_TYPE_FOREACH 14
#define CMD_FLAG_STORE_AS_ARRAY 1
#define CMD_FLAG_DYNAMIC_SQL 2
#define CMD_FLAG_EXECUTED 4
#define POS_RESULT_ROW 2
#define POS_NEXT_RESULT 3
typedef struct sqlite3_var sqlite3_var;
struct sqlite3_var {
char name[32]; /* variable name, including the @ */
int len; /* variable name size */
u8 type; //affinity; /* defined type. SQLITE_INTEGER, REAL, TEXT or BLOB */
int declared_in_pos; /* position in the procedure where it was declared */
sqlite3_value value; /* contains a value or a pointer to an array struct */
sqlite3_var *next; /* next in the global list */
sqlite3_var *nextUsed; /* temporary use */
};
#define VAR_POS_PARAMETER -2
// when a sqlite3_var contains an array, the sqlite3_value has a pointer to a sqlite3_array structure
typedef struct sqlite3_array sqlite3_array;
struct sqlite3_array {
int num_items;
sqlite3_value value[1];
};
typedef struct stored_proc stored_proc;
typedef struct command command;
struct command {
int type;
char *sql;
int nsql;
sqlite3_stmt *stmt; /* used in STATEMENT, SET, FOREACH and RETURN */
sqlite3_array *input_array; /* parsed ARRAY, used in SET, FOREACH and CALL commands */
sqlite3_var *input_var; /* used in the FOREACH command */
unsigned int current_item; /* used in the FOREACH command */
int flags;
stored_proc *procedure; /* used in CALL command */
int next_if_cmd; /* used in ELSEIF, ELSE, END IF */
int related_cmd; /* used in LOOP, BREAK, CONTINUE, END LOOP, FOREACH */
sqlite3_var **vars; /* variables used in this command (array of pointers to) */
unsigned int num_vars;
};
struct stored_proc {
sqlite3 *db;
char name[128];
bool is_function;
char *code;
char *error_msg;
// commands
command* cmds; // an array of commands (pointer to allocated memory)
unsigned int num_alloc_cmds; // the current size of the array (number of elements)
unsigned int num_cmds;
// variables
sqlite3_var* vars;
//unsigned int num_vars;
// parameters = variables declared in the procedure header
sqlite3_var** params; // an array of pointers to variables
unsigned int num_params;
// result
sqlite3_array *result_array;
int current_row;
// aMem and nMem from Vdbe are temporarily stored here
sqlite3_value *aMem;
int nMem;
};
struct procedure_call {
stored_proc *procedure;
sqlite3_array *input_array;
};
////////////////////////////////////////////////////////////////////////////////
SQLITE_PRIVATE sqlite3_var* findVariable(stored_proc *procedure, char *name, int len);
SQLITE_PRIVATE int parse_variables_list(
stored_proc* procedure,
int cmd_pos,
char** psql,
unsigned int *pnum_vars,
sqlite3_var **pvar_list
);
SQLITE_PRIVATE int parse_input_array(Parse *pParse, stored_proc* procedure, int cmd_pos, char** psql);
SQLITE_PRIVATE int parse_procedure_body(Parse *pParse, stored_proc* procedure, char** psql);
SQLITE_PRIVATE void releaseProcedure(stored_proc* procedure);
SQLITE_PRIVATE void releaseProcedureCall(procedure_call* call);
////////////////////////////////////////////////////////////////////////////////
/*
** Identifies the next `;` token, and returns the position of the next token.
** If the `;` is inside a string or identifier, it will be ignored.
** If the `;` is inside a comment, it will be ignored.
** Use the sqlite3GetToken() function to identify the tokens
*/
SQLITE_PRIVATE int skip_sql_command(char **psql){
char *sql = *psql;
int n;
int token_type = 0;
while( (n = sqlite3GetToken((u8*)sql, &token_type)) != 0 ){
if( token_type == TK_SEMI ){
break;
}
sql += n;
}
n = sql - *psql;
if( token_type == TK_SEMI ){
sql++;
}
*psql = sql;
return n;
}
SQLITE_PRIVATE int skip_delimited_sql_command(char **psql, int delimiter, int ndelim){
char *sql = *psql;
int n;
int token_type = 0;
bool found = false;
while( (n = sqlite3GetToken((u8*)sql, &token_type)) != 0 ){
if( token_type == delimiter ){
found = true;
break;
}
sql += n;
}
// if the delimiter was not found, return -1
if( !found ) return -1;
// get the size of the command
n = sql - *psql;
// skip the delimiter
sql += ndelim;
// skip whitespaces
while( sqlite3Isspace(*sql) ) sql++;
// return the position of the next token
*psql = sql;
// return the size of the command
return n;
}
////////////////////////////////////////////////////////////////////////////////
// VALUES
////////////////////////////////////////////////////////////////////////////////
SQLITE_PRIVATE void sqlite3ValueSetSubtype(sqlite3_value *pVal, unsigned int eSubtype){
pVal->eSubtype = eSubtype & 0xff;
pVal->flags |= MEM_Subtype;
}
/*
** Store a variable name in a value.
*/
SQLITE_PRIVATE void sqlite3ValueSetVariable(
sqlite3_value *value, char *name, int len, u8 enc
){
sqlite3ValueSetStr(value, len, name, enc, SQLITE_TRANSIENT);
sqlite3ValueSetSubtype(value, 'v');
}
/*
** Store a pointer to an array in a value.
*/
SQLITE_PRIVATE void sqlite3ValueSetArray(
sqlite3_value *value, sqlite3_array *array, void (*free_func)(sqlite3_array*)
){
sqlite3VdbeMemSetNull(value);
sqlite3VdbeMemSetPointer(value, array, "array", (void(*)(void*))free_func);
}
/*
** Return true if the supplied value contains a variable.
*/
SQLITE_PRIVATE bool is_variable(sqlite3_value *pVal){
return (sqlite3_value_type(pVal) == SQLITE_TEXT) && (sqlite3_value_subtype(pVal) == 'v');
}
/*
** Return true if the value contains an array.
*/
SQLITE_PRIVATE bool is_array(sqlite3_value *pVal){
return sqlite3_value_pointer(pVal, "array") != NULL;
}
/*
** Return the array stored in the value.
*/
SQLITE_PRIVATE sqlite3_array* get_array_from_value(sqlite3_value *pVal){
return sqlite3_value_pointer(pVal, "array");
}
/*
** Fill the sqlite3_value object with the value of the given token.
**
** This only works for very simple expressions that consist of one constant
** token (i.e. "12", "-3.4", "'a string'", "TRUE", "FALSE", "NULL", "x'0102'").
** If the expression cannot be converted to a value, SQLITE_ERROR is returned.
*/
SQLITE_PRIVATE int sqlite3ValueFromToken(
char **pzToken, /* The token to evaluate */
int nToken,
int tk,
u8 enc, /* Encoding to use */
sqlite3_value *pVal /* Write the new value here */
){
char *zToken = *pzToken;
int rc = SQLITE_OK;
assert( pVal!=NULL );
if( tk==TK_MINUS ){
assert( nToken==1 );
// get the next token
zToken++;
nToken = sqlite3GetToken((u8*)zToken, &tk);
// if the next token is not an integer or float, then it is not a negative integer
if( tk!=TK_INTEGER && tk!=TK_FLOAT ){
return SQLITE_ERROR;
}
zToken--;
nToken++;
}
if( tk==TK_INTEGER ){
i64 value = 0;
sqlite3Atoi64(zToken, &value, nToken, enc);
sqlite3VdbeMemSetInt64(pVal, value);
}else if( tk==TK_FLOAT ){
double value = (double) 0;
sqlite3AtoF(zToken, &value, nToken, enc);
sqlite3VdbeMemSetDouble(pVal, value);
}else if( tk==TK_STRING ){
if( nToken>0 && sqlite3Isquote(zToken[0]) ){
char *zStr = sqlite3StrNDup(zToken, nToken);
sqlite3Dequote(zStr);
sqlite3VdbeMemSetStr(pVal, zStr, -1, enc, SQLITE_DYNAMIC);
} else if( nToken>0 ){
sqlite3VdbeMemSetStr(pVal, zToken, nToken, enc, SQLITE_TRANSIENT);
}else{
sqlite3VdbeMemSetStr(pVal, "", 0, enc, SQLITE_STATIC);
}
}
#ifndef SQLITE_OMIT_BLOB_LITERAL
else if( tk==TK_BLOB ){
char *zVal;
int nVal;
assert( zToken[0]=='x' || zToken[0]=='X' );
assert( zToken[1]=='\'' );
zVal = &zToken[2];
nVal = nToken - 3;
assert( zVal[nVal]=='\'' );
zVal = sqlite3HexToBlob2(zVal, nVal);
if( zVal==NULL ) return SQLITE_NOMEM;
sqlite3VdbeMemSetStr(pVal, zVal, nVal/2, 0, SQLITE_DYNAMIC);
}
#endif
else if( tk==TK_ID ){
if( nToken==4 && sqlite3_strnicmp(zToken, "true", nToken)==0 ){
pVal->flags = MEM_Int;
pVal->u.i = 1;
} else if( nToken==5 && sqlite3_strnicmp(zToken, "false", nToken)==0 ){
pVal->flags = MEM_Int;
pVal->u.i = 0;
} else if( nToken==4 && sqlite3_strnicmp(zToken, "null", nToken)==0 ){
sqlite3VdbeMemSetNull(pVal);
} else {
rc = SQLITE_ERROR;
}
} else {
rc = SQLITE_ERROR;
}
if( rc==SQLITE_OK ){
zToken += nToken;
*pzToken = zToken;
}
return rc;
}
////////////////////////////////////////////////////////////////////////////////
// ARRAYS
////////////////////////////////////////////////////////////////////////////////
/*
** Release the content of the array, recursively.
** If the value contains a sub-array, then the sub-array is also released.
*/
SQLITE_PRIVATE void sqlite3_free_array(sqlite3_array *array) {
if (array == NULL) return;
for (int i = 0; i < array->num_items; i++) {
// release the value
// if it contains an array, it is released recursively
sqlite3VdbeMemRelease(&array->value[i]);
}
sqlite3_free(array);
}
/*
** Parse an array
** It can contain internal arrays.
** The ARRAY keyword is optional.
** Examples:
** ARRAY(1,2,3,ARRAY(4,5,6))
** ARRAY(1,2,3,(4,5,6))
** (1,2,3,(4,5,6))
*/
SQLITE_PRIVATE int parse_array(
Parse *pParse, stored_proc* procedure, char** psql, sqlite3_array **parray
){
char* sql = *psql;
int rc = SQLITE_OK;
int n, tokenType;
sqlite3_array* array = NULL;
// skip whitespaces
while (sqlite3Isspace(*sql)) sql++;
// check for the optional "ARRAY" keyword
if (sqlite3_strnicmp(sql, "ARRAY", 5) == 0) {
sql += 5;
while (sqlite3Isspace(*sql)) sql++;
}
// check for "("
if (*sql != '(') return SQLITE_ERROR;
sql++;
while (sqlite3Isspace(*sql)) sql++;
// parse the array values
while (1) {
if (array == NULL) {
// allocate the array object with 1 item
array = sqlite3MallocZero( sizeof(sqlite3_array) );
if (!array) return SQLITE_NOMEM;
} else {
// increment the array size by 1 item
sqlite3_array* new_array;
new_array = sqlite3Realloc(array, sizeof(sqlite3_array) +
(array->num_items) * sizeof(sqlite3_value));
if (!new_array) {
sqlite3_free_array(array);
return SQLITE_NOMEM;
}
array = new_array;
memset(&array->value[array->num_items], 0, sizeof(sqlite3_value));
}
// get a reference to the new value
sqlite3_value *value = &array->value[array->num_items];
// initialize the value
sqlite3VdbeMemInit(value, pParse->db, MEM_Null);
// get the next token
n = sqlite3GetToken((u8*)sql, &tokenType);
if (tokenType == TK_VARIABLE) {
// if parsing a stored procedure, then the variable must exist
if (procedure) {
sqlite3_var *var;
var = findVariable(procedure, sql, n);
if (!var) {
sqlite3ErrorMsg(pParse, "variable must exist: %.*s", n, sql);
goto loc_invalid;
}
}
// save the variable name into the value
sqlite3ValueSetVariable(value, sql, n, SQLITE_UTF8);
// skip the variable name
sql += n;
} else if (tokenType == TK_LP || (tokenType == TK_ID &&
n == 5 && sqlite3_strnicmp(sql, "ARRAY", 5) == 0)) {
// parse the internal array
sqlite3_array *internal_array;
rc = parse_array(pParse, procedure, &sql, &internal_array);
if (rc != SQLITE_OK) {
goto loc_invalid;
}
// store the pointer to the internal array on the value
sqlite3ValueSetArray(value, internal_array, sqlite3_free_array);
} else if (tokenType == TK_RP) {
// this is an empty array
sql++;
break;
} else {
// retrieve the value from the token
rc = sqlite3ValueFromToken(&sql, n, tokenType, SQLITE_UTF8, value);
#ifdef SQLITE_DEBUG
printf("parse_array() pos=%d value=", array->num_items);
memTracePrint(value);
puts("");
#endif
if (rc != SQLITE_OK) {
goto loc_invalid;
}
}
// we have a new value
array->num_items++;
// skip whitespaces
while (sqlite3Isspace(*sql)) sql++;
// check for "," or ")"
if (*sql == ',') {
sql++;
while (sqlite3Isspace(*sql)) sql++;
} else if (*sql == ')') {
sql++;
break;
} else {
goto loc_invalid;
}
}
// skip whitespaces
while (sqlite3Isspace(*sql)) sql++;
*psql = sql;
*parray = array;
return SQLITE_OK;
loc_invalid:
if (array) sqlite3_free_array(array);
if (rc == SQLITE_OK) rc = SQLITE_ERROR;
if (pParse->zErrMsg == NULL) {
sqlite3ErrorMsg(pParse, "invalid token: %s", sql);
}
*psql = sql;
return rc;
}
////////////////////////////////////////////////////////////////////////////////
// VARIABLES
////////////////////////////////////////////////////////////////////////////////
/*
** Add a new local variable to the list or return the existing
** one with the supplied name.
*/
SQLITE_PRIVATE sqlite3_var* addVariable(
stored_proc *procedure, char *name, int len, u8 type, bool *pExists
){
sqlite3_var *var;
if( pExists ) *pExists = false;
/* check the variable name size */
if( len>sizeof(var->name)-1 ){
procedure->error_msg = sqlite3_mprintf("variable name must be up to 31 bytes long: %.*s", len, name);
return NULL;
}
/* check if already exists */
for( var=procedure->vars; var; var=var->next ){
/* use case sensitive variables */
if( var->len==len && sqlite3_strnicmp(var->name, name, len)==0 ){
if( pExists ) *pExists = true;
return var;
}
}
var = sqlite3MallocZero(sizeof(struct sqlite3_var));
if( !var ){
procedure->error_msg = sqlite3_mprintf("out of memory");
return NULL;
}
strncpy(var->name, name, len);
var->len = len;
var->type = type;
/* initialize the value */
sqlite3VdbeMemInit(&var->value, procedure->db, MEM_Null);
/* add to the list of variables */
var->next = procedure->vars;
procedure->vars = var;
return var;
}
/*
** Find a local variable with the supplied name.
*/
SQLITE_PRIVATE sqlite3_var* findVariable(stored_proc *procedure, char *name, int len){
sqlite3_var *var;
/* check the variable name size */
if( len>sizeof(var->name)-1 ){
procedure->error_msg = sqlite3_mprintf("variable name must be up to 31 bytes long: %.*s", len, name);
return NULL;
}
/* check if already exists */
for( var=procedure->vars; var; var=var->next ){
/* use case sensitive variables */
if( var->len==len && sqlite3_strnicmp(var->name, name, len)==0 ){
return var;
}
}
return NULL;
}
/*
** Drop all local variables.
*/
SQLITE_PRIVATE void dropAllVariables(stored_proc *procedure){
assert( procedure!=NULL );
/* clear the list of variables */
while( procedure->vars ){
sqlite3_var *current = procedure->vars;
// if it is an array, free it
//sqlite3_array *array = get_array_from_value(¤t->value);
//if( array ) sqlite3_free_array(array);
// the free function may be called by sqlite3VdbeMemRelease
// release the value
sqlite3VdbeMemRelease((Mem*)¤t->value);
// release the variable
sqlite3_var *next = current->next;
sqlite3_free(current);
procedure->vars = next;
}
}
/*
** Bind values of local variables to the prepared statement.
*/
SQLITE_PRIVATE void bindLocalVariables(stored_proc *procedure, sqlite3_stmt *stmt){
sqlite3_var *var;
XTRACE("bindLocalVariables count=%d \n", sqlite3_bind_parameter_count(stmt));
if( !procedure->vars || sqlite3_bind_parameter_count(stmt)==0 ) return;
/* for each declared variable, check if being used in the statement */
for( var=procedure->vars; var; var=var->next ){
int idx = sqlite3_bind_parameter_index(stmt, var->name);
XTRACE("bindLocalVariables %s idx=%d \n", var->name, idx);
if( idx>0 ){
sqlite3_bind_value(stmt, idx, &var->value);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// COMMANDS
////////////////////////////////////////////////////////////////////////////////
SQLITE_PRIVATE int parse_new_command(Parse *pParse, stored_proc* procedure, int type, char** psql);
SQLITE_PRIVATE int parseDeclareStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseSetStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseReturnStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseRaiseStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseIfStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseElseIfStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseElseStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseEndIfStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseLoopStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseEndLoopStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseBreakStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseContinueStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
SQLITE_PRIVATE int parseForEachStatement(Parse *pParse, stored_proc* procedure, int pos, char** psql);
#ifdef SQLITE_DEBUG
// returns the command type name in string format
SQLITE_PRIVATE char* command_type_str(int type) {
switch (type) {
case CMD_TYPE_DECLARE:
return "DECLARE";
case CMD_TYPE_SET:
return "SET";
case CMD_TYPE_RETURN:
return "RETURN";
case CMD_TYPE_RAISE:
return "RAISE";
case CMD_TYPE_STATEMENT:
return "STATEMENT";
case CMD_TYPE_IF:
return "IF";
case CMD_TYPE_ELSEIF:
return "ELSEIF";
case CMD_TYPE_ELSE:
return "ELSE";
case CMD_TYPE_ENDIF:
return "END IF";
case CMD_TYPE_LOOP:
return "LOOP";
case CMD_TYPE_ENDLOOP:
return "ENDLOOP";
case CMD_TYPE_BREAK:
return "BREAK";
case CMD_TYPE_CONTINUE:
return "CONTINUE";
case CMD_TYPE_FOREACH:
return "FOREACH";
}
return "UNKNOWN";
}
#endif
// new_command using arrays:
// - allocate an array of 16 commands if the array is not yet allocated (cmds == NULL),
// - scan the array for the first empty slot,
// - if the array is full (no empty slot), reallocates the array to double its size,
// - stores the new command object at the empty slot,
// - returns the position of the new command object in the array.
SQLITE_PRIVATE int new_command(stored_proc* procedure, int type) {
if (procedure->cmds == NULL) {
procedure->cmds = (command*) sqlite3_malloc(16 * sizeof(command));
if (procedure->cmds == NULL) return -1;
memset(procedure->cmds, 0, 16 * sizeof(command));
procedure->num_alloc_cmds = 16;
} else if (procedure->num_cmds == procedure->num_alloc_cmds) {
unsigned int old_size = procedure->num_alloc_cmds * sizeof(command);
char *new_list = sqlite3_realloc(procedure->cmds, 2 * old_size);
if (new_list == NULL) return -1;
memset(new_list + old_size, 0, old_size);
procedure->cmds = (command*) new_list;
procedure->num_alloc_cmds *= 2;
}
int pos = procedure->num_cmds;
procedure->num_cmds++;
procedure->cmds[pos].type = type;
procedure->cmds[pos].procedure = procedure;
return pos;
}
////////////////////////////////////////////////////////////////////////////////
// PROCEDURE PARSING
////////////////////////////////////////////////////////////////////////////////
/*
** Parse a stored procedure.
** The SQL command must start with "PROCEDURE". The "CREATE [OR REPLACE]" is not stored.
*/
SQLITE_PRIVATE int parseStoredProcedure(Parse *pParse, stored_proc* procedure, char** psql) {
char* sql = *psql;
int rc = SQLITE_OK;
int n, tokenType, i;
sqlite3_var *varList, *var;
if (sqlite3_strnicmp(sql, "PROCEDURE ", 10) == 0) {
//procedure->is_function = false;
// skip the "PROCEDURE" keyword + the space
sql += 10;
} else if (sqlite3_strnicmp(sql, "FUNCTION ", 9) == 0) {
procedure->is_function = true;
// skip the "FUNCTION" keyword + the space
sql += 9;
} else {
goto loc_invalid;
}
// skip spaces
while (sqlite3Isspace(*sql)) sql++;
// get the procedure name
n = sqlite3GetToken((u8*)sql, &tokenType);
if( tokenType!=TK_ID || n == 0 ){
goto loc_invalid;
}
// check the length of the procedure name
if( n > sizeof(procedure->name)-1 ){
sqlite3ErrorMsg(pParse, "procedure name too long");
goto loc_invalid;
}
// store it into the procedure object
strncpy(procedure->name, sql, n);
procedure->name[n] = '\0';
sql += n;
// skip spaces
while (sqlite3Isspace(*sql)) sql++;
// check for the "(" character
if (*sql != '(') {
goto loc_invalid;
}
// skip the "(" character
sql++;
// skip spaces
while (sqlite3Isspace(*sql)) sql++;
// if there is no parameter, skip the ")" character
if (*sql == ')') {
goto loc_skip_params;
}
// parse the procedure parameters
rc = parse_variables_list(procedure, VAR_POS_PARAMETER, &sql,
&procedure->num_params, &varList);
if (rc != SQLITE_OK) {
goto loc_invalid;
}
// store the list of parameters into the procedure object
procedure->params = sqlite3_malloc( procedure->num_params * sizeof(sqlite3_var*) );
for( i=0, var=varList; var; i++, var=var->nextUsed ){
procedure->params[i] = var;
}
// check for the ")" character
if (*sql != ')') {
goto loc_invalid;
}
loc_skip_params:
// skip the ")" character
sql++;
// skip spaces
while (sqlite3Isspace(*sql)) sql++;
// check for the "BEGIN" keyword
if (sqlite3_strnicmp(sql, "BEGIN", 5) != 0 || !sqlite3Isspace(sql[5])) {
goto loc_invalid;
}
// skip the "BEGIN" keyword
sql += 5;
// skip spaces
while (sqlite3Isspace(*sql)) sql++;
// parse the procedure body
rc = parse_procedure_body(pParse, procedure, &sql);
if (rc != SQLITE_OK) {
goto loc_invalid;
}
// check for the "END" keyword
if (sqlite3_strnicmp(sql, "END", 3) != 0) {
goto loc_invalid;
}
// skip the "END" keyword
sql += 3;
// skip spaces
while (sqlite3Isspace(*sql)) sql++;
// check for the ";" character or the end of the SQL command
if (*sql == ';') {
sql++;
} else if (*sql != '\0') {
goto loc_invalid;
}
// skip spaces
while (sqlite3Isspace(*sql)) sql++;
// return the remaining SQL command
*psql = sql;
return SQLITE_OK;
loc_invalid:
if (rc == SQLITE_OK) rc = SQLITE_ERROR;
if (pParse->zErrMsg == NULL) {
if (procedure->error_msg != NULL) {
sqlite3ErrorMsg(pParse, "%s", procedure->error_msg);
sqlite3_free(procedure->error_msg);
procedure->error_msg = NULL;
} else {
sqlite3ErrorMsg(pParse, "invalid token: %s", sql);
}
}
return rc;
}
/*
** Parse the body of a stored procedure or function.
*/
SQLITE_PRIVATE int parse_procedure_body(Parse *pParse, stored_proc* procedure, char **psql) {
char* sql = *psql;
int rc = SQLITE_OK;
while (sql && *sql) {
// if the SQL command starts with "DECLARE", then it is a variable declaration
if (sqlite3_strnicmp(sql, "DECLARE", 7) == 0 && sqlite3Isspace(sql[7])) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_DECLARE, &sql);
// if the SQL command starts with "SET", then it is a variable assignment
} else if (sqlite3_strnicmp(sql, "SET", 3) == 0 && sqlite3Isspace(sql[3])) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_SET, &sql);
// if the SQL command starts with "RETURN", then it is a return statement
} else if (sqlite3_strnicmp(sql, "RETURN", 6) == 0) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_RETURN, &sql);
// if the SQL command starts with "RAISE", then it is a raise statement
} else if (sqlite3_strnicmp(sql, "RAISE", 5) == 0) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_RAISE, &sql);
// process IF, ELSEIF, ELSE and END IF
} else if (sqlite3_strnicmp(sql, "IF", 2) == 0 && sqlite3Isspace(sql[2])) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_IF, &sql);
} else if (sqlite3_strnicmp(sql, "ELSEIF", 6) == 0 && sqlite3Isspace(sql[6])) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_ELSEIF, &sql);
} else if (sqlite3_strnicmp(sql, "ELSE", 4) == 0 && sqlite3Isspace(sql[4])) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_ELSE, &sql);
} else if (sqlite3_strnicmp(sql, "END IF;", 7) == 0) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_ENDIF, &sql);
// process LOOP, ENDLOOP, BREAK, CONTINUE and FOREACH
} else if (sqlite3_strnicmp(sql, "LOOP", 4) == 0 && sqlite3Isspace(sql[4])) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_LOOP, &sql);
} else if (sqlite3_strnicmp(sql, "END LOOP;", 9) == 0) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_ENDLOOP, &sql);
} else if (sqlite3_strnicmp(sql, "BREAK", 5) == 0 && !sqlite3Isalpha(sql[5])) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_BREAK, &sql);
} else if (sqlite3_strnicmp(sql, "CONTINUE", 8) == 0 && !sqlite3Isalpha(sql[8])) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_CONTINUE, &sql);
} else if (sqlite3_strnicmp(sql, "FOREACH", 7) == 0 && sqlite3Isspace(sql[7])) {
rc = parse_new_command(pParse, procedure, CMD_TYPE_FOREACH, &sql);
// if the statement is just "END", then it is the end of the procedure
} else if (sqlite3_strnicmp(sql, "END", 3) == 0 && !sqlite3Isalpha(sql[3])) {
break;
// if the SQL command is not one of the above, then it is a SQL statement
} else {
int pos = new_command(procedure, CMD_TYPE_STATEMENT);
if (pos < 0) return SQLITE_NOMEM;
command* cmd = &procedure->cmds[pos];
// save the SQL statement
cmd->sql = sql;
cmd->nsql = skip_sql_command(&sql);
}
if (rc != SQLITE_OK) {
if (procedure->error_msg != NULL) {
// if an error occurred, set the error message and return
sqlite3ErrorMsg(pParse, "%s", procedure->error_msg);
// release the memory allocated for the error message
sqlite3_free(procedure->error_msg);
procedure->error_msg = NULL;
}
// exit the loop
goto loc_exit;
}
// skip whitespaces
while (sqlite3Isspace(*sql)) sql++;
}
#ifdef SQLITE_DEBUG
// print the list of commands
for (int i = 0; i < procedure->num_cmds; i++) {
command* cmd = &procedure->cmds[i];
printf("command type: %s\n", command_type_str(cmd->type));
if (cmd->sql) {
printf("\tSQL: %.*s\n", cmd->nsql, cmd->sql);
}
}
#endif
loc_exit:
// return the remaining SQL
*psql = sql;
return rc;
}
/*
** Parses a list of variables separated by comma, optionally containing a type.
** Used in these cases:
** - procedure parameters: (@name TEXT, @value INT)
** - SET statement: SET @name, @value = ...
** - DECLARE statement: DECLARE @name, @value
** - RETURN statement: RETURN @name, @value
** - FOREACH statement: FOREACH @name, @value IN ...
*/
SQLITE_PRIVATE int parse_variables_list(
stored_proc* procedure,
int cmd_pos,
char** psql,
unsigned int *pnum_vars,
sqlite3_var **pvar_list
){
char* sql = *psql;
int rc = SQLITE_OK;
int num_vars = 0;
int n;
int tokenType;
sqlite3_var *varList=NULL, *lastVar=NULL, *var, *v;
bool expect_type = false;
/* can it contain a variable type? */
if( cmd_pos==VAR_POS_PARAMETER || procedure->cmds[cmd_pos].type==CMD_TYPE_DECLARE ){
/* yes */
expect_type = true;
}
// iterate over the list of variables and clear the nextUsed pointer
for(var=procedure->vars; var; var=var->next){
var->nextUsed = NULL;
}
while (sql && *sql) {
/* skip spaces */
while( sqlite3Isspace(*sql) ) sql++;
/* parse the variable name */
n = sqlite3GetToken((u8*)sql, &tokenType);
if( tokenType!=TK_VARIABLE ){
goto loc_invalid_token;
}
//name = sql;
//name_len = n;
//sql += n;
/* create a new variable or retrieve existing */
//var = addVariable(procedure, cmd_pos, sql, n, NULL);
var = addVariable(procedure, sql, n, 0, NULL);
if( !var ) return SQLITE_ERROR;
/* check if already on the list of used variables */
for( v=varList; v; v=v->nextUsed ){
if( v==var ){
procedure->error_msg = sqlite3_mprintf("variable can only be used once: %s", v->name);
goto loc_invalid_token;
}
}
/* add it to the list of used variables */
var->nextUsed = NULL;
if( lastVar )
lastVar->nextUsed = var;
else
varList = var;
lastVar = var;
num_vars++;
/* skip the variable name */
sql += n;
/* skip spaces */
while( sqlite3Isspace(*sql) ) sql++;
/* parse the next token */