-
Notifications
You must be signed in to change notification settings - Fork 6
/
sql_parser.pl
1998 lines (1777 loc) · 105 KB
/
sql_parser.pl
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
/* Part of SWI-Prolog
Author: Matt Lilley
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (c) 2014, Mike Elston, Matt Lilley
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* PostgreSQL is a trademark of the PostgreSQL Global Development Group.
Microsoft, SQL Server, and Windows are either registered trademarks or
trademarks of Microsoft Corporation in the United States and/or other
countries. SQLite is a registered trademark of Hipp, Wyrick & Company,
Inc in the United States. All other trademarks or registered trademarks
are the property of their respective owners.
*/
:-module(sql_parser, [sql_gripe_level/1,
sql_parse/4,
strip_sql_comments/2]).
/** <module> SQL Parser
This module contains an SQL parser
---+ sql_parse/4
Parsing is invoked with sql_parse(+Term, -TrailingComments, +Options, +Tokens). Notice that all terms are bound when the predicate is called: you must direct the parser where to start. For a view definition, an example invocation might be
sql_tokens(Tokens, "CREATE VIEW foo AS SELECT bar FROM qux", []), sql_parse(view_definition(Definition, Types), TrailingComments, [], Tokens).
---++ Comments
Because comments can appear literally anywhere in the input text, every parse node has both a syntax element (such as view_definition/2) and a list of comments which preceed the element. This means comments are pushed as far as possible down the syntax tree. Any transformations of the input with the intention that it should be printed out again need to take the comments into account. Any other uses of the parse tree may pass it to strip_sql_comments(+InTree, -OutTree) to simply remove them all, leaving the tree with just the syntactic elements.
Finally, there may be trailing comments at the end of the input which are not followed by any token. This means they're not absorbed into the parse tree - so that they're not lost, they are returned as a list from sql_parse/4.
---++ Options
Current options include:
* dbms(+DBMS): If omitted, DBMS will be set to 'Microsoft SQL Server'. For the most part only 'Microsoft SQL Server' views are parseable, but it would not be difficult to extend the parser if this was ever required (just search the source for dbms('Microsoft SQL Server') conditionals)
* view_name(+Name): Passed to gripe/6 so that complaints about view syntax can be associated with a view name
Internally used options include (these should not be passed in under normal circumstances)
* query_id(-Qid): Used to logically separate distinct parts of the query
* subquery: Used to flag whether currently in the top-level query or a subquery
---++ Parse tree
The parse tree returned can be very complicated. The best documentation for this is probably either the sql_write or the sql_check module, which take the tree as an input and do processing on it.
---++ Type inference
Type inference makes the parser take almost 4 times longer, but the resulting information is very useful. It is rarely possible to tell as the input is read what the type of each element is. Where possible, the types are defined (for example, the type of count(*) is always native_type(int)) but where the type is unknown, a new variable is created and a constraint is made.
Type inference is done with CHR, and types are in one of three states:
1 Known, and bound (ie committed)
2 Unknown with one unresolved dependency
3 Unknown with two unresolved dependencies
A dependency here refers to something which would influence the eventual type.
Some examples of the slightly more complicated case 2:
* The type of a column selected from a table that we have not yet resolved
* Consider SELECT foo FROM bar: Until we read the FROM clause we cannot begin to guess what the type of foo is, even though it has only one dependency
* The type of a scalar subquery
* SELECT (SELECT TOP 1 foo FROM bar) AS q: In this case, the type of q is not actually a subquery, it is the single element that subquery returns. A constraint-handling rule checks for a type constraint of type scalar(_) and replaces it with the single element it contains.
* The type of an set operation (ie aggregation)
* SELECT SUM(foo) AS q FROM bar: The type of q may be coerced to a decimal, depending on the eventual type of foo, which is not known until we have read the FROM clause
Some examples of case 3:
* The type of a column which is the union of two selects
* The type of an arithmetic expression
---+ Internal Details
---++ Syntax of the grammar
The grammar started out as an EBNF format, and is based roughly on http://savage.net.au/SQL/sql-92.bnf.html
{}/1 are escaped Prolog, like in a DCG
[...] denote optional clauses
| denotes options
@foo matches the token foo (case-insensitive matching is employed)
#Foo matches the next token with Foo
#Foo:Type matches the next token with Foo if it is a literal of type Type
---++ Left factoring types
SQL Server has some very complicated rules for inferring the type of decimal arithmetic (see http://msdn.microsoft.com/en-us/library/ms190476). The crucial, yet sadly missing information from that page deals with overflows. This is half-explained at http://blogs.msdn.com/b/sqlprogrammability/archive/2006/03/29/564110.aspx.
Because we have truncation, the order of operations is crucial: Although (x * y) / z is mathematically equivalent to x * (y / z), the types of the two expressions in SQL Server are actually different due to truncation. The parser is LL, but this means we will always read x * y / z as x * (y / z), whereas SQL Server does the type inference in reverse. This is only a problem for division and multiplication since the handling of addition and subtraction are symmetric, but without a transformation, we will compute the wrong type. After a term/2 is parsed, left_factor_types/3 is called, which translates just the types in the term from LL into LR form.
---+ Uses
* Automatic determination of the view interface from the view SQL. These are prone to bit rot:
* Someone changes the SQL but forgets to change the interface
* Someone changes the underlying type of a table or view which is directly or indirectly referenced by the view. It's a burden to find all views which might reference the table which has been changes
* Determination of view hierarchies
* This can be used to determine the order in which views should be refreshed or replaced/installed from metadata
* Can also be used with the load dependency analysis
* Determination of indices
* Parsing the view allows us to build a set of disjunctions used in WHERE clauses
* Sanity checking
* Some of the views contain some very, very weird things. Currently there is no oversight or review. If gripes are enabled at compile-time, the quality of code in views can be brought up to a higher standard
* Some views may contain extremely inefficient logical structures. If the parse-tree can be suitably analysed, more efficient equivalent queries can be automatically generated. In any case, uses of patterns which are known to be inefficient can be reported at compile-time
* DBMS indepdence
* Transforming the views is relatively simple once we have the tree isolated. This can allow us to customize views to take advantage of features in later version of SQL Server while not alienating clients using older versions
* If necessary, we can translate views to run on other DBMS, such as Oracle, 'PostgreSQL' or MySQL
---+ Known problems
% It is not practical to determine what + means ahead of time if the source view is MS T-SQL. We would have to guess and backtrack if wrong, and that is horribly inefficient. Instead if we read + in 'Microsoft SQL Server' mode, we should delay determining whether it is really + or actually || until the types of the LHS and RHS are resolved.
*/
:-op(95, fx, @).
:-op(100, fx, #).
% Disable some operators defined elsewhere!
:-op(0, xfx, as).
:-op(0, xfx, on).
:-op(0, xfx, or).
:-op(0, xfx, and).
:-op(0, xfx, not).
:-op(0, xfx, in).
:-op(0, xfx, like).
:-op(100, fx, ??).
:-op(1200, xfx, --->).
:-use_module(library(chr)).
:-use_module(library(quintus), [otherwise/0]).
:-use_module(library(dcg/basics)).
:-use_module(library(cql/sql_keywords)).
:-use_module(library(cql/sql_write)).
:-use_module(library(cql/sql_tokenizer)).
:-use_module(library(cql/cql), [default_schema/1,
cql_normalize_name/3,
dbms/2,
database_attribute/8,
domain_database_data_type/2,
routine_return_type/3,
sql_gripe/3]).
:-chr_option(line_numbers, on).
:-chr_option(check_guard_bindings, error).
:-chr_option(debug, off).
:-chr_option(optimize, full).
:-chr_option(guard_simplification, off). % Added to stop trail overflowing
:-chr_type 'Table' == any.
:-chr_type 'Alias' == any.
:-chr_type 'Type' == any.
:-chr_type 'Column' == any.
:-chr_type 'Constraint' == any.
:-chr_type 'Vars' == any.
:-chr_type 'N' == any.
:-chr_type 'QueryId' == any.
:-chr_type 'Source' == any.
:-chr_constraint type_constraint(-'QueryId', ?'Source', ?'Type', ?'Constraint').
:-chr_constraint type_constraint_ready(-'QueryId', ?'Type').
:-chr_constraint type_merge_hint(?'Type', ?'Constraint').
:-chr_constraint query_table(-'QueryId', ?'Alias', ?'Table').
:-chr_constraint derived_query_column(-'QueryId', ?'Alias', ?'Column', ?'Type').
:-chr_constraint subquery(-'QueryId', -'QueryId').
:-chr_constraint peer_query(-'QueryId', -'QueryId').
:-chr_constraint query_is_xml(-'QueryId').
:-chr_constraint resolve_types(-'QueryId').
:-chr_constraint commit(-'QueryId').
:-chr_constraint union_type(-'QueryId', ?'Constraint', ?'Constraint', ?'Constraint').
:-chr_constraint derived_table(-'QueryId', +'Table', ?'Constraint').
:-chr_constraint find_all_column_types(-'QueryId', ?'Source', ?'Type').
:-chr_constraint force_type_not_domain(?'Type').
:-chr_constraint frozen_reverse(-'QueryId', ?'Constraint', ?'Constraint').
:-chr_constraint cleanup(-'QueryId').
:-dynamic(cached_gripe_level/1).
sql_gripe_level(N):-
cached_gripe_level(N), !.
sql_gripe_level(N):-
( getenv('SQL_GRIPE_LEVEL', Atom),
atom_number(Atom, N)->
true
; otherwise->
N = 0 % FIXME: Should be 1, Testing only
),
assert(cached_gripe_level(N)).
stream_to_tokens(Stream, Tokens):-
stream_to_lazy_list(Stream, List),
sql_tokens(Tokens, List, []), !.
sql_parse(Head, TrailingComments, Options, Tokens):-
Head =.. [Functor, Arg, Types|Args],
reverse(Tokens, TR),
trailing_comments_reversed(TR, TrailingCommentsReversed, Tail),
reverse(Tail, TokensWithoutTrailingComments),
reverse(TrailingCommentsReversed, TrailingComments),
Goal =.. [Functor, TokensWithoutTrailingComments, [], [query_id(QueryId)|Options], _, 0, _, Arg, T1 |Args],
Goal,
!,
%chr_show_store(sql_parser),
%format(user_error, '---------------~n', []),
resolve_types(QueryId),
map_nulls_to_ints(T1, Types),
consolidate_errors(Arg),
cleanup(QueryId),
true.
map_nulls_to_ints([], []):- !.
map_nulls_to_ints([merged(A, _, N)|As], [A-native_type(int)|Bs]):-
N == {nulltype}, !,
map_nulls_to_ints(As, Bs).
map_nulls_to_ints([merged(A, _, N)|As], [A-native_type(int)|Bs]):-
nonvar(N), N = native_type(int(_)), !,
map_nulls_to_ints(As, Bs).
map_nulls_to_ints([merged(A, _, AT)|As], [A-AT|Bs]):-
map_nulls_to_ints(As, Bs).
trailing_comments_reversed([], [], []):- !.
trailing_comments_reversed([comment(A,B)|In], [comment(A,B)|More], Tail):- !,
trailing_comments_reversed(In, More, Tail).
trailing_comments_reversed(Tail, [], Tail):- !.
term_expansion(OldHead ---> OldBody, NewHead :- NewBody):-
OldHead =.. [Functor, A1|Args],
NewHead =.. [Functor, In, Out, ContextIn, _, P0, P1, meta(Comments, Source):A1|Args],
transform_body(OldBody, In, Out, Source, ContextIn, _, Comments, [], P0, P1, NewBody).
transform_body({A}, In, Out, _, C, C, C1, C2, P0, P0, (A, Out = In, C1 = C2)):- !.
transform_body(\+(X), In, In, Source, C, C, C1, C1, P0, P0, \+G):-
transform_body(X, In, _, Source, C, _, C1, _, P0, _, G).
transform_body(??(X), In, Out, Source, CIn, COut, C1, C2, P0, P1, Transformed):-
transform_body(X, In, Out, Source, CIn, COut, C1, C2, P0, P1, G),
functor(X, Functor, Arity),
Transformed = (( length(First, 20), append(First, _, In)-> true ; otherwise-> First = In),
format(user_error, '----- CALL ~w (~q) ~w~n', [Functor/Arity, G, First]),
setup_call_catcher_cleanup(true,
G,
Reason,
( Reason == ! ->
( length(Last, 20), append(Last, _, Out)-> true ; otherwise-> Last = Out),
format(user_error, '----- CUT ~w ~w~n', [Functor/Arity, Last])
; Reason == fail->
format(user_error, '----- FAIL ~w~n', [Functor/Arity])
; Reason == exit->
( length(Last, 20), append(Last, _, Out)-> true ; otherwise-> Last = Out),
format(user_error, '----- EXIT ~w ~w~n', [Functor/Arity, Last])
)),
( var(Reason) ->
( length(Last, 20), append(Last, _, Out)-> true ; otherwise-> Last = Out),
format(user_error, '----- PEND ~w ~w~n', [Functor/Arity, Last])
; otherwise->
true
)
).
transform_body(get_source(Source), In, In, Source, C, C, C1, C1, P0, P0, true):- !.
transform_body(get_parameter(P0), In, In, _, C, C, C1, C1, P0, P1, P1 is P0 + 1):- !.
transform_body(!, InOut, InOut, _, C, C, C1, C2, P0, P0, (!, C1 = C2)):- !.
transform_body(@Functor, In, Out, Source, C, C, C1, C2, P0, P0, get_token(Token, C, C1, C2, In, Out)):- Functor =.. [Token, Source], !.
transform_body(@Token, In, Out, _, C, C, C1, C2, P0, P0, get_token(Token, C, C1, C2, In, Out)):- !.
transform_body(#Identifier : Type, In, Out, _, C, C, C1, C2, P0, P0, get_identifier(Identifier, Type, C, C1, C2, In, Out)):-!.
transform_body(#Identifier, In, Out, _, C, C, C1, C2, P0, P0, get_identifier(Identifier, any, C, C1, C2, In, Out)):-!.
transform_body((A | B), In, Out, Source, CIn, COut, C1, C2, P0, P1, (C, COut = COut1, P1 = P1a ; D, COut = COut2, P1 = P1b)):-
!,
transform_body(A, In, Out, Source, CIn, COut1, C1, C2, P0, P1a, C),
transform_body(B, In, Out, Source, CIn, COut2, C1, C2, P0, P1b, D).
transform_body((A,B), In, Out, Source, CIn, COut, C1, C2, P0, P2, (C,D)):-
!,
transform_body(A, In, Intermediate, Source, CIn, CInt, C1, C1b, P0, P1, C),
transform_body(B, Intermediate, Out, Source, CInt, COut, C1b, C2, P1, P2, D).
transform_body(List, In, Out, Source, CIn, COut, C1, C2, P0, P1Out, (Goals, P1Out = P1 ; In = Out, CIn = COut, C1 = C2, P1Out = P0)):-
is_list(List), !,
transform_list_body(List, In, Out, Source, CIn, COut, C1, C2, P0, P1, Goals).
transform_body(Rule, In, Out, _, CIn, CX, C1, C2, P0, P1, ( C1 = C2, NewRule )):-
Rule =.. [Functor|Args],
NewRule =.. [Functor, In, Out, CIn, COut, P0, P1|Args],
( ( Functor == set_qid ; Functor == add_option)->
CX = COut
; otherwise->
CX = CIn
).
transform_list_body([Tail], In, Out, Source, CIn, COut, C1, C2, P0, P1, Goals):-
transform_body(Tail, In, Out, Source, CIn, COut, C1, C2, P0, P1, Goals).
transform_list_body([Head|Tail], In, Out, Source, CIn, COut, C1, C2, P0, P2, (G, G2)):-
transform_body(Head, In, Intermediate, Source, CIn, CInt, C1, C1b, P0, P1, G),
transform_list_body(Tail, Intermediate, Out, Source, CInt, COut, C1b, C2, P1, P2, G2).
get_token(Token, Options, [comment(A,B)|C1], C2, [comment(A,B)|X], Out):- !,
get_token(Token, Options, C1, C2, X, Out).
get_token(Token, Options, C1, C1, [TopToken|Out], Out):-
( reverse_lex(TopToken, Options, Token)->
true
; atom(TopToken),
downcase_atom(TopToken, Token)->
true
).
get_identifier(Identifier, Type, Options, [comment(A,B)|C1], C2, [comment(A,B)|X], Out):- !,
get_identifier(Identifier, Type, Options, C1, C2, X, Out).
get_identifier(Identifier, Type, Options, C1, C1, [Top|Out], Out):-
( Type == any ->
Identifier = Top
; otherwise->
Top = literal(Identifier, Type)
),
( atom(Identifier)->
downcase_atom(Identifier, IdentifierLC),
\+reserved_sql_keyword(IdentifierLC)
; otherwise->
true
),
\+reverse_lex(Identifier, Options, _).
reverse_lex('*', _Options, asterisk).
reverse_lex('/', _Options, solidus).
reverse_lex('+', _Options, plus_sign).
reverse_lex('-', _Options, minus_sign).
reverse_lex(',', _Options, comma).
reverse_lex('.', _Options, period).
reverse_lex('(', _Options, left_paren).
reverse_lex(')', _Options, right_paren).
reverse_lex('{', _Options, left_curly).
reverse_lex('}', _Options, right_curly).
reverse_lex('IS', _Options, is_keyword).
reverse_lex('Is', _Options, is_keyword).
reverse_lex('iS', _Options, is_keyword).
reverse_lex('is', _Options, is_keyword).
reverse_lex('<', _Options, less_than_operator).
reverse_lex('=', _Options, equals_operator).
reverse_lex('<>', _Options, not_equals_operator).
reverse_lex('>', _Options, greater_than_operator).
reverse_lex('<=', _Options, less_than_or_equals_operator).
reverse_lex('>=', _Options, greater_than_or_equals_operator).
reverse_lex('+', Options, concatenation_operator):- dbms([], [], Options, _, _, _, 'Microsoft SQL Server').
reverse_lex('||', Options, concatenation_operator):- \+dbms([], [], Options, _, _, _, 'Microsoft SQL Server').
add_option(L, L, O, [X|O], P, P, X).
set_qid(L, L, O, O2, P, P, X):-
change_qid(O, X, O2).
change_qid([query_id(_)|T], Qid, [query_id(Qid)|T]):- !.
change_qid([A|T], Qid, [A|T2]):- !, change_qid(T, Qid, T2).
get_option(L, L, O, O, P, P, X):- memberchk(X, O).
qid(L, L, O, O, P, P, Qid):- memberchk(query_id(Qid), O).
default_precision_and_scale(L, L, O, O, P0, P0, P, S):-
( dbms(L, L, O, O, P0, P0, 'Microsoft SQL Server')->
P = 18,
S = 0
; otherwise->
throw(default_unknown)
).
dbms(L, L, Options, Options, P, P, DBMS):-
( memberchk(dbms(X), Options)->
DBMS = X
; otherwise->
DBMS = 'Microsoft SQL Server'
).
check_order_by_is_in_top_query(L, L, Options, Options, P, P, Source):-
( memberchk(subquery, Options)->
true
; \+memberchk(view_name(_), Options)->
% ORDER BY is fine in the top level of an actual query, of course!
true
; otherwise->
semantic_error(Source, order_by(top_level), 1)
).
action(Action, Types)--->
query_expression(Action, Types) | delete_statement_searched(Action, Types) | insert_statement(Action, Types) | update_statement_searched(Action, Types).
delete_statement_searched(delete(TableName, Where), [])--->
@delete, @from, !, table_name(TableName), (@where, search_condition(Condition), {Where = where(Condition)} | {Where = {no_where}}).
insert_statement(insert(TableName, Values), [])--->
@insert, @into, !, table_name(TableName), insert_columns_and_source(Values), [dbms('PostgreSQL'), @returning, query_expression(_,_)].
insert_columns_and_source(Values)--->
from_subquery(Values) | from_constructor(Values) | from_default(Values).
from_default({default_values})---> @default, @values, !.
from_subquery(insert_source(Source, Override, Target))--->
( ( @left_paren, insert_column_list(Source), @right_paren) | {Source = {default}} ),
( override_clause(Override) | {Override = {no_override}} ),
query_expression(Target, _).
from_constructor(insert_source(Source, Override, Target))--->
( ( @left_paren, insert_column_list(Source), @right_paren) | {Source = {default}} ),
( override_clause(Override) | {Override = {no_override}} ),
table_value_constructor(Target, _).
update_statement_searched(update(TableName, List, From, Condition), [])--->
% Actually should be table_name here. Apparently it is not legal to use an alias?
@update, table_reference(TableName),
qid(Qid), {strip_sql_comments(TableName, Stripped), determine_tables(Qid, Stripped)},
@set, set_clause_list(List),
( @from, from_clause_1(F), {strip_sql_comments(F, CleanedFrom), ( determine_tables(Qid, CleanedFrom)-> From = from(F) ; otherwise->throw(failed_tables(CleanedFrom)))}
| {From = {no_from}}),
( @where, search_condition(Where), {Condition = where(Where)} | {Condition = {no_where}}).
set_clause_list([Head|Tail])--->
set_clause(Head), (@comma, set_clause_list(Tail) | {Tail = []}).
set_clause(set(Target, Source))--->
update_target(Target), @equals_operator, update_source(Source). % Or mutated-set-clause, but we probably dont need to worry about that
update_target(Target)---> column_name(Target). % Actually also allows foo[expression]
update_source(Source)---> value_expression(Source, _) | default_specification(Source, _) | null_specification(Source, _). % Also allows ARRAY[]
insert_column_list(List)---> column_name_list(List).
override_clause(overriding_user_value)---> @overriding, @user, @value, !.
override_clause(overriding_system_value)---> @overriding, @system, @value, !.
view_definition(view_definition(Name, Columns, Expression, With), Types)---> (@create), @view, table_name(Name),
{
strip_sql_comments(Name, NameNoComments),
( NameNoComments = table(identifier(schema(_, literal(dbo, identifier)), _))->
true
; otherwise->
throw(illegal_view_name(no_schema))
)},
( @left_paren, view_column_list(Columns), @right_paren | {Columns = {all}}), with_attribute(With), @as, query_expression(Expression, Types).
table_name(table(Name))---> qualified_name(Name).
view_column_list(List)---> column_name_list(List).
query_expression(Term, T)--->
qid(Qid),
non_join_query_term(LHS, LT),
( @union, (@all, {Term = union_all(LHS, RHS, Corresponding)} | {Term = union(LHS, RHS, Corresponding)}), (corresponding_spec(Corresponding) | {Corresponding = {no_corresponding}}), set_qid(SubQid), query_expression(RHS, RT), {peer_query(Qid, SubQid), union_type(Qid, LT, RT, T)}
| @except, (@all, {Term = except_all(LHS, RHS, Corresponding)} | {Term = except(LHS, RHS, Corresponding)}), (corresponding_spec(Corresponding) | {Corresponding = {no_corresponding}}), query_expression(RHS, RT), {union_type(Qid, LT, RT, T)}
| {Term = LHS, T = LT}).
non_join_query_term(Term, T)---> (non_join_query_primary(LHS, LT) | free_joined_table(LHS, LT)),
( @intersect, ( @all, {Term = intersect_all(LHS, RHS, Corresponding)} | {Term = intersect(LHS, RHS, Corresponding)}),
( corresponding_spec(Corresponding) | {Corresponding = {no_corresponding}}), non_join_query_term(RHS, RT), qid(Qid), {union_type(Qid, LT, RT, T)} | {Term = LHS, T = LT}).
non_join_query_primary(Primary, T)---> (simple_table(Primary, T) | @left_paren, query_expression(Primary, T), @right_paren).
simple_table(Table, T)---> query_specification(Query, T), {Table = query(Query)} | table_value_constructor(Values, T), {Table = values(Values)} | explicit_table(Explicit), {Table = explicit_table(Explicit), T = {fixme1}}.
query_specification(select(Q, Selections, Source, Limit, For), QueryType)--->
@select, ( set_quantifier(Q) | {Q = {no_quantifier}} ), [ dbms('Microsoft SQL Server'), top_clause(Limit) ],
select_list(Selections, Sources, Types), table_expression(Source), [dbms('PostgreSQL'), limit_clause(Limit)], {var(Limit)->Limit = {no_limit} ; true},
( dbms('Microsoft SQL Server'), for_clause(For), get_source(S1), {semantic_error(for_clause, S1, 2)} | {For = {no_for}}),
{(strip_sql_comments(Selections, S), merge_types(S, Sources, Types, QueryType)-> true ; throw(failed_to_resolve))}.
select_list(N, S, T)---> (@asterisk, qid(Qid), get_source(Source), {N = all, find_all_column_types(Qid, Source, T1), frozen_reverse(Qid, T1, T)} | select_list_1(N, S, T)).
select_list_1([Head|Tail], [Source|Sources], [Type|Types])---> select_sublist(Head, Source, Type), (@comma, select_list_1(Tail, Sources, Types) | {Tail = [], Sources = [], Types = []}).
select_sublist(S, Source, Type)---> get_source(Source), derived_column(Column, Type), {S = Column} | qualifier(Qualifier), @period, @asterisk, {S = all(Qualifier), Type = {fixme3}}.
derived_column(derived_column(Column, As), Type)---> (illegal_null_specification(Column, Type) | value_expression(Column, Type)), (as_clause(As) | {As = {no_alias}}). % Added @null to allow for SELECT NULL AS foo, since null is not a value
as_clause(Name)---> [@as], column_name(Name).
table_expression(source(From, Where, GroupBy, OrderBy, Having))--->
from_clause(From),
qid(Qid),
{((From = _:from(F))->
strip_sql_comments(F, CleanedFrom),
( determine_tables(Qid, CleanedFrom)-> true ; otherwise->throw(failed_tables(CleanedFrom)))
; From = _:{no_from}->
true
)},
( where_clause(Where) | {Where = {no_where}}),
( group_by_clause(GroupBy) | {GroupBy = {no_groupby}}),
% Some hacks here. table_expression is not supposed to have an order-by clause, but it is used in a lot of views
% Further, some views put the order-by AFTER the having
% To allow the order-by to refer to expressions in the view, we have to make the entire query become a sub-query of the order-by clause
% However, confusingly, the HAVING clause needs to be part of the same query so that things like SUM(x) which resolve in the select list also resolve in the HAVING clause
qid(Qid), set_qid(SubqueryId), {subquery(SubqueryId, Qid)},
( order_by_clause(OrderBy), set_qid(Qid), (having_clause(Having) | {Having = {no_having}})
| set_qid(Qid), having_clause(Having), ( set_qid(SubqueryId), order_by_clause(OrderBy), get_source(Source), {semantic_error(order(having, order_by), Source, 2)} | {OrderBy = {no_orderby}})
| {OrderBy = {no_orderby}, Having = {no_having}}),
set_qid(Qid).
from_clause(from(From))---> @from, from_clause_1(From).
from_clause({no_from})---> {true}.
from_clause_1([Head|Tail])---> table_reference(Head), get_source(Source), (@comma, {semantic_error(Source, deprecated('SQL89-style join', 'Explicit JOIN clauses'), 1)}, from_clause_1(Tail) | {Tail = []}).
table_reference(Reference)---> (@left_paren, table_reference(LHS), @right_paren
| derived_table(Derivation, T), correlation_specification(Correlation), {LHS = derived_table(Derivation, Correlation, T)}
| table_name(Name), (correlation_specification(Correlation) | {Correlation = {no_correlation}}), {LHS = correlated_table(Name, Correlation)}),
[ dbms('Microsoft SQL Server'), with_clause(_) ], % TBD: Preserve WITH
( more_join(RHS), {Reference = join(LHS, RHS)} | {Reference = LHS}).
more_join(X)--->
( cross_join_rhs(LHS), {Reference = cross_join(LHS)}
| qualified_join_rhs(Type, LHS, On), {Reference = qualified_join(Type, LHS, On)}),
( more_join(RHS2), {X = join(Reference, RHS2)} | {X = Reference}).
correlation_specification(correlation(Name, Columns))---> [@as], #NameMC, (@left_paren, derived_column_list(Columns), @right_paren | {Columns = {no_columns}}), {name_from_identifier(NameMC, Name)}.
derived_column_list(L)--->column_name_list(L).
derived_table(Table, T)---> table_subquery(Table, T).
table_subquery(Query, T)---> subquery(Query, T).
cross_join_rhs(Reference)---> @cross, @join, table_reference(Reference).
qualified_join_rhs(Type, Reference, Spec)---> ( @natural, {Type = natural(T1)} | {Type = T1} ), ( join_type(T1) | {T1 = join} ), (@join), table_reference(Reference), ( join_specification(Spec) | {Spec = {no_on}} ).
free_joined_table(Table, {fixme4})---> table_reference(Table).
join_type(join_type(Type))---> (@inner, {Type = inner} | outer_join_type(T1), {Type = outer(T1)}, [ @outer ] | @union, {Type = union}).
outer_join_type(T)---> (@left, {T=left} | @right, {T=right} | @full, {T=full}).
join_specification(Spec)---> ( join_condition(Spec) | named_columns_join(Spec) ).
join_condition(on(On)) ---> @on, search_condition(On).
named_columns_join(columns(Columns))---> @using, @left_paren, join_column_list(Columns), @right_paren.
join_column_list(Columns)---> column_name_list(Columns).
set_quantifier(Q)---> ( @distinct, {Q = distinct} | @all, {Q = all} ).
where_clause(where(Where))---> @where, search_condition(Where).
corresponding_spec(Columns)---> @corresponding, ( @by, @left_paren, corresponding_column_list(Columns), @right_paren | {Columns = {no_columns}} ).
corresponding_column_list(List)---> column_name_list(List).
query_primary(Primary, T)---> ( non_join_query_primary(Primary, T) | free_joined_table(Primary, T) ).
subquery(subquery(Query), T)---> (@left_paren, add_option(subquery), qid(Qid), set_qid(SubqueryId), {subquery(Qid, SubqueryId)}, query_expression(Query, T), @right_paren).
column_name_list([Head|Tail])---> column_name(Head), (@comma, column_name_list(Tail) | {Tail = []}).
column_name(Name)---> #Identifier, \+(@left_paren),
{( Identifier = literal(Name, identifier)->
true
; Identifier = literal(A,B)-> % Quirks. This is for "SELECT '01' AS foo. The 'column' here is actually the literal 01
Name = literal(A,B)
; otherwise->
downcase_atom(Identifier, Name)
)}.
explicit_table(table(Table)) ---> @(table), table_name(Table).
qualifier(Qualifier)---> qualified_name(Qualifier).
% If this were a numeric_value_expression followed by /plus/ (as distinct but indistiguishable from /concat/) then it
% would have been absorbed into the numeric_value_expression. The only time we would exist numeric_value_expression and consume a +
% is if we knew it was actually a concat!
value_expression(V, T)---> numeric_value_expression(V, T), \+(@concatenation_operator), \+(@minus_sign), \+(@period) % Hints we might be barking up the wrong parse tree
| string_value_expression(V, T), \+(@concatenation_operator), \+(@minus_sign), \+(@period)
| datetime_value_expression(V, T)
| interval_value_expression(V, T).
% TBD: This should ALSO be applied for subtract, since CURRENT_TIMESTAMP - 1 is not subtract but add_interval(CURRENT_TIMESTAMP, -1)
numeric_value_expression(V, T)--->
numeric_value_expression_1(V, T1),
qid(Qid),
{left_factor_types(Qid, T1, T)}.
numeric_value_expression_1(V, T)--->
get_source(LS), term(LHS, LT), qid(Qid),
( ( @plus_sign, {Op = add} | @minus_sign, {Op = subtract} ),
get_source(RS),
numeric_value_expression_1(RHS, RT),
{T = node(LT, LS, Op, RT, RS),
% T1 is not the type of the subexpression (since this sub-expression may not even exist in the final result)
% but it IS needed to determine whether the operation is +(addition) or +(concatenation) since SQL Server
% doesnt distinguish these with syntax
% Similarly R1 is not necessarily needed for the SQL, but it IS needed here
left_factor_types(Qid, RT, R1),
left_factor_types(Qid, LT, L1),
most_general_type(Qid, Source, Source, L1, R1, Op, T1),
freeze(T1, determine_operation_from_types(T1, L1, R1, Op, LHS, RHS, V))}
| {V = LHS, T = LT}
).
%TBD: This currently does not always work. See for example le_vw_negative_holdings
determine_operation_from_types(Type, LT, RT, Op, LHS, RHS, V):-
%format(user_error, '--------------------------------- add_or_concat: ~w, ~w, ~w~n', [Type, LT, RT]),
native_type_of_type(LT, LTT),
native_type_of_type(RT, RTT),
( Op == add ->
( native_type_of_type(Type, native_type(varchar(_)))->
V = concatenate(LHS, RHS)
; native_type_of_type(Type, native_type(nvarchar(_)))->
V = concatenate(LHS, RHS)
; LTT = native_type(datetime),
RTT = native_type(int(_))->
V = add_interval(LHS, RHS)
; RTT = native_type(datetime),
LTT = native_type(int(_))->
V = add_interval(RHS, LHS)
% Believe it or not, there are places where we add numerics to dates as well. I will only implement
% the cases that exist as a workaround
; LTT = native_type(datetime),
RTT = native_type(decimal(_,_))->
V = add_interval(LHS, RHS)
; otherwise->
V = add(LHS, RHS)
)
; Op == subtract ->
( LTT = native_type(datetime),
RTT = native_type(int(_))->
V = add_interval(LHS, negative(RHS))
; RTT = native_type(datetime),
LTT = native_type(int(_))->
V = add_interval(RHS, negative(LHS))
% Believe it or not, there are places where we subtract numerics from dates as well. I will only implement
% the cases that exist as a workaround
; LTT = native_type(datetime),
RTT = native_type(decimal(_,_))->
V = add_interval(LHS, negative(RHS))
; otherwise->
V = subtract(LHS, RHS)
)
).
native_type_of_type(native_type(X), native_type(X)):- !.
native_type_of_type(domain(D), native_type(X)):-
fetch_domain_data_type(D, X).
term(V, T)---> get_source(LS), factor(LHS, LT), ((@asterisk, {V = multiply(LHS, RHS), Op = multiply} | @solidus, {V = divide(LHS, RHS), Op = divide(RT)}), get_source(RS), term(RHS, RT), {T = node(LT, LS, Op, RT, RS)} | {V = LHS, T = LT}).
factor(V, T)---> ( (@plus_sign, {V = positive(N)} | @minus_sign, dbms(DBMS), {V = negative(N), (DBMS == 'Microsoft SQL Server' -> force_type_not_domain(T) ; true)}) | { V = N} ), numeric_primary(N, T). % Quirk. This is in contradiction to the T-SQL Reference, but confirmed.
numeric_primary(N, T)---> value_expression_primary(N, T) | numeric_value_function(N, T).
value_expression_primary(N, T)--->
unsigned_value_specification(N, T) | parameter(N, T) | column_reference(N, T) | set_function_specification(N, T) | case_expression(N, T) | @left_paren, value_expression(N, T), @right_paren | cast_specification(N, T) | scalar_subquery(N, T) | routine_invocation(N, T).
parameter(parameter(N), native_type(int)) ---> @(?), get_parameter(N). % FIXME: Type of parameter
column_reference(column(Qualifier, Name), Type)---> ( qualifier(Qualifier), @period | {Qualifier = {no_qualifier}} ), column_name(Name), qid(Qid), get_source(Source), {strip_sql_comments(Qualifier, QS), strip_sql_comments(Name, NS), type_constraint(Qid, Source, Type, typeof(QS, NS)), type_constraint_ready(Qid, Type)}.
scalar_subquery(S, T)---> subquery(S, ST), qid(Qid), get_source(Source), {type_constraint(Qid, Source, T, scalar(ST)), type_constraint_ready(Qid, T)}.
having_clause(having(Having))---> @having, search_condition(Having).
group_by_clause(group_by(List))---> @group, @by, grouping_column_reference_list(List).
grouping_column_reference_list([Head|Tail])---> grouping_column_reference(Head), ( @comma, grouping_column_reference_list(Tail) | {Tail = []} ).
grouping_column_reference(group_column(Reference, Collate))---> column_reference(Reference, _), ( collate_clause(Collate) | {Collate = {no_collation}} ).
collate_clause(collate(Name))---> @collate, collation_name(Name).
collation_name(collation(Name))---> qualified_name(Name).
qualified_name(identifier(Qualifier, Name))---> ( schema_name(Qualifier), @period | {Qualifier = {no_schema}}), #Identifier, {name_from_identifier(Identifier, Name)}. % Quirk
schema_name(schema(Catalog, Schema))---> ( catalog_name(Catalog), @period | {Catalog = {no_catalog}}), #Schema.
catalog_name(Catalog)---> #Catalog.
set_function_specification(S, T)---> (@count, @left_paren, @asterisk, @right_paren, {S = count(all), T = native_type(int)} | general_set_function(S, T)).
set_function_specification(S, T)---> (@count_big, @left_paren, @asterisk, @right_paren, {S = count(all), T = native_type(bigint)} | general_set_function(S, T)).
general_set_function(set_function(S, Q, A), T)---> set_function_type(S), @left_paren, ( set_quantifier(Q) | {Q = {no_quantifier}} ), value_expression(A, AT), @right_paren, qid(Qid), get_source(Source),
{S = _:count ->
T = native_type(int)
; S = _:sum->
type_merge_hint(T, sum),
type_constraint(Qid, Source, T, AT),
type_constraint_ready(Qid, T)
; S = _:avg->
type_merge_hint(T, avg),
type_constraint(Qid, Source, T, AT),
type_constraint_ready(Qid, T)
; otherwise->
T = AT
}.
set_function_type(T)---> @avg, {T = avg} | @max, {T = max} | @min, {T = min} | @sum, {T = sum} | @count, {T = count}.
search_condition(C, _Types)---> search_condition(C).
search_condition(C)---> boolean_term(Head), (@or, search_condition(Tail), {C = or(Head, Tail)} | {C = Head}).
boolean_term(C)---> boolean_factor(Head), (@and, boolean_term(Tail), {C = and(Head, Tail)} | {C = Head}).
boolean_factor(C)---> ( @not, {C = not(X)} | {C = X} ), boolean_test(X).
boolean_test(Test)---> boolean_primary(X), ( @is_keyword, ( @not, {Test = isnot(X, T)} | {Test = is(X, T)}), truth_value(T) | {Test = X}).
truth_value(T)---> (@true, {T = true} | @false, {T = false} | @unknown, {T = unknown}).
boolean_primary(P)---> @left_paren, search_condition(Search), {P = search(Search)}, @right_paren | predicate(Pr), {P = predicate(Pr)}.
predicate(Predicate)---> comparison_predicate(Predicate) | between_predicate(Predicate) | in_predicate(Predicate) | like_predicate(Predicate) | null_predicate(Predicate) | quantified_comparison_predicate(Predicate) | exists_predicate(Predicate) | match_predicate(Predicate) | overlaps_predicate(Predicate).
comparison_predicate(comparison(CompOp, LHS, RHS))---> row_value_constructor(LHS, LT), comp_op(CompOp), row_value_constructor(RHS, RT), {check_types(LT, RT)}.
row_value_constructor(Row, Types)---> @left_paren, row_value_constructor_list(List, Types), {Row = list(List)}, @right_paren | row_value_constructor_element(Element, Types), {Row = element(Element)} | row_subquery(SubQuery, Types), {Row = query(SubQuery, Types)}.
row_value_constructor_element(Element, Type)---> value_expression(Element, Type) | null_specification(Element, Type) | default_specification(Element, Type).
comp_op(Op)---> @equals_operator, {Op = '='}
| @not_equals_operator, {Op = '<>'}
| @less_than_operator, {Op = '<'}
| @greater_than_operator, {Op = '>'}
| @less_than_or_equals_operator, {Op = '<='}
| @greater_than_or_equals_operator, {Op = '>='}.
null_specification({null}, T)---> @null, qid(Qid), get_source(Source), {type_constraint(Qid, Source, T, {nulltype}), type_constraint_ready(Qid, T)}.
illegal_null_specification({null}, T)---> @null, qid(Qid), get_source(Source), {semantic_error(Source, null_value, 1), type_constraint(Qid, Source, T, {nulltype}), type_constraint_ready(Qid, T)}.
null_predicate(Predicate)---> row_value_constructor(LHS, _), @is_keyword, ( @not, {Predicate = is_not_null(LHS)} | {Predicate = is_null(LHS)} ), @null. % The spec is wrong here
default_specification({default}, {defaulttype})---> @default.
row_subquery(S, T)---> subquery(S, T).
row_value_constructor_list([Head|Tail], [Type|Types])---> row_value_constructor_element(Head, Type), (@comma, row_value_constructor_list(Tail, Types) | {Tail = [], Types = []}) .
between_predicate(Term)---> row_value_constructor(LHS, TA), ( @not, {Term = not_between(LHS, Min, Max)} | {Term = between(LHS, Min, Max)}), @between, row_value_constructor(Min, TB), @and, row_value_constructor(Max, TC), {check_types(TA, TB), check_types(TA, TC)}.
exists_predicate(exists(Query))---> @exists, table_subquery(Query, _).
in_predicate(P) ---> row_value_constructor(Value, T1), ( @not, {P = not_in(Value, List)} | {P = in(Value, List)} ), @in, in_predicate_value(List, T2), {forall(member(T, T2), check_types(T1, T))}.
in_predicate_value(In, Types)---> @left_paren, in_value_list(List, Types), {In = list(List)}, @right_paren | table_subquery(Query, Types), {In = query(Query)}.
in_value_list([Head|Tail], [Type|Types])---> value_expression(Head, Type), ( @comma, in_value_list(Tail, Types) | {Tail = [], Types = []} ).
like_predicate(P)---> match_value(LHS), ( @not, {P = not_like(LHS, Pattern, Escape)} | {P = like(LHS, Pattern, Escape)}), (@like | @ilike), pattern(Pattern), ( @escape, escape_character(Escape) | {Escape = {no_escape}}).
match_value(P)---> character_value_expression(P, _).
pattern(P)---> character_value_expression(P, _).
escape_character(P)---> character_value_expression(P, _).
character_value_expression(E, T)---> get_source(S1), character_factor(LHS, LT), (@concatenation_operator, get_source(S2), character_value_expression(RHS, RT), qid(Qid), {E = concatenate(LHS, RHS), concatenate_type(Qid, S1, S2, LT, RT, T)} | {E = LHS, T = LT}).
character_factor(Factor, T)---> character_primary(F, T), ( collate_clause(C), {Factor = collated_factor(F, C)} | {Factor = F} ).
character_primary(X, T)---> value_expression_primary(X, T) | string_value_function(X, T).
match_predicate(match(Unique, MatchLevel, LHS, RHS))---> row_value_constructor(LHS, TL), @match, [ @unique, {Unique = unique} ], [ (@partial, {MatchLevel = partial} | @full, {MatchLevel = full}) ], table_subquery(RHS, TR), {check_types(TL, TR)}.
overlaps_predicate(overlaps(LHS, RHS))---> row_value_constructor(LHS, TL), @overlaps, row_value_constructor(RHS, TR), {check_types(TL, TR)}.
quantified_comparison_predicate(quantified_comparison(Op, Quantifier, LHS, RHS))---> row_value_constructor(LHS, TL), comp_op(Op), quantifier(Quantifier), table_subquery(RHS, TR), {check_types(TL, TR)}.
quantifier(Quantifier)---> @all, {Quantifier = all} | @some, {Quantifier = some}.
table_value_constructor(N, T)---> @values, table_value_constructor_list(N, T).
table_value_constructor_list([Head|Tail], [Type|Types])---> row_value_constructor(Head, Type), (@comma, table_value_constructor_list(Tail, Types) | {Tail = [], Types = []}).
case_expression(N, T)---> case_abbreviation(N, T) | case_specification(N, T).
case_abbreviation(V, T)---> @nullif, @left_paren, value_expression(LHS, LT), @comma, value_expression(RHS, RT), @right_paren, qid(Qid), get_source(Source), {V = nullif(LHS, RHS), most_general_type(Qid, Source, Source, LT, RT, case, T)}
| @coalesce, @left_paren, coalesce_list(List, Types, Sources), @right_paren, qid(Qid), {V = coalesce(List), coalesce_type(Qid, Types, Sources, T)}.
coalesce_list([Head|Tail], [Type|Types], [Source|Sources])---> get_source(Source), (null_specification(Head, Type), get_source(Source), {semantic_error(Source, coalesce(null_argument), 1)} | value_expression(Head, Type)), ( @comma, coalesce_list(Tail, Types, Sources) | {Tail = [], Types = [], Sources = []} ).
case_specification(N, T)---> searched_case(N, T) | simple_case(N, T).
simple_case(simple_case(Operand, List, Else), T)---> @case, qid(Qid), case_operand(Operand), simple_when_clause_list(List, Types, Sources), ( get_source(Source), else_clause(Else, ElseType), {coalesce_type(Qid, [ElseType|Types], [Source|Sources], T)} | {Else = {no_else}, coalesce_type(Qid, Types, Sources, T)} ), @end.
simple_when_clause_list([Head|Tail], [Type|Types], [Source|Sources])---> get_source(Source), simple_when_clause(Head, Type), (simple_when_clause_list(Tail, Types, Sources) | {Tail = [], Types = [], Sources = []}).
case_operand(X)---> value_expression(X, _).
simple_when_clause(when(When, Result), T)---> @when, when_operand(When), @then, result(Result, T).
when_operand(X)---> value_expression(X, _).
result(X, T)---> null_specification(X, T) | result_expression(X, T).
result_expression(X, T)---> value_expression(X, T).
else_clause(else(Else), T)---> @else, result(Else, T).
searched_case(case(Cases, Else), T)---> @case, qid(Qid), searched_when_clause_list(Cases, Types, Sources), ( get_source(Source), else_clause(Else, ElseT), {coalesce_type(Qid, [ElseT|Types], [Source|Sources], T)} | {Else = {no_else}, /* No domain if no else clause? */ force_type_not_domain(T), coalesce_type(Qid, Types, Sources, T)} ), (@end).
searched_when_clause_list([Head|Tail], [Type|Types], [Source|Sources])---> get_source(Source), searched_when_clause(Head, Type), (searched_when_clause_list(Tail, Types, Sources) | {Tail = [], Types = [], Sources = []}).
searched_when_clause(when(searched(Search), Result), T)---> @when, search_condition(Search), @then, result(Result, T).
numeric_value_function(N, native_type(int))---> position_expression(N) | extract_expression(N) | length_expression(N).
position_expression(position(A, B))---> @position, @left_paren, character_value_expression(A, _), @in, character_value_expression(B, _), @right_paren.
extract_expression(extract(Field, Source))---> @extract, @left_paren, extract_field(Field), @from, extract_source(Source), @right_paren.
length_expression(A)---> char_length_expression(A) | octet_length_expression(A) | bit_length_expression(A).
char_length_expression(char_length(A))---> ( @char_length | @character_length ), @left_paren, string_value_expression(A, _), @right_paren.
string_value_expression(X, T)---> character_value_expression(X, T) | bit_value_expression(X, T).
octet_length_expression(octet_length(A))---> @octet_length, @left_paren, string_value_expression(A, _), @right_paren.
bit_length_expression(bit_length(A))---> @bit_length, @left_paren, string_value_expression(A, _), @right_paren.
extract_field(Field)---> datetime_field(Field) | time_zone_field(Field).
extract_source(V)---> datetime_value_expression(V, _) | interval_value_expression(V, _).
unsigned_value_specification(Value, native_type(int(X)))---> #Value : int(X).
routine_invocation(routine(Name, Args), Type)---> qualified_name(Name), @left_paren, dbms(DBMS), {not_a_builtin_function(DBMS, Name)}, (sql_argument_list(Args) | {Args = []}), @right_paren, {routine_type(Name, Type)}.
sql_argument_list([Head|Tail])---> sql_argument(Head), (@comma, sql_argument_list(Tail) | {Tail = []}).
sql_argument(Arg)---> value_expression(Arg, _).
cast_specification(cast(Operand, Target), Type)---> @cast, @left_paren, cast_operand(Operand), @as, cast_target(Target), {strip_sql_comments(Target, Type)}, @right_paren.
cast_operand(Operand)---> @null, {Operand = {null}} | value_expression(Operand, _).
cast_target(Target)---> data_type(Type), {Target = native_type(Type)} | domain_name(Domain), {Target = domain(Domain)}.
domain_name(Name)---> qualified_name(Name).
data_type(Type)---> character_string_type(Type), ( @character, @set, character_set_specification(_) | {true}) | national_character_string_type(Type) | bit_string_type(Type) | numeric_type(Type) | datetime_type(Type) | interval_type(Type).
character_string_type(varchar(Length))---> @character, ( @left_paren, length(Length), @right_paren | {Length = 30})
| @char, ( @left_paren, length(Length), @right_paren | {Length = 30})
| @character, @varying, ( @left_paren, length(Length), @right_paren | {Length = 30})
| @char, @varying, ( @left_paren, length(Length), @right_paren | {Length = 30})
| @varchar, ( @left_paren, length(Length), @right_paren | {Length = 30}).
length(Length)---> #Length : int(_) | (@max, {Length = max}).
national_character_string_type(nchar_type(Length))--->
@national, @character, [ @left_paren, length(Length), @right_paren ]
| @national, @char, [ @left_paren, length(Length), @right_paren ]
| @nchar, [ @left_paren, length(Length), @right_paren ]
| @national, @character, @varying, [ @left_paren, length(Length), @right_paren ]
| @national, @char, @varying, [ @left_paren, length(Length), @right_paren ]
| @nchar, @varying, [ @left_paren, length(Length), @right_paren ].
bit_string_type(bit_type(Length))---> @bit, [ @left_paren, length(Length), @right_paren ] | @bit, @varying, [ @left_paren, length(Length), @right_paren ].
numeric_type(Type)---> exact_numeric_type(Type) | approximate_numeric_type(Type).
exact_numeric_type(Type)---> @numeric, {Type = decimal(Precision, Scale)}, ( @left_paren, precision(Precision), ( @comma, scale(Scale) | {Scale = {no_scale}}), @right_paren | default_precision_and_scale(Precision, Scale))
| @decimal, {Type = decimal(Precision, Scale)}, ( @left_paren, precision(Precision), ( @comma, scale(Scale) | {Scale = {no_scale}}), @right_paren | default_precision_and_scale(Precision, Scale) )
| @dec, {Type = decimal(Precision, Scale)}, ( @left_paren, precision(Precision), ( @comma, scale(Scale) | {Scale = {no_scale}}), @right_paren | default_precision_and_scale(Precision, Scale) )
| @integer, {Type = int}
| @int, {Type = int}
| @smallint, {Type = smallint}
| dbms('Microsoft SQL Server'), @tinyint, {Type = tinyint}.
precision(Precision)---> #Precision : int(_).
scale(Scale)---> #Scale : int(_).
approximate_numeric_type(Type)---> @float, ( @left_paren, precision(Precision), @right_paren | {Precision = {no_precision}}), {Type = float(Precision)} | @real, {Type = real} | @double, precision(Precision), {Type = double(Precision)}.
datetime_value_expression(V, T)---> (datetime_term(LHS, LT) | interval_value_expression(LHS, LT)),
( ( @plus_sign, {V = add(LHS, RHS), Op = add} | @minus_sign, {V = subtract(LHS, RHS), Op = subtract}), datetime_value_expression(RHS, RT), qid(Qid), get_source(Source), {most_general_type(Qid, Source, Source, LT, RT, Op, T)} | {V = LHS, T = LT}).
order_by_clause(order_by(List))---> @order, @by, get_source(Source), check_order_by_is_in_top_query(Source), sort_specification_list(List).
sort_specification_list([Head|Tail])---> sort_specification(Head), ( @comma, sort_specification_list(Tail) | {Tail = []}).
sort_specification(sort_key(Key, Collate, Order))---> sort_key(Key), ( collate_clause(Collate) | {Collate = {no_collation}} ), ( ordering_specification(Order) | {Order = {no_order}} ).
% According to SQL92, a sort_key is a column_reference. In SQL99, however, it is a value_expression, which is quite a bit easier.
%sort_key(Key)---> column_reference(C, _), {Key = sort_column(C)} | #I : int(_), {Key = index(I)}.
sort_key(Key)---> value_expression(C, _), {Key = sort_column(C)} | #I : int(_), {Key = index(I)}.
ordering_specification(S)---> @asc, {S = asc} | @desc, {S = desc}.
interval_term(V, T)---> interval_factor(LHS, LT), (((@asterisk, {V = multiply(LHS, RHS), Op = multiply} | @solidus, {V = divide(LHS, RHS), Op = divide(RT)}), interval_term(RHS, RT), qid(Qid), get_source(Source), {most_general_type(Qid, Source, Source, LT, RT, Op, T)}) | {V = LHS, T = LT})
| term(LHS, LT), @asterisk, interval_factor(RHS, RT), qid(Qid), get_source(Source), {T = multiply(LHS, RHS), most_general_type(Qid, Source, Source, LT, RT, multiply, T)}.
interval_factor(F, T)---> (@plus_sign, {F = positive(F1)} | @minus_sign, {F = negative(F1)} | {F = F1}), interval_primary(F1, T).
interval_primary(interval(P, Q), T)---> value_expression_primary(P, T), ( interval_qualifier(Q) | {Q = {no_qualifier}} ).
interval_value_expression(V, T)---> interval_term(LHS, LT), (((@plus_sign, {V = add(LHS, RHS), Op = add} | @minus_sign, {V = subtract(LHS, RHS), Op = subtract}), interval_term(RHS, RT), qid(Qid), get_source(Source), {most_general_type(Qid, Source, Source, LT, RT, Op, T)}) | {V = LHS, T = LT})
| @left_paren, datetime_value_expression(LHS, LT), @minus_sign, datetime_term(RHS, RT), @right_paren, interval_qualifier(Q), qid(Qid), get_source(Source), {T = qualified_subtract(Q, LHS, RHS), most_general_type(Qid, Source, Source, LT, RT, subtract, T)}.
datetime_term(V, T)---> datetime_factor(V, T).
datetime_factor(V, T)---> datetime_primary(P, T1), ( time_zone(TZ), qid(Qid), get_source(Source), {V = date_with_timezone(P, TZ), most_general_type(Qid, Source, Source, datetime_with_timezone, T1, add, T)} | {V = P, T = T1}).
datetime_primary(V, T)---> value_expression_primary(V, T) | datetime_value_function(V, T).
time_zone(T)---> @at, time_zone_specifier(T).
time_zone_specifier(time_zone(T))---> @local, {T = local} | @time, @zone, interval_value_expression(T, _).
time_zone_field(T)---> (@timezone_hour, {T = timezone_hour} | @timezone_minute, {T = timezone_minute}).
datetime_type(T)---> @date, {T = date}
| @time, ( @left_paren, time_precision(P), @right_paren | {P = {no_precision}}), [ @with, @time, @zone], {T = time(P)}
| @timestamp, ( @left_paren, timestamp_precision(P), @right_paren | {P = {no_precision}}), [ @with, @time, @zone], {T = timestamp(P)}.
time_precision(P)---> precision(P).
timestamp_precision(P)---> precision(P).
character_set_specification(P) ---> #P.
% Not implemented
datetime_field(_)---> {fail}.
interval_qualifier(_)---> {fail}.
interval_type(_)---> {fail}.
string_value_function(_, _)---> {fail}.
bit_value_expression(_, _)---> {fail}.
% SQL Server 'features'
:-discontiguous(string_value_function/8).
string_value_function(ltrim(S), T)---> dbms('Microsoft SQL Server'), @ltrim, @left_paren, value_expression(S, T), @right_paren.
string_value_function(rtrim(S), T)---> dbms('Microsoft SQL Server'), @rtrim, @left_paren, value_expression(S, T), @right_paren.
string_value_function(left(S, N), T)---> dbms('Microsoft SQL Server'), @left, @left_paren, value_expression(S, ST), @comma, numeric_value_expression(N, _), @right_paren, get_source(Source), sized_varchar_type(N, Source, ST, T).
string_value_function(right(S, N), T)---> dbms('Microsoft SQL Server'), @right, @left_paren, value_expression(S, ST), @comma, numeric_value_expression(N, _), @right_paren, get_source(Source), sized_varchar_type(N, Source, ST, T).
string_value_function(isnull(P, C), T)---> dbms('Microsoft SQL Server'), @isnull(Source), {semantic_error(Source, deprecated(isnull, coalesce), 1)}, @left_paren, value_expression(P, T), @comma, value_expression(C, _), @right_paren. % According to the spec, the type of ISNULL is the first argument.
string_value_function(replace(S, M, R), T)---> dbms('Microsoft SQL Server'), @replace, @left_paren, string_value_expression(S, ST), @comma, string_value_expression(M, _), @comma, string_value_expression(R, _), @right_paren,
get_source(Source),
{type_merge_hint(T, max),
type_constraint(Qid, Source, T, native_type(varchar(8000))),
type_constraint(Qid, Source, T, ST)}.
string_value_function(upper(S), T)---> dbms('Microsoft SQL Server'), @upper, @left_paren, value_expression(S, T), @right_paren.
string_value_function(lower(S), T)---> dbms('Microsoft SQL Server'), @lower, @left_paren, value_expression(S, T), @right_paren.
string_value_function(substring(Source, Start, Length), T)--->
dbms('Microsoft SQL Server'), @substring, @left_paren, character_value_expression(Source, ST), @comma, numeric_value_expression(Start, _), @comma, numeric_value_expression(Length, _), @right_paren, get_source(Source), sized_varchar_type(Length, Source, ST, T).
string_value_function(datename(Type, Source), varchar) ---> dbms('Microsoft SQL Server'), @datename, @left_paren, sql_server_date_part(Type), @comma, datetime_value_expression(Source, _), @right_paren.
string_value_function(dbname({}), native_type(nvarchar(128)))---> dbms('Microsoft SQL Server'), @db_name, @left_paren, @right_paren.
string_value_function(permissions(S), varchar)---> dbms('Microsoft SQL Server'), @permissions, @left_paren, character_value_expression(S, _), @right_paren.
string_value_function(username(String), native_type(nvarchar(128)))---> dbms('Microsoft SQL Server'), @user_name, @left_paren, character_value_expression(String, _), @right_paren.
string_value_function(str(S), T)---> dbms('Microsoft SQL Server'), @str, @left_paren, qid(Qid), get_source(Source), {type_merge_hint(T, str), type_constraint(Qid, Source, T, native_type(varchar(1))), type_constraint(Qid, Source, T, ST)}, numeric_value_expression(S, ST), @right_paren.
:-discontiguous(datetime_value_function/8).
datetime_value_function(dateadd(Type, N, Source), native_type(datetime))---> dbms('Microsoft SQL Server'), @dateadd, @left_paren, sql_server_date_part(Type), @comma, numeric_value_expression(N, _), @comma, datetime_value_expression(Source, _), @right_paren.
:-discontiguous(numeric_value_function/8).
numeric_value_function(current_timestamp, native_type(datetime))---> @current_timestamp.
numeric_value_function(getdate({}), native_type(datetime))---> dbms('Microsoft SQL Server'), @getdate, @left_paren, @right_paren.
numeric_value_function(fn_now({}), native_type(datetime))---> dbms('Microsoft SQL Server'), @left_curly, @fn, @now, @left_paren, @right_paren, @right_curly, get_source(Source), {semantic_error(sql_escape, Source, 1)}.
numeric_value_function(isnull(P, C), T)---> dbms('Microsoft SQL Server'), @isnull(Source), {semantic_error(Source, deprecated(isnull, coalesce), 1)}, @left_paren, value_expression(P, T), @comma, value_expression(C, _), @right_paren.
numeric_value_function(datediff(Type, LHS, RHS), native_type(int))---> dbms('Microsoft SQL Server'), @datediff, @left_paren, sql_server_date_part(Type), @comma, datetime_value_expression(LHS, _), @comma, numeric_value_expression(RHS, _), @right_paren.
numeric_value_function(day(S), native_type(int))---> dbms('Microsoft SQL Server'), @day, @left_paren, datetime_value_expression(S, _), @right_paren.
numeric_value_function(month(S), native_type(int))---> dbms('Microsoft SQL Server'), @month, @left_paren, datetime_value_expression(S, _), @right_paren.
numeric_value_function(year(S), native_type(int))---> dbms('Microsoft SQL Server'), @year, @left_paren, datetime_value_expression(S, _), @right_paren.
numeric_value_function(datepart(Type, S), native_type(int))---> dbms('Microsoft SQL Server'), @datepart, @left_paren, sql_server_date_part(Type), @comma, datetime_value_expression(S, _), @right_paren.
numeric_value_function(charindex(Source, Search, Start), native_type(int))---> dbms('Microsoft SQL Server'), @charindex, @left_paren, character_value_expression(Source, _), @comma, string_value_expression(Search, _), ( @comma, numeric_value_expression(Start, _) | {Start = {no_start}}), @right_paren.
numeric_value_function(len(Source), native_type(int))---> dbms('Microsoft SQL Server'), @len, @left_paren, character_value_expression(Source, _), @right_paren.
numeric_value_function(abs(S), T)---> dbms('Microsoft SQL Server'), @abs, @left_paren, {force_type_not_domain(T)}, numeric_value_expression(S, T), @right_paren.
numeric_value_function(round(S, P), T)---> dbms('Microsoft SQL Server'), @round, @left_paren, {force_type_not_domain(T)}, numeric_value_expression(S, T), @comma, numeric_value_expression(P, _), @right_paren.
numeric_value_function(floor(S), T)---> dbms('Microsoft SQL Server'), @floor, @left_paren, numeric_value_expression(S, ST), @right_paren, qid(Qid), get_source(Source), {type_merge_hint(T, round), type_constraint(Qid, Source, T, ST), type_constraint_ready(Qid, T)}.
numeric_value_function(ceiling(S), native_type(int))---> dbms('Microsoft SQL Server'), @ceiling, @left_paren, numeric_value_expression(S, _), @right_paren.
sql_server_date_part(T)---> ( @year | @yy | @yyyy), {T = year}
| (@quarter | @qq | @q ), {T = quarter}
| (@month | @mm | @m), {T = month}
| (@dayofyear | @dy), {T = dayofyear}
| (@day | @dd | @d | #literal(day, _), get_source(Source), {semantic_error(superfluous_quote(day), Source, 1)}), {T = day}
| (@week | @wk | @ww), {T = week}
| (@weekday | @dw | @w), {T = weekday}
| (@hour | @hh), {T = hour}
| (@minute | @mi | @n), {T = minute}
| (@second | @ss | @s), {T = second}
| (@millisecond | @ms), {T = millisecond}
| (@microsecond | @mcs), {T = microsecond}
| (@nanosecond | @ns), {T = nanosecond}.
:-discontiguous(cast_specification/8).
cast_specification(precision_cast(Target, Operand, P), Type)---> dbms('Microsoft SQL Server'), @convert, @left_paren, cast_target(Target), @comma, cast_operand(Operand), ( @comma, precision(P) | {P = {no_precision}} ), @right_paren, {strip_sql_comments(Target, Type)}.
top_clause(top(N))---> @top, numeric_value_expression(NN, _T), ( @percent, get_source(Source), {semantic_error(percent, Source, 1)}, {N = percent(NN)} | {N = NN}). % TBD: Check that T is integer!
limit_clause(top(N))---> @limit, numeric_value_expression(N, _T). % TBD: Check that T is integer!
with_attribute(With)---> @with, @schemabinding, {With = with(schemabinding)} % schema_bound_view(ViewName)
| {With = {no_with}}. % view_attribute can also be ENCRYPTION or VIEW_METADATA, not used
with_clause(with(nolock))---> @with, @left_paren, @nolock, @right_paren.
with_clause(with(noexpand))---> @with, @left_paren, @noexpand, @right_paren. % eg force use of indexed views
for_clause(for(xml_path(I)))---> @for, @xml, @path, @left_paren, string_value_expression(I, _), @right_paren, qid(Q), {query_is_xml(Q)}.
:-discontiguous(grouping_column_reference/7).
grouping_column_reference(group_expression(Expression, Collate))---> dbms('Microsoft SQL Server'), value_expression(Expression, _), ( collate_clause(Collate) | {Collate = {no_collation}} ).
:-discontiguous(sort_key/7).
sort_key(sort_expression(Expression))---> dbms('Microsoft SQL Server'), value_expression(Expression, _).
:-discontiguous(datetime_type/7).
datetime_type(datetime)---> @datetime.
sized_varchar_type(L, L, O, O, P0, P0, Length, Source, SourceT, T):-
memberchk(query_id(Qid), O),
strip_sql_comments(Length, LS),
( integer(LS) ->
% substring(foo, 5000) is the min of (5000, len(foo)). Create a new type resolution branch
type_merge_hint(T, sized_varchar),
type_constraint(Qid, Source, T, native_type(varchar(LS))),
type_constraint(Qid, Source, T, SourceT)
; otherwise->
force_type_not_domain(T),
type_constraint(Qid, Source, T, SourceT),
type_constraint_ready(Qid, T)
).
sql_explain(_).
user:goal_expansion(sql_explain(_), true).
%user:goal_expansion(sql_explain(A), (format(user_error, '*** ~w~n', [A]))).
remove_quoted_column @
type_constraint(QueryId, Source, Type, typeof(identifier(A, B), literal(ColumnName, string)))
<=>
type_constraint(QueryId, Source, Type, typeof(identifier(A, B), ColumnName)).
define_type_from_subquery @
derived_query_column(QueryId, TableAlias, Column, DerivedType)
\
type_constraint(QueryId, Source, Type, typeof(identifier(_, TableAlias), Column))
<=>
type_constraint(QueryId, Source, Type, DerivedType).
define_type_from_subquery_with_unspecified_column @
derived_query_column(QueryId, _, Column, DerivedType)
\
type_constraint(QueryId, Source, Type, typeof({no_qualifier}, Column))
<=>
type_constraint(QueryId, Source, Type, DerivedType).
define_type_from_literal @
type_constraint(QueryId, Source, Type, typeof({no_qualifier}, literal(Literal, Kind)))
<=>
( Literal == '' ->
ColumnType = native_type(varchar(1)) % Quirk?
; Kind == string->
atom_length(Literal, L),
ColumnType = native_type(varchar(L))
; otherwise->
ColumnType = native_type(Kind)
),
type_constraint(QueryId, Source, Type, ColumnType).
define_type_from_query @
query_table(QueryId, TableAlias, identifier(_, TableName))
\
type_constraint(QueryId, Source, Type, typeof(identifier(_, TableAlias), SourceColumnName))
<=>
default_schema(Schema),
fetch_database_attribute(_, Schema, TableName, SourceColumnName, ColumnType, _, _, _)
|
type_constraint(QueryId, Source, Type, ColumnType).
define_type_from_query_with_unnamed_table @
query_table(QueryId, _, identifier(_, TableName))
\
type_constraint(QueryId, Source, Type, typeof({no_qualifier}, SourceColumnName))
<=>
% Have to search all tables :-(
default_schema(Schema),
%writeln(checking(Schema, TableName, SourceColumnName)),
fetch_database_attribute(_, Schema, TableName, SourceColumnName, ColumnType, _, _, _)
%writeln(found)
|
type_constraint(QueryId, Source, Type, ColumnType).
define_type_from_uncorrelated_table_with_explicit_reference @ % Yuck!
query_table(QueryId, uncorrelated(TableName), _)
\
type_constraint(QueryId, Source, Type, typeof(identifier(_, TableName), SourceColumnName))
<=>
default_schema(Schema),
fetch_database_attribute(_, Schema, TableName, SourceColumnName, ColumnType, _, _, _)
|
type_constraint(QueryId, Source, Type, ColumnType).
define_type_from_uncorrelated_table @
query_table(QueryId, uncorrelated(TableName), _)
\
type_constraint(QueryId, Source, Type, typeof(X, SourceColumnName))
<=>
X \= identifier(_,_),
% Have to search all tables here, too :-(
default_schema(Schema),
fetch_database_attribute(_, Schema, TableName, SourceColumnName, ColumnType, _, _, _)
|
type_constraint(QueryId, Source, Type, ColumnType).
crush_xml_subquery_into_scalar @
query_is_xml(SubQueryId),
subquery(QueryId, SubQueryId)
\
type_constraint(QueryId, Source, Type, scalar([merged(_, _, _Subtype)]))
<=>
sql_explain(crush_xml),
type_constraint(QueryId, Source, Type, native_type(nvarchar(max))).
crush_subquery_into_scalar @
type_constraint(QueryId, Source, Type, scalar([merged(_, _, Subtype)]))
<=>
sql_explain(crush_subquery),
type_constraint(QueryId, Source, Type, Subtype).
concatenate_char @
type_merge_hint(Type, Hint),
type_constraint(QueryId, Source1, Type, native_type(varchar(N))),
type_constraint(QueryId, Source2, Type, native_type(varchar(M)))
<=>
Hint == add ; Hint == concatenate
|
( N == max ->
Z = max
; M == max ->
Z = max
; otherwise ->
Z is min(N+M, 8000)
),
sql_explain(concatenate_char),
merge_sources(Source1, Source2, Source),
type_constraint(QueryId, Source, Type, native_type(varchar(Z))),
type_constraint_ready(QueryId, Type).
concatenate_nchar_and_varchar @
type_merge_hint(Type, Hint),
type_constraint(QueryId, Source1, Type, native_type(nvarchar(N))),
type_constraint(QueryId, Source2, Type, native_type(varchar(M)))
<=>
Hint == add ; Hint == concatenate
|
( N == max ->
Z = max
; M == max ->
Z = max
; otherwise->
Z is min(N+M, 8000)
),
sql_explain(concatenate_nchar_and_varchar),
merge_sources(Source1, Source2, Source),
type_constraint(QueryId, Source, Type, native_type(nvarchar(Z))),
type_constraint_ready(QueryId, Type).