forked from georgebarwood/Database
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSqlExec.cs
1314 lines (1189 loc) · 36.4 KB
/
SqlExec.cs
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
namespace SQLNS
{
using G = System.Collections.Generic;
using DBNS;
abstract class Exec // This allows for alternates to SQL in principle ( although none are anticipated ).
{
public abstract void Error( string Message );
public abstract TableExpression LoadView( string source, string viewname );
}
class SqlExec : Exec // Parses and Executes ( Interprets ) SQL.
{
public static void ExecuteBatch( string sql, DatabaseImp d, ResultSet rs )
{
// System.Console.WriteLine("Sql: " + sql );
new SqlExec( sql, d, null ).Batch( rs );
}
public static Block LoadRoutine( bool func, string sql, DatabaseImp d, string name )
{
SqlExec e = new SqlExec( sql, d, name );
e.B = new Block( d, func );
e.B.Params = e.RoutineDef( func, out e.B.ReturnType );
return e.B;
}
public override TableExpression LoadView( string source, string viewname )
{
SqlExec e = new SqlExec( source, Db, viewname );
e.B = new Block( Db, false );
return e.ViewDef();
}
public override void Error( string error )
{
throw new Exception( RoutineName, SourceLine, SourceColumn, error,
Source.Substring( TokenStart, TokenStop - TokenStart ), Source, T );
}
public DatabaseImp Db;
public ColInfo CI; // Associated with current table scope.
public bool [] Used; // Which columns in CI have been referenced in an expression.
public Block B;
// Rest is private
string Source; // The source SQL
string RoutineName; // The name of the routine being parsed ( null if batch statements are being parsed ).
int SourceIx = -1; // Index of current character in Source
int SourceLine = 1; // Current line number
int SourceColumn = 0; // Current column number
char CC; // Current character in Source as it is being parsed.
Token T; // Current token.
int TokenStart, TokenStop; // Position in source of start and end of current token.
string NS,TS; // Current name token : TS is uppercase copy of NS.
long DecimalInt, DecimalFrac; // Details of decimal token
int DecimalScale;
public bool ParseOnly; // True when parsing CREATE FUNCTION or CREATE PROCEDURE.
bool DynScope; // When parsing SELECT or WHERE clauses, suppresses name lookup/type checking.
int BreakId = -1; // Break label id for current WHILE or FOR statement.
SqlExec( string sql, DatabaseImp db, string routineName )
{
Source = sql;
Db = db;
RoutineName = routineName;
ReadChar();
ReadToken();
}
void Batch( ResultSet rs )
{
B = new Block( Db, false );
while ( T != Token.Eof ) Statement();
B.AllocLocalValues( this );
B.ExecuteStatements( rs );
}
void Add( System.Action a )
{
if ( !ParseOnly ) B.Statements.Add( a );
}
// ****************** Token parsing
void ReadChar()
{
SourceIx += 1;
CC = ( SourceIx >= Source.Length ) ? '\0' : Source[ SourceIx ];
if ( CC == '\n' ) { SourceColumn = 0; SourceLine += 1; } else SourceColumn += 1;
}
void ReadToken()
{
SkipSpace:
while ( CC == ' ' || CC == '\n' || CC == '\r' ) ReadChar();
TokenStart = SourceIx;
if ( CC >= 'A' && CC <= 'Z' || CC >= 'a' && CC <= 'z' || CC == '@' )
{
T = Token.Name;
ReadChar();
while ( CC >= 'A' && CC <= 'Z' || CC >= 'a' && CC <= 'z' || CC == '@' ) ReadChar();
TokenStop = SourceIx;
NS = Source.Substring( TokenStart, TokenStop - TokenStart );
TS = NS.ToUpper();
}
else if ( CC >= '0' && CC <= '9' )
{
char fc = CC;
T = Token.Number;
ReadChar();
if ( fc == '0' && CC == 'x' )
{
ReadChar();
T = Token.Hex;
while ( CC >= '0' && CC <= '9' || CC >= 'A' && CC <= 'F' || CC >= 'a' && CC <= 'f') ReadChar();
}
else
{
while ( CC >= '0' && CC <= '9' ) ReadChar();
int part1 = SourceIx;
DecimalInt = long.Parse( Source.Substring( TokenStart, part1 - TokenStart ) );
if ( CC == '.' && T == Token.Number )
{
T = Token.Decimal;
ReadChar();
while ( CC >= '0' && CC <= '9' ) ReadChar();
DecimalScale = SourceIx - ( part1 + 1 );
DecimalFrac = long.Parse( Source.Substring( part1 + 1, DecimalScale ) );
}
else
{
DecimalScale = 0;
DecimalFrac = 0;
}
}
TokenStop = SourceIx;
NS = Source.Substring( TokenStart, TokenStop - TokenStart );
}
else if ( CC == '[' )
{
T = Token.Name;
ReadChar();
int start = SourceIx; NS = "";
while ( CC != '\0' )
{
if ( CC == ']' )
{
ReadChar();
if ( CC != ']' ) break;
NS = NS + Source.Substring( start, SourceIx-start-1 );
start = SourceIx;
}
ReadChar();
}
TokenStop = SourceIx;
NS = NS + Source.Substring( start, SourceIx-start-1 );
TS = NS.ToUpper();
}
else if ( CC == '\'' )
{
T = Token.String;
ReadChar();
int start = SourceIx; NS = "";
while ( CC != '\0' )
{
if ( CC == '\'' )
{
ReadChar();
if ( CC != '\'' ) break;
NS = NS + Source.Substring( start, SourceIx-start-1 );
start = SourceIx;
}
ReadChar();
}
TokenStop = SourceIx;
NS = NS + Source.Substring( start, SourceIx-start-1 );
}
else
{
if ( CC == '(' ) T = Token.LBra;
else if ( CC == ')' ) T = Token.RBra;
else if ( CC == ',' ) T = Token.Comma;
else if ( CC == '.' ) T = Token.Dot;
else if ( CC == ':' ) T = Token.Colon;
else if ( CC == '>' ) T = Token.Greater;
else if ( CC == '<' ) T = Token.Less;
else if ( CC == '+' ) T = Token.Plus;
else if ( CC == '|' ) T = Token.VBar;
else if ( CC == '-' ) T = Token.Minus;
else if ( CC == '*' ) T = Token.Times;
else if ( CC == '/' ) T = Token.Divide;
else if ( CC == '%' ) T = Token.Percent;
else if ( CC == '=' ) T = Token.Equal;
else if ( CC == '!' ) T = Token.Exclamation;
else if ( CC == '\0' ) { T = Token.Eof; TokenStop = SourceIx; return; }
else { ReadChar(); TokenStop = SourceIx; T = Token.Unknown; Error( "Unrecognised character" ); }
ReadChar();
// The processing below could be more efficient if moved into sections above.
if ( CC == '=' && ( T == Token.Greater || T == Token.Less || T == Token.Exclamation ) )
{
T = T == Token.Greater ? Token.GreaterEqual
: T == Token.Exclamation ? Token.NotEqual
: Token.LessEqual;
ReadChar();
}
else if ( CC == '>' && T == Token.Less )
{
T = Token.NotEqual;
ReadChar();
}
else if ( T == Token.Divide && CC == '*' )
{
// Skip comment
ReadChar();
char prevchar = 'X';
while ( ( CC != '/' || prevchar != '*' ) && CC != '\0' )
{
prevchar = CC;
ReadChar();
}
ReadChar();
goto SkipSpace;
}
else if ( T == Token.Minus && CC == '-' )
{
while ( CC != '\n' && CC != '\0' ) ReadChar();
goto SkipSpace;
}
TokenStop = SourceIx;
}
}
// ****************** Help functions for parsing.
DataType GetExactDataType( string tname )
{
switch ( tname )
{
case "int" : return DataType.Int;
case "string" : return DataType.String;
case "binary" : return DataType.Binary;
case "tinyint" : return DataType.Tinyint;
case "smallint" : return DataType.Smallint;
case "bigint" : return DataType.Bigint;
case "float" : return DataType.Float;
case "double" : return DataType.Double;
case "bool" : return DataType.Bool;
case "decimal" :
int p = 18; int s = 0;
if ( Test( Token.LBra ) )
{
p = ReadInt();
if ( p < 1 ) Error( "Minimum precision is 1" );
if ( p > 18 ) Error( "Maxiumum decimal precision is 18" );
if ( Test( Token.Comma) ) s = ReadInt();
if ( s < 0 ) Error( "Scale cannot be negative" );
if ( s > p ) Error( "Scale cannot be greater than precision" );
Read( Token.RBra );
}
return DTI.Decimal( p, s );
default: Error( "Datatype expected" ); return DataType.None;
}
}
DataType GetDataType( string s )
{
return DTI.Base( GetExactDataType( s ) );
}
Token GetOperator( out int prec )
{
Token result = T;
if ( result >= Token.Name )
{
if ( result == Token.Name )
{
if ( TS == "AND" ) result = Token.And;
else if ( TS == "OR" ) result = Token.Or;
else if ( TS == "IN" ) result = Token.In;
else { prec = -1; return result; }
}
else { prec = -1; return result; }
}
prec = TokenInfo.Precedence[(int)result];
return result;
}
string Name()
{
if ( T != Token.Name ) Error ("Name expected");
string result = NS;
ReadToken();
return result;
}
bool Test( Token t )
{
if ( T != t ) return false;
ReadToken();
return true;
}
int ReadInt()
{
if ( T != Token.Number ) Error( "Number expected" );
int result = int.Parse(NS);
ReadToken();
return result;
}
void Read( Token t )
{
if ( T != t ) Error ( "Expected \"" + TokenInfo.Name( t ) + "\"" );
ReadToken();
}
bool Test( string t )
{
if ( T != Token.Name || TS != t ) return false;
ReadToken();
return true;
}
void Read( string t )
{
if ( T != Token.Name || TS != t ) Error( "Expected " + t );
ReadToken();
}
// End Help functions for parsing.
// ****************** Expression parsing
Exp NameExp( bool AggAllowed )
{
Exp result = null;
string name = NS;
ReadToken();
if ( Test(Token.Dot) )
{
string fname = Name();
var parms = new G.List<Exp>();
Read( Token.LBra );
if ( T != Token.RBra) do
{
parms.Add( Exp() );
} while ( Test( Token.Comma ) );
Read( Token.RBra );
result = new ExpFuncCall( name, fname, parms );
}
else if ( Test( Token.LBra ) )
{
var parms = new G.List<Exp>();
if ( T != Token.RBra) do
{
parms.Add( Exp() );
} while ( Test( Token.Comma ) );
Read( Token.RBra );
if ( AggAllowed && name == "COUNT" )
{
if ( parms.Count > 0 ) Error( "COUNT does have any parameters" );
result = new COUNT();
}
else if ( AggAllowed && name == "SUM" ) result = new ExpAgg( AggOp.Sum, parms, this );
else if ( AggAllowed && name == "MIN" ) result = new ExpAgg( AggOp.Min, parms, this );
else if ( AggAllowed && name == "MAX" ) result = new ExpAgg( AggOp.Max, parms, this );
else if ( name == "PARSEINT" ) result = new PARSEINT( parms, this );
else if ( name == "PARSEDOUBLE" ) result = new PARSEDOUBLE( parms, this );
else if ( name == "PARSEDECIMAL" ) result = new PARSEDECIMAL( parms, this );
else if ( name == "LEN" ) result = new LEN( parms, this );
else if ( name == "REPLACE" ) result = new REPLACE( parms, this );
else if ( name == "SUBSTRING" ) result = new SUBSTRING( parms, this );
else if ( name == "EXCEPTION" ) result = new EXCEPTION( parms, this );
else if ( name == "LASTID" ) result = new LASTID( parms, this );
else if ( name == "ARG" ) result = new ARG( parms, this );
else if ( name == "FILEATTR" ) result = new FILEATTR( parms, this );
else if ( name == "FILECONTENT" ) result = new FILECONTENT( parms, this );
else Error( "Unknown function : " + name );
}
else if ( name == "true" ) result = new ExpConstant(true);
else if ( name == "false" ) result = new ExpConstant(false);
else
{
int i = B.Lookup( name );
if ( i < 0 )
{
if ( DynScope )
result = new ExpName( name );
else
Error( "Undeclared local : " + name );
}
else result = new ExpLocalVar( i, B.LocalType[i] );
}
return result;
}
Exp Primary( bool AggAllowed )
{
Exp result = null;
if ( T == Token.Name )
{
result =
Test( "CASE" ) ? Case()
: Test( "NOT" ) ? new ExpNot( Exp(10) ) // Not sure about precedence here.
: NameExp( AggAllowed );
}
else if ( Test( Token.LBra ) )
{
if ( Test( "SELECT" ) )
result = ScalarSelect();
else
{
result = Exp();
if ( Test( Token.Comma ) ) // Operand of IN e.g. X IN ( 1,2,3 )
{
var list = new G.List<Exp>();
list.Add( result );
do
{
list.Add( Exp() );
} while ( Test( Token.Comma ) );
result = new ExpList( list );
}
}
Read( Token.RBra );
}
else if ( T == Token.String )
{
result = new ExpConstant( NS );
ReadToken();
}
else if ( T == Token.Number || T == Token.Decimal )
{
long value = DecimalInt;
if ( DecimalScale > 0 ) value = value * (long)Util.PowerTen( DecimalScale ) + DecimalFrac;
result = new ExpConstant( value, DecimalScale > 0 ? DTI.Decimal( 18, DecimalScale ) : DataType.Bigint );
ReadToken();
}
else if ( T == Token.Hex )
{
if ( ( NS.Length & 1 ) != 0 ) Error( "Hex literal must have even number of characters" );
result = new ExpConstant( Util.ParseHex(NS) );
ReadToken();
}
else if ( Test( Token.Minus ) )
{
result = new ExpMinus( Exp( 30 ) );
}
else Error( "Expression expected" );
return result;
}
Exp ExpOrAgg()
{
Exp result = Exp( Primary( true ), 0 );
if ( !ParseOnly && !DynScope ) result.Bind( this );
return result;
}
Exp Exp()
{
return Exp(0);
}
Exp Exp( int prec )
{
Exp result = Exp( Primary( false ), prec );
if ( !ParseOnly && !DynScope ) result.Bind( this );
return result;
}
Exp Exp( Exp lhs, int precedence )
{
int prec_t; Token t = GetOperator( out prec_t );
while ( prec_t >= precedence )
{
int prec_op = prec_t; Token op = t;
ReadToken();
Exp rhs = Primary( false );
t = GetOperator( out prec_t );
while ( prec_t > prec_op /* or t is right-associative and prec_t == prec_op */ )
{
rhs = Exp( rhs, prec_t );
t = GetOperator( out prec_t );
}
lhs = BinaryOp( op, lhs, rhs );
}
return lhs;
}
Exp BinaryOp( Token op, Exp lhs, Exp rhs )
{
if ( op == Token.In )
return new ExpIn( lhs, rhs );
else
return new ExpBinary( op, lhs, rhs );
}
Exp Case()
{
var list = new G.List<CASE.Part>();
while ( Test( "WHEN" ) )
{
Exp test = Exp(); Read( "THEN" ); Exp e = Exp();
list.Add( new CASE.Part( test, e ) );
}
if ( list.Count == 0 ) Error( "Empty Case Expression" );
Read( "ELSE" );
list.Add( new CASE.Part( null, Exp() ) );
Read( "END" );
return new CASE( list.ToArray() );
}
Exp ScalarSelect()
{
TableExpression te = Expressions( null );
if ( te.ColumnCount != 1 ) Error ( "Scalar select must have one column" );
return new ScalarSelect( te );
}
// ****************** Table expression parsing
TableExpression InsertExpression()
{
if ( Test( "VALUES" ) ) return Values();
else if ( Test( "SELECT") ) return Expressions( null );
else Error( "VALUES or SELECT expected" );
return null;
}
TableExpression Values()
{
var values = new G.List<Exp[]>();
DataType [] types = null;
while ( true )
{
Read( Token.LBra );
var v = new G.List<Exp>();;
while ( true )
{
v.Add( Exp() );
if ( Test( Token.RBra ) ) break;
if ( T != Token.Comma ) Error( "Comma or closing bracket expected" );
ReadToken();
}
if ( types == null )
{
types = new DataType[ v.Count ];
for ( int i = 0; i < v.Count; i += 1 ) types[ i ] = v[i].Type;
}
else
{
if ( types.Length != v.Count ) Error( "Inconsistent number of values" );
}
values.Add( v.ToArray() );
if ( !Test( Token.Comma ) && T != Token.LBra ) break; // The comma between multiple VALUES is optional.
}
return new ValueTable( types.Length, values );
}
TableExpression Expressions( G.List<int> locals )
{
// locals has the indexes of local variables being assigned in a SET or FOR statement.
bool save = DynScope; DynScope = true; // Suppresses Binding of expressions until table is known.
var exps = new G.List<Exp>();
do
{
if ( locals != null )
{
var name = Name();
int i = B.Lookup( name );
if ( i < 0 ) Error( "Undeclared local variable : " + name );
Read( Token.Equal );
if ( locals.Contains( i ) ) Error( "Duplicated local name in SET or FOR" );
locals.Add( i );
}
Exp exp = ExpOrAgg();
if ( Test( "AS" ) ) exp.Name = Name();
exps.Add( exp );
} while ( Test( Token.Comma ) );
TableExpression te = Test( "FROM" ) ? PrimaryTableExp() : new DummyFrom();
te.CheckNames( this );
Exp where = Test( "WHERE" ) ? Exp() : null;
Exp[] group = null;
if ( Test( "GROUP" ) )
{
var list = new G.List<Exp>();
Read( "BY" );
do
{
Exp exp = Exp();
if ( Test( "AS" ) ) exp.Name = Name();
list.Add( exp );
} while ( Test( Token.Comma ) );
group = list.ToArray();
}
OrderByExp[] order = OrderBy();
DynScope = save;
TableExpression result;
if ( !ParseOnly )
{
var save1 = Used; var save2 = CI;
te = te.Load( this );
CI = te.Cols;
Used = new bool[ CI.Count ]; // Bitmap of columns that are referenced by any expression.
for ( int i=0; i<exps.Count; i+=1 )
{
if ( exps[i].GetAggOp() != AggOp.None )
{
if ( group == null )
{
if ( i != 0 ) Error( "All exps in aggregate select must be aggregate functions" );
group = new Exp[0];
System.Console.WriteLine("Auto-group");
}
exps[i].BindAgg( this );
}
else
{
if ( group != null ) Error( "All exps in aggregate select must be aggregate functions" );
exps[i].Bind( this );
}
}
if ( where != null && where.Bind( this ) != DataType.Bool )
Error( "WHERE expression must be boolean" );
if ( group != null )
{
for ( int i=0; i<group.Length; i+=1 )
{
group[i].Bind( this );
exps.Add( group[i] );
}
}
result = new Select( exps, te, where, group, order, Used, this );
if ( locals != null )
{
var types = new DataType[ locals.Count ];
for ( int i = 0; i < locals.Count; i += 1 )
types[i] = B.LocalType[ locals[i] ];
result.Convert( types, this );
}
Used = save1; CI = save2;
}
else result = new Select( exps, te, where, group, order, null, this ); // Potentially used by CheckNames
return result;
}
ViewOrTable TableName()
{
if ( T == Token.Name )
{
var n1 = NS;
ReadToken();
if ( T == Token.Dot )
{
ReadToken();
if ( T == Token.Name )
return new ViewOrTable( n1, Name() );
}
}
Error( "Table or view name expected" );
return null;
}
TableExpression PrimaryTableExp()
{
if ( T == Token.Name ) return TableName();
else if ( Test( Token.LBra ) )
{
Read( "SELECT" );
TableExpression te = Expressions( null );
Read( Token.RBra );
if ( Test("AS") ) te.Alias = Name();
return te;
}
Error( "Table expected" );
return null;
}
OrderByExp [] OrderBy()
{
if ( Test( "ORDER" ) )
{
var list = new G.List<OrderByExp>();
Read("BY");
do
{
list.Add( new OrderByExp( Exp(), Test("DESC") ) );
} while ( Test( Token.Comma) );
return list.ToArray();
}
return null;
}
// ****************** Statement parsing
TableExpression Select( bool exec )
{
var te = Expressions( null );
if ( exec ) Add( () => B.ExecuteSelect( te, null ) );
return te;
}
void Set()
{
var locals = new G.List<int>();
var te = Expressions( locals );
Add( () => B.ExecuteSelect( te, locals.ToArray() ) );
}
void Insert()
{
Read( "INTO" );
string schema = Name();
Read( Token.Dot );
string tableName = Name();
Read( Token.LBra );
var names = new G.List<string>();
while ( true )
{
string name = Name();
if ( names.Contains( name ) ) Error( "Duplicate name in insert list" );
names.Add( name );
if ( Test( Token.RBra ) ) break;
if ( T != Token.Comma ) Error( "Comma or closing bracket expected" );
ReadToken();
}
TableExpression src = InsertExpression();
if ( src.ColumnCount != names.Count ) Error( "Insert count mismatch" );
if ( !ParseOnly )
{
var t = Db.GetTable( schema, tableName, this );
int[] colIx = new int[names.Count];
int idCol = -1;
var types = new DataType[ names.Count ];
for ( int i=0; i < names.Count; i += 1 )
{
int ci = t.ColumnIx( names[i], this );
if ( ci == 0 ) idCol = i;
colIx[i] = ci;
types[i] = t.Cols.Types[ ci ];
}
src.Convert( types, this );
Add( () => B.ExecInsert( t, src, colIx, idCol ) );
}
}
void Update()
{
bool save = DynScope; DynScope = true;
var te = TableName();
Read( "SET" );
var alist = new G.List<Assign>();
do
{
var name = Name();
Read( Token.Equal );
var exp = Exp();
alist.Add( new Assign( name, exp ) );
} while ( Test( Token.Comma ) );
var a = alist.ToArray();
var where = Test( "WHERE" ) ? Exp() : null;
if ( where == null ) Error( "UPDATE must have a WHERE" );
DynScope = save;
if ( !ParseOnly )
{
Table t = Db.GetTable( te.Schema, te.Name, this );
var save1 = Used; var save2 = CI;
Used = new bool[ t.Cols.Count ]; // Bitmap of columns that are referenced by any expression.
CI = t.Cols;
int idCol = -1;
for ( int i=0; i < a.Length; i += 1 )
{
if ( a[i].Lhs.Bind( this ) != a[i].Rhs.Bind( this ) )
{
Exp conv = a[i].Rhs.Convert( a[i].Lhs.Type );
if ( conv == null ) Error( "Update type mismatch" );
else a[i].Rhs = conv;
}
if ( a[i].Lhs.ColIx == 0 ) idCol = i;
}
if ( where != null && where.Bind( this ) != DataType.Bool )
Error( "WHERE expression must be boolean" );
var used = Used; // Need to take a copy
Add( () => t.ExecUpdate( a, where, used, idCol, B ) );
Used = save1; CI = save2;
}
}
void Delete()
{
bool save = DynScope; DynScope = true;
Read( "FROM" );
var te = TableName();
Exp where = Test( "WHERE" ) ? Exp() : null;
if ( where == null ) Error( "DELETE must have a WHERE" );
DynScope = save;
if ( !ParseOnly )
{
Table t = Db.GetTable( te.Schema, te.Name, this );
var save1 = Used; var save2 = CI;
Used = new bool[ t.Cols.Count ]; // Bitmap of columns that are referenced by any expression.
CI = t.Cols;
if ( where != null && where.Bind( this ) != DataType.Bool )
Error( "WHERE expression must be boolean" );
var used = Used; // Need to take a copy.
Add( () => t.ExecDelete( where, used, B ) );
Used = save1; CI = save2;
}
}
void Execute()
{
Read( Token.LBra );
var exp = Exp();
Read( Token.RBra );
if ( !ParseOnly )
{
if ( exp.Type != DataType.String ) Error( "Argument of EXECUTE must be a string" );
Add( () => B.Execute( exp ) );
}
}
void Exec()
{
string name = Name();
string schema = null;
if ( Test( Token.Dot ) )
{
schema = name;
name = Name();
}
Read( Token.LBra );
var parms = new G.List<Exp>();
if ( !Test( Token.RBra ) )
{
parms.Add( Exp() );
while ( Test( Token.Comma ) ) parms.Add( Exp() );
Read( Token.RBra );
}
if ( schema != null )
{
if ( !ParseOnly )
{
var b = Db.GetRoutine( schema, name, false, this );
// Check parameter types.
if ( b.Params.Count != parms.Count ) Error( "Param count error calling " + name + "." + name );
for ( int i = 0; i < parms.Count; i += 1 )
if ( parms[i].Type != b.Params.Types[i] )
Error( "Parameter Type Error calling procedure " + name );
Add( () => B.ExecProcedure( b, parms, this ) );
}
}
else if ( name == "SETMODE" )
{
if ( !ParseOnly && ( parms.Count != 1 || parms[0].Bind( this ) != DataType.Bigint ) )
Error( "SETMODE param error" );
Add( () => B.SetMode( parms[0] ) );
}
else Error( "Unrecognised procedure" );
}
void For()
{
var locals = new G.List<int>();
TableExpression te = Expressions( locals );
int forid = B.GetForId();
Add( () => B.InitFor( forid, te, locals.ToArray() ) );
int start = B.GetHere();
int breakid = B.GetJumpId();
Add( () => B.ExecuteFor( forid, breakid ) );
int save = BreakId;
BreakId = breakid;
Statement();
BreakId = save;
Add( () => B.JumpBack( start ) );
B.SetJump( breakid );
}
// ****************** Create Statements
void CreateTable()
{
string schema = Name();
Read( Token.Dot );
string tableName = Name();
int sourceStart = SourceIx-1;
Read( Token.LBra );
var names = new G.List<string>();
var types = new G.List<DataType>();
while ( true )
{
var name = Name();
if ( names.Contains( name ) ) Error ( "Duplicate column name" );
names.Add( name );
types.Add( GetExactDataType( Name() ) );
if ( Test( Token.RBra ) ) break;
if ( T != Token.Comma ) Error( "Comma or closing bracket expected" );
ReadToken();
}
string source = Source.Substring( sourceStart, TokenStart - sourceStart );
Add( () => Db.CreateTable( schema, tableName, ColInfo.New( names, types ), source, false, false, this ) );
}
void CreateView( bool alter )
{
string schema = Name();
Read( Token.Dot );
string viewName = Name();
Read( "AS" );
int sourceStart = TokenStart;
Read( "SELECT" );
var save = ParseOnly;
ParseOnly = true;
var se = Select( false );
ParseOnly = save;
se.CheckNames( this );
string source = Source.Substring( sourceStart, TokenStart - sourceStart );
Add( () => Db.CreateTable( schema, viewName, se.Cols, source, true, alter, this ) );
}
TableExpression ViewDef()
{
Read( "SELECT" );
return Select( false );
}
void CreateRoutine( bool func, bool alter )
{
string schema = Name();
Read( Token.Dot );
string funcName = Name();
int sourceStart = SourceIx-1;
Block save1 = B; bool save2 = ParseOnly;
B = new Block( B.Db, func ); ParseOnly = true;
DataType retType; var parms = RoutineDef( func, out retType );
B = save1; ParseOnly = save2;
string source = Source.Substring( sourceStart, TokenStart - sourceStart );
Add( () => Db.CreateRoutine( schema, funcName, source, func, alter, this ) );
}
ColInfo RoutineDef( bool func, out DataType retType )
{
var names = new G.List<string>();
var types = new G.List<DataType>();
Read( Token.LBra );
while ( T == Token.Name )
{
string name = Name();
DataType type = GetDataType( Name() );
names.Add( name );
types.Add( type );
B.Declare( name, type );
if ( T == Token.RBra ) break;
if ( T != Token.Comma ) Error( "Comma or closing bracket expected" );
ReadToken();
}