-
Notifications
You must be signed in to change notification settings - Fork 35
/
BaseGrammar.cfc
1336 lines (1174 loc) · 39.8 KB
/
BaseGrammar.cfc
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
import qb.models.Query.QueryBuilder;
import qb.models.Query.QueryUtils;
/**
* Grammar represents a platform to run sql on.
*
* This is the Base Grammar that other grammars can extend to modify
* the generated sql for their specific platforms.
*/
component displayname="Grammar" accessors="true" {
/**
* ColdBox Interceptor Service to announce pre- and post- interception points
* This is not injected since we need to determine if we are in CommandBox or ColdBox first.
* This is handled in the ModuleConfig file
*/
property name="interceptorService";
/**
* LogBox logger to log out SQL and bindings.
* If this is not a ColdBox application, a NullLogger will be created in the constructor.
*/
property name="log" inject="logbox:logger:{this}";
/**
* Query utilities shared across multiple models.
*/
property name="utils";
/**
* Global table prefix for the grammar.
*/
property name="tablePrefix" type="string" default="";
/**
* The different components of a select statement in the order of compilation.
*/
variables.selectComponents = [
"commonTables", "aggregate", "columns", "from", "joins", "wheres",
"groups", "havings", "unions", "orders", "limitValue", "offsetValue"
];
/**
* Creates a new basic Query Grammar.
*
* @utils A collection of query utilities. Default: qb.models.Query.QueryUtils
*
* @return qb.models.Grammars.BaseGrammar
*/
public BaseGrammar function init(
QueryUtils utils = new qb.models.Query.QueryUtils()
) {
variables.utils = arguments.utils;
variables.tablePrefix = "";
// These are overwritten by WireBox, if it exists.
variables.interceptorService = new qb.models.compat.NullInterceptorService();
variables.log = new qb.models.compat.NullLogger();
return this;
}
/**
* Runs a query through `queryExecute`.
* This function exists so that platform-specific grammars can override it if needed.
*
* @sql The sql string to execute.
* @bindings The bindings to apply to the query.
* @options Any options to pass to `queryExecute`. Default: {}.
*
* @return any
*/
public any function runQuery( sql, bindings, options, returnObject = "query" ) {
local.result = "";
var data = duplicate( arguments );
tryPreInterceptor( data );
structAppend( options, { result = "local.result" }, true );
log.debug( "Executing sql: #sql#", "With bindings: #serializeJSON( bindings )#" );
var q = queryExecute( sql, bindings, options );
data.query = isNull( q ) ? javacast( "null", "" ) : q;
data.result = local.result;
tryPostInterceptor( data );
return returnObject == "query" ? q : { result = local.result, query = q };
}
/**
* This method exists because the API for InterceptorService differs between ColdBox and CommandBox
*/
private function tryPreInterceptor( data ) {
if ( structKeyExists( application, "applicationName" ) && application.applicationName == "CommandBox CLI" ) {
variables.interceptorService.announceInterception( "preQBExecute", data );
return;
}
variables.interceptorService.processState( "preQBExecute", data );
return;
}
/**
* This method exists because the API for InterceptorService differs between ColdBox and CommandBox
*/
private function tryPostInterceptor( data ) {
if ( structKeyExists( application, "applicationName" ) && application.applicationName == "CommandBox CLI" ) {
variables.interceptorService.announceInterception( "postQBExecute", data );
return;
}
variables.interceptorService.processState( "postQBExecute", data );
return;
}
/**
* Compile a Builder's query into a sql string.
*
* @query The Builder instance.
*
* @return string
*/
public string function compileSelect( required QueryBuilder query ) {
var sql = [];
for ( var component in selectComponents ) {
var func = variables[ "compile#component#" ];
var args = {
"query" = query,
"#component#" = invoke( query, "get" & component )
};
arrayAppend( sql, func( argumentCollection = args ) );
}
return trim( concatenate( sql ) );
}
/**
* Compiles the Common Table Expressions (CTEs).
*
* @query The Builder instance.
* @columns The selected columns.
*
* @return string
*/
private string function compileCommonTables(
required QueryBuilder query,
required array commonTables
) {
return getCommonTableExpressionSQL(arguments.query, arguments.commonTables);
}
/**
* Compiles the Common Table Expressions (CTEs).
*
* @query The Builder instance.
* @columns The selected columns.
* @supportsRecursiveKeyword Determines if the current grammar requires the RECURSIVE keyword if any CTEs are recursive.
*
* @return string
*/
private string function getCommonTableExpressionSQL(
required query,
required array commonTables,
boolean supportsRecursiveKeyword=true
) {
if ( arguments.commonTables.isEmpty() ) {
return "";
}
var hasRecursion = false;
var sql = arguments.commonTables.map(function (commonTable){
var sql = arguments.commonTable.query.toSQL();
// generate the optional column definition
var columns = arguments.commonTable.columns.map(function (value){
return wrapColumn(arguments.value);
}).toList();
// we need to track if any of the CTEs are recursive
if( arguments.commonTable.recursive ){
hasRecursion = true;
}
return wrapColumn(arguments.commonTable.name) & (len(columns) ? " " & columns : "") & " AS (" & sql & ")";
});
/*
Most implementations of CTE require the RECURSIVE keyword if *any* single CTE uses recursive,
but some grammars, like SQL Server, does not support the keyword (as it's not necessary).
*/
return trim( "WITH " & (arguments.supportsRecursiveKeyword && hasRecursion ? "RECURSIVE " : "") & sql.toList(', ') );
}
/**
* Compiles the columns portion of a sql statement.
*
* @query The Builder instance.
* @columns The selected columns.
*
* @return string
*/
private string function compileColumns(
required QueryBuilder query,
required array columns
) {
if ( ! query.getAggregate().isEmpty() ) {
return "";
}
var select = query.getDistinct() ? "SELECT DISTINCT " : "SELECT ";
return select & columns.map( wrapColumn ).toList( ", " );
}
/**
* Compiles the table portion of a sql statement.
*
* @query The Builder instance.
* @from The selected table.
*
* @return string
*/
private string function compileFrom(
required QueryBuilder query,
required any from
) {
return "FROM " & wrapTable( from );
}
/**
* Compiles the joins portion of a sql statement.
*
* @query The Builder instance.
* @joins The selected joins.
*
* @return string
*/
private string function compileJoins(
required QueryBuilder query,
required array joins
) {
var joinsArray = [];
for ( var join in arguments.joins ) {
var conditions = compileWheres( join, join.getWheres() );
var table = wrapTable( join.getTable() );
joinsArray.append( "#uCase( join.getType() )# JOIN #table# #conditions#" );
}
return arrayToList( joinsArray, " " );
}
/**
* Compiles the where portion of a sql statement.
*
* @query The Builder instance.
* @wheres The where clauses.
*
* @return string
*/
private string function compileWheres(
required QueryBuilder query,
array wheres = []
) {
var wheresArray = [];
if ( arguments.wheres.isEmpty() ) {
return "";
}
for ( var where in arguments.wheres ) {
var whereFunc = variables[ "where#where.type#" ];
var sql = uCase( where.combinator ) & " " & whereFunc( query, duplicate( where ) );
wheresArray.append( sql );
}
if ( wheresArray.isEmpty() ) {
return "";
}
var whereList = wheresArray.toList( " " );
var conjunction = query.isJoin() ? "ON" : "WHERE";
return trim( "#conjunction# #removeLeadingCombinator( whereList )#" );
}
/**
* Compiles a basic where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereBasic(
required QueryBuilder query,
required struct where
) {
if ( ! isStruct( where ) ) {
return;
}
where.column = wrapColumn( where.column );
var placeholder = "?";
if ( variables.utils.isExpression( where.value ) ) {
placeholder = where.value.getSql();
}
return trim( "#where.column# #uCase( where.operator )# #placeholder#" );
}
/**
* Compiles a raw where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereRaw(
required QueryBuilder query,
required struct where
) {
return where.sql;
}
/**
* Compiles a column where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereColumn(
required QueryBuilder query,
required struct where
) {
return trim( "#wrapColumn( where.first )# #where.operator# #wrapColumn( where.second )#" );
}
/**
* Compiles a nested where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereNested(
required QueryBuilder query,
required struct where
) {
var sql = compileWheres(
arguments.where.query,
arguments.where.query.getWheres()
);
// cut off the first 7 characters to account for the extra "WHERE"
return trim( "(#mid( sql, 7, len( sql ) - 6 )#)" );
}
/**
* Compiles a subselect where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereSub(
required QueryBuilder query,
required struct where
) {
return "#wrapValue( where.column )# #where.operator# (#compileSelect( where.query )#)";
}
/**
* Compiles an exists where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereExists(
required QueryBuilder query,
required struct where
) {
return "EXISTS (#compileSelect( where.query )#)";
}
/**
* Compiles a not exists where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereNotExists(
required QueryBuilder query,
required struct where
) {
return "NOT EXISTS (#compileSelect( where.query )#)";
}
/**
* Compiles a null where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereNull(
required QueryBuilder query,
required struct where
) {
return "#wrapColumn( where.column )# IS NULL";
}
/**
* Compiles a not null where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereNotNull(
required QueryBuilder query,
required struct where
) {
return "#wrapColumn( where.column )# IS NOT NULL";
}
/**
* Compiles a between where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereBetween(
required QueryBuilder query,
required struct where
) {
return "#wrapColumn( where.column )# BETWEEN ? AND ?";
}
/**
* Compiles a not between where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereNotBetween(
required QueryBuilder query,
required struct where
) {
return "#wrapColumn( where.column )# NOT BETWEEN ? AND ?";
}
/**
* Compiles an in where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereIn(
required QueryBuilder query,
required struct where
) {
var placeholderString = where.values.map( function( value ) {
return variables.utils.isExpression( value ) ? value.getSql() : "?";
} ).toList( ", " );
if ( placeholderString == "" ) {
return "0 = 1";
}
return "#wrapColumn( where.column )# IN (#placeholderString#)";
}
/**
* Compiles a not in where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereNotIn(
required QueryBuilder query,
required struct where
) {
var placeholderString = where.values.map( function( value ) {
return variables.utils.isExpression( value ) ? value.getSql() : "?";
} ).toList( ", " );
if ( placeholderString == "" ) {
return "1 = 1";
}
return "#wrapColumn( where.column )# NOT IN (#placeholderString#)";
}
/**
* Compiles a in subselect where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereInSub(
required QueryBuilder query,
required struct where
) {
return "#wrapColumn( where.column )# IN (#compileSelect( where.query )#)";
}
/**
* Compiles a not in subselect where statement.
*
* @query The Builder instance.
* @where The where clause to compile.
*
* @return string
*/
private string function whereNotInSub(
required QueryBuilder query,
required struct where
) {
return "#wrapColumn( where.column )# NOT IN (#compileSelect( where.query )#)";
}
/**
* Compiles the group by portion of a sql statement.
*
* @query The Builder instance.
* @wheres The group clauses.
*
* @return string
*/
private string function compileGroups( required QueryBuilder query, required array groups ) {
if ( groups.isEmpty() ) {
return "";
}
return trim( "GROUP BY #groups.map( wrapColumn ).toList( ", " )#" );
}
/**
* Compiles the having portion of a sql statement.
*
* @query The Builder instance.
* @havings The having clauses.
*
* @return string
*/
private string function compileHavings( required QueryBuilder query, required array havings ) {
if ( arguments.havings.isEmpty() ) {
return "";
}
var sql = arguments.havings.map( compileHaving );
return trim( "HAVING #removeLeadingCombinator( sql.toList( " " ) )#" );
}
/**
* Compiles a single having clause.
*
* @having The having clauses.
*
* @return string
*/
private string function compileHaving( required struct having ) {
var placeholder = variables.utils.isExpression( having.value ) ?
having.value.getSQL() : "?";
return trim( "#having.combinator# #wrapColumn( having.column )# #having.operator# #placeholder#" );
}
/**
* Compiles the UNION portion of a sql statement.
*
* @query The Builder instance.
* @orders The union clauses.
*
* @return string
*/
private string function compileUnions( required QueryBuilder query, required array unions ) {
if ( arguments.unions.isEmpty() ) {
return "";
}
var sql = arguments.unions.map(function (union){
/*
* No queries being unioned to the origin query can contain an ORDER BY clause, only the outer-most
* QueryBuilder instance can actually have a defined orderBy().
*/
if( arguments.union.query.getOrders().len() ){
throw(
type = "OrderByNotAllowed",
message = "The ORDER BY clause is not allowed in a UNION statement.",
detail = "A QueryBuilder instance used in a UNION statement is cannot have any ORDER BY clause, as this is not allowed by SQL. Only the outer most query is allowed to specify an ORDER BY clause which will be used on the unioned queries."
);
}
var sql = arguments.union.query.toSQL();
return "UNION " & (arguments.union.all ? "ALL " : "") & sql;
});
return trim( arrayToList(sql, ' ') );
}
/**
* Compiles the order by portion of a sql statement.
*
* @query The Builder instance.
* @orders The where clauses.
*
* @return string
*/
private string function compileOrders(
required QueryBuilder query,
required array orders
) {
if ( orders.isEmpty() ) {
return "";
}
var orderBys = orders.map( function( orderBy ) {
return orderBy.direction == "raw" ?
orderBy.column.getSql() :
"#wrapColumn( orderBy.column )# #uCase( orderBy.direction )#";
} );
return "ORDER BY #orderBys.toList( ", " )#";
}
/**
* Compiles the limit portion of a sql statement.
*
* @query The Builder instance.
* @limitValue The limit clauses.
*
* @return string
*/
private string function compileLimitValue( required QueryBuilder query, limitValue ) {
if ( isNull( arguments.limitValue ) ) {
return "";
}
return "LIMIT #limitValue#";
}
/**
* Compiles the offset portion of a sql statement.
*
* @query The Builder instance.
* @offsetValue The offset value.
*
* @return string
*/
private string function compileOffsetValue( required QueryBuilder query, offsetValue ) {
if ( isNull( arguments.offsetValue ) ) {
return "";
}
return "OFFSET #offsetValue#";
}
/**
* Compile a Builder's query into an insert string.
*
* @query The Builder instance.
* @columns The array of columns into which to insert.
* @values The array of values to insert.
*
* @return string
*/
public string function compileInsert(
required QueryBuilder query,
required array columns,
required array values
) {
var columnsString = columns.map( wrapColumn ).toList( ", " );
var placeholderString = values.map( function( valueArray ) {
return "(" & valueArray.map( function() {
return "?";
} ).toList( ", " ) & ")";
} ).toList( ", ");
return trim( "INSERT INTO #wrapTable( query.getFrom() )# (#columnsString#) VALUES #placeholderString#" );
}
/**
* Compile a Builder's query into an update string.
*
* @query The Builder instance.
* @columns The array of columns into which to insert.
*
* @return string
*/
public string function compileUpdate(
required QueryBuilder query,
required array columns
) {
var updateList = columns.map( function( column ) {
return "#wrapColumn( column )# = ?";
} ).toList( ", " );
return trim( "UPDATE #wrapTable( query.getFrom() )# SET #updateList# #compileWheres( query, query.getWheres() )# #compileLimitValue( query, query.getLimitValue() )#" );
}
/**
* Compile a Builder's query into a delete string.
*
* @query The Builder instance.
*
* @return string
*/
public string function compileDelete( required QueryBuilder query ) {
return trim( "DELETE FROM #wrapTable( query.getFrom() )# #compileWheres( query, query.getWheres() )#" );
}
/**
* Compile a Builder's query into an aggregate select string.
*
* @query The Builder instance.
* @aggregate The aggregate query to execute.
*
* @return string
*/
private string function compileAggregate( required QueryBuilder query, required struct aggregate ) {
if ( aggregate.isEmpty() ) {
return "";
}
return "SELECT #uCase( aggregate.type )#(#wrapColumn( aggregate.column )#) AS ""aggregate""";
}
/**
* Returns an array of sql concatenated together with empty spaces.
*
* @sql An array of sql fragments.
*
* @return string
*/
private string function concatenate( required array sql ) {
return arrayToList( arrayFilter( sql, function( item ) {
return item != "";
} ), " " );
}
/**
* Removes the leading "AND" or "OR" from a sql fragment.
*
* @whereList The sql fragment
*
* @return string;
*/
private string function removeLeadingCombinator( required string whereList ) {
return REReplaceNoCase( whereList, "and\s|or\s", "", "one" );
}
/**
* Parses and wraps a table from the Builder for use in a sql statement.
*
* @table The table to parse and wrap.
*
* @return string
*/
public string function wrapTable( required any table ) {
// if we have a raw expression, just return it as-is
if ( variables.utils.isExpression( arguments.table ) ) {
return arguments.table.getSql();
}
var alias = "";
if ( table.findNoCase( " as " ) > 0 ) {
var matches = REFindNoCase( "(.*)(?:\sAS\s)(.*)", table, 1, true );
if ( matches.pos.len() >= 3 ) {
alias = mid( table, matches.pos[3], matches.len[3] );
table = mid( table, matches.pos[2], matches.len[2] );
}
}
else if ( table.findNoCase( " " ) > 0 ) {
alias = listGetAt( table, 2, " " );
table = listGetAt( table, 1, " " );
}
table = table.listToArray( "." ).map( function( tablePart, index ) {
return wrapValue( index == 1 ? getTablePrefix() & tablePart : tablePart );
} ).toList( "." );
return alias == "" ? table : table & " AS " & wrapValue( getTablePrefix() & alias );
}
/**
* Parses and wraps a column from the Builder for use in a sql statement.
*
* @column The column to parse and wrap.
*
* @return string
*/
public string function wrapColumn( required any column ) {
// In this case, isInstanceOf takes ~30 ms while this takes ~0 ms
if ( ! isSimpleValue( column ) &&
isObject( column ) &&
structKeyExists( column, "getSQL" )
) {
return column.getSQL();
}
var alias = "";
if ( column.findNoCase( " as " ) > 0 ) {
var matches = REFindNoCase( "(.*)(?:\sAS\s)(.*)", column, 1, true );
if ( matches.pos.len() >= 3 ) {
alias = mid( column, matches.pos[3], matches.len[3] );
column = mid( column, matches.pos[2], matches.len[2] );
}
}
else if ( column.findNoCase( " " ) > 0 ) {
alias = listGetAt( column, 2, " " );
column = listGetAt( column, 1, " " );
}
column = column.listToArray( "." ).map( wrapValue ).toList( "." );
return alias == "" ? column : column & " AS " & wrapValue( alias );
}
/**
* Parses and wraps a value from the Builder for use in a sql statement.
*
* @table The value to parse and wrap.
*
* @return string
*/
public string function wrapValue( required any value ) {
if ( value == "*" ) {
return value;
}
return """#value#""";
}
/**
* Parses and wraps a value from the Builder for use in a sql statement.
*
* @table The value to parse and wrap.
*
* @return string
*/
public string function wrapAlias( required any value ) {
return wrapValue( value );
}
function compileRaw( blueprint, commandParameters ) {
return commandParameters;
}
/*=========================================
= Blueprint: Create =
=========================================*/
function compileCreate( required blueprint ) {
return "CREATE TABLE #wrapTable( blueprint.getTable() )# (#compileCreateBody( blueprint )#)";
}
function compileCreateBody( blueprint ) {
return arrayToList( arrayFilter( [
compileCreateColumns( blueprint ),
compileCreateIndexes( blueprint )
], function( item ) {
return item != "";
} ), ", " );
}
function compileCreateColumns( required blueprint ) {
return blueprint.getColumns().map( function( column ) {
return compileCreateColumn( column, blueprint );
} ).toList( ", " );
}
function compileCreateColumn( column, blueprint ) {
if ( utils.isExpression( column ) ) {
return column.getSql();
}
try {
if (!column.isColumn()) {
throw(message="Not a Column");
}
} catch(any e) {
//exception happens when isColumn returns false or is not a method on the column object
throw(
type = "InvalidColumn",
message = "Recieved a TableIndex instead of a Column when trying to create a Column.",
detail = "Did you maybe try to add a column and a constraint in an ALTER clause at the same time? Split those up in to separate addColumn and addConstraint commands."
);
}
return arrayToList( arrayFilter( [
wrapColumn( column.getName() ),
generateType( column, blueprint ),
modifyUnsigned( column ),
generateNullConstraint( column ),
generateUniqueConstraint( column, blueprint ),
generateAutoIncrement( column, blueprint ),
generateDefault( column, blueprint ),
generateComment( column, blueprint )
], function( item ) {
return item != "";
} ), " " );
}
function generateNullConstraint( column ) {
return column.getNullable() ? "" : "NOT NULL";
}
function generateUniqueConstraint( column, blueprint ) {
return column.getUnique() ? "UNIQUE" : "";
}
function modifyUnsigned( column ) {
return column.getUnsigned() ? "UNSIGNED" : "";
}
function generateAutoIncrement( column, blueprint ) {
return column.getAutoIncrement() ? "AUTO_INCREMENT" : "";
}
function generateDefault( column ) {
return column.getDefault() != "" ? "DEFAULT #column.getDefault()#" : "";
}
function generateComment( column ) {
return column.getComment() != "" ? "COMMENT #wrapValue( column.getComment() )#" : "";
}
function compileAddComment( blueprint, commandParameters ) {
return arrayToList( [
"COMMENT ON COLUMN",
wrapColumn( commandParameters.table & "." & commandParameters.column.getName() ),
"IS",
"'" & commandParameters.column.getComment() & "'"
], " " );
}
/*===== End of Blueprint: Create ======*/
/*=======================================
= Blueprint: Drop =
=======================================*/
function compileDrop( required blueprint ) {
return arrayToList( arrayFilter( [
"DROP TABLE",
generateIfExists( blueprint ),
wrapTable( blueprint.getTable() )
], function( item ) {
return item != "";
} ), " ");
}
function generateIfExists( blueprint ) {
return blueprint.getIfExists() ? "IF EXISTS" : "";
}
function compileDropAllObjects() {
throw(
type = "OperationNotSupported",
message = "This database grammar does not support this operation",
detail = "compileDropAllObjects"
);
}
function compileEnableForeignKeyConstraints() {
throw(
type = "OperationNotSupported",
message = "This database grammar does not support this operation",
detail = "compileEnableForeignKeyConstraints"
);
}
function compileDisableForeignKeyConstraints() {
throw(
type = "OperationNotSupported",
message = "This database grammar does not support this operation",
detail = "compileDisableForeignKeyConstraints"
);
}
/*===== End of Blueprint: Drop ======*/
/*========================================
= Blueprint: Alter =
========================================*/
function compileAddColumn( blueprint, commandParameters ) {
var existingIndexes = blueprint.getIndexes();
blueprint.setIndexes( [] );
var body = arrayToList( arrayFilter( [
compileCreateColumn( commandParameters.column, blueprint ),
compileCreateIndexes( blueprint )
], function( item ) {