/
sql.go
2114 lines (2027 loc) · 52 KB
/
sql.go
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
// Package rel are the AST Structures and Parsers
// for the SQL, FilterQL, and Expression dialects.
package rel
import (
"bytes"
"encoding/json"
"fmt"
"hash/fnv"
"io"
"sort"
"strings"
u "github.com/araddon/gou"
"github.com/gogo/protobuf/proto"
"github.com/araddon/qlbridge/expr"
"github.com/araddon/qlbridge/lex"
"github.com/araddon/qlbridge/value"
)
var (
// Ensure SqlSelect and cousins etc are SqlStatements
_ SqlStatement = (*SqlSelect)(nil)
_ SqlStatement = (*SqlInsert)(nil)
_ SqlStatement = (*SqlUpsert)(nil)
_ SqlStatement = (*SqlUpdate)(nil)
_ SqlStatement = (*SqlDelete)(nil)
_ SqlStatement = (*SqlShow)(nil)
_ SqlStatement = (*SqlDescribe)(nil)
_ SqlStatement = (*SqlCommand)(nil)
_ SqlStatement = (*SqlInto)(nil)
// sub-query statements
_ SqlSourceStatement = (*SqlSource)(nil)
// Statements with Columns
_ ColumnsStatement = (*SqlSelect)(nil)
// A select * columns
starCols Columns
)
func init() {
starCols = make(Columns, 1)
starCols[0] = NewColumnFromToken(lex.Token{T: lex.TokenStar, V: "*"})
}
type (
// ColumnsStatement is a statement interface for those statements that
// have columns that need to be added during parse.
ColumnsStatement interface {
AddColumn(col Column) error
}
// SqlStatement interface, to define the sql statement
// Select, Insert, Update, Delete, Command, Show, Describe etc
SqlStatement interface {
// string representation of Node, AST parseable back to itself
String() string
// Write out this statement in a specific dialect
WriteDialect(w expr.DialectWriter)
// SQL keyword (select, insert, etc)
Keyword() lex.TokenType
}
// SqlSourceStatement interface, to define the subselect/join-types
// Join, SubSelect, From
SqlSourceStatement interface {
// string representation of Node, AST parseable back to itself
String() string
// Write out this statement in a specific dialect
WriteDialect(w expr.DialectWriter)
// SQL Keyword for this statement
Keyword() lex.TokenType
}
)
type (
// PreparedStatement Prepared/Aliased SQL statement
PreparedStatement struct {
Alias string
Statement SqlStatement
}
// SqlSelect SQL Select statement
SqlSelect struct {
Db string // If provided a use "dbname"
Raw string // full original raw statement
Star bool // for select * from ...
Distinct bool // Distinct flag?
Columns Columns // An array (ordered) list of columns
From []*SqlSource // From, Join
Into *SqlInto // Into "table"
Where *SqlWhere // Expr Node, or *SqlSelect
Having expr.Node // Filter results
GroupBy Columns
OrderBy Columns
Limit int
Offset int
Alias string // Non-Standard sql, alias/name of sql another way of expression Prepared Statement
With u.JsonHelper // Non-Standard SQL for properties/config info, similar to Cassandra with, purse json
proj *Projection // Projected fields
isAgg bool // is this an aggregate query? has group-by, or aggregate selector expressions (count, cardinality etc)
finalized bool // have we already finalized, ie formalized left/right aliases
schemaqry bool // is this a schema qry? ie select @@max_packet etc
// Memoized sql, we assume this is an immuteable struct so if this is populated use it
pb *SqlStatementPb
fingerprintid int64
}
// SqlSource is a table name, sub-query, or join as used in
// SELECT <columns> FROM <SQLSOURCE>
// - SELECT .. FROM table_name
// - SELECT .. from (select a,b,c from tableb)
// - SELECT .. FROM tablex INNER JOIN ...
SqlSource struct {
final bool // has this been finalized?
alias string // either the short table name or full
cols map[string]*Column // Un-aliased columns, ie "x.y" -> "y"
colIndex map[string]int // Key(alias) to index in []driver.Value positions
joinNodes []expr.Node // x.y = q.y AND x.z = q.z --- []Node{Identity{x},Identity{z}}
Source *SqlSelect // Sql Select Source query, written by Rewrite
Raw string // Raw Partial Query
Name string // From Name (optional, empty if join, subselect)
Alias string // From name aliased
Schema string // FROM `schema`.`table`
Op lex.TokenType // In, =, ON
LeftOrRight lex.TokenType // Left, Right
JoinType lex.TokenType // INNER, OUTER
JoinExpr expr.Node // Join expression x.y = q.y
SubQuery *SqlSelect // optional, Join/SubSelect statement
// Plan Hints, move to a dedicated planner
Seekable bool
// Memoized sql, we assume this is an immuteable struct so if this is populated use it
pb *SqlSourcePb
}
// SqlWhere WHERE is select stmt, or set of expressions
// - WHERE x in (select name from q)
// - WHERE x = y
// - WHERE x = y AND z = q
// - WHERE tolower(x) IN (select name from q)
SqlWhere struct {
// Either Op + Source exists
Op lex.TokenType // (In|=|ON) for Select Clauses operators
Source *SqlSelect // IN (SELECT a,b,c from z)
// OR expr but not both
Expr expr.Node // x = y AND q > 5
}
// SqlInsert SQL Insert Statement
SqlInsert struct {
kw lex.TokenType // Insert, Replace
Table string // table name
Columns Columns // Column Names
Rows [][]*ValueColumn // Values to insert
Select *SqlSelect //
}
// SqlUpsert SQL Upsert Statement
SqlUpsert struct {
Columns Columns
Rows [][]*ValueColumn
Values map[string]*ValueColumn
Where *SqlWhere
Table string
}
// SqlUpdate SQL Update Statement
SqlUpdate struct {
Values map[string]*ValueColumn
Where *SqlWhere
Table string
}
// SqlDelete SQL Delete Statement
SqlDelete struct {
Table string
Where *SqlWhere
Limit int
}
// SqlShow SQL SHOW Statement
SqlShow struct {
Raw string // full raw statement
Db string // Database/Schema name
Full bool // SHOW FULL TABLE FROM
Scope string // {FULL, GLOBAL, SESSION}
ShowType string // object type, [tables, columns, etc]
From string // `table` or `schema`.`table`
Identity string // `table` or `schema`.`table`
Create bool
CreateWhat string
Where expr.Node
Like expr.Node
}
// SQL Describe statement
SqlDescribe struct {
Raw string // full original raw statement
Identity string // Describe
Tok lex.Token // Explain, Describe, Desc
Stmt SqlStatement
}
// SqlInto INTO statement (select a,b,c from y INTO z)
SqlInto struct {
Table string
}
// SqlCommand is admin command such as "SET", "USE"
SqlCommand struct {
kw lex.TokenType // SET or USE
Columns CommandColumns // can have multiple columns in command
Identity string //
Value expr.Node //
}
// SqlCreate SQL CREATE statement
SqlCreate struct {
Raw string // full original raw statement
Identity string // identity of table, view, etc
Tok lex.Token // CREATE [TABLE,VIEW,CONTINUOUSVIEW,TRIGGER] etc
OrReplace bool // OR REPLACE
IfNotExists bool // IF NOT EXISTS
Cols []*DdlColumn // columns
Engine map[string]interface{}
With u.JsonHelper
Select *SqlSelect
}
// SqlDrop SQL DROP statement
SqlDrop struct {
Raw string // full original raw statement
Identity string // identity of table, view, etc
Temp bool // Temp?
Tok lex.Token // DROP [TEMP] [TABLE,VIEW,CONTINUOUSVIEW,TRIGGER] etc
With u.JsonHelper
}
// SqlAlter SQL ALTER statement
SqlAlter struct {
Raw string // full original raw statement
Identity string // identity to alter
Tok lex.Token // ALTER [TABLE,VIEW,CONTINUOUSVIEW,TRIGGER] etc
Cols []*DdlColumn // columns
}
// Columns List of Columns in SELECT [columns]
Columns []*Column
// Column represents the Column as expressed in a [SELECT]
// expression
Column struct {
sourceQuoteByte byte // quote mark? [ or ` etc
asQuoteByte byte // quote mark [ or `
originalAs string // original as string
left string // users.col_name = "users"
right string // users.first_name = "first_name"
isLiteral bool // is this a literal column?
ParentIndex int // slice idx position in parent query cols
Index int // slice idx position in original query cols
SourceIndex int // slice idx position in source []driver.Value
SourceField string // field name of underlying field
SourceOriginal string // field name of underlying field without the "left.right" parse
As string // As field, auto-populate the Field Name if exists
Comment string // optional in-line comments
Order string // (ASC | DESC)
Star bool // *
Agg bool // aggregate function column? count(*), avg(x) etc
Expr expr.Node // Expression, optional, often Identity.Node
Guard expr.Node // column If guard, non-standard sql column guard
}
// ValueColumn List of Value columns in INSERT into TABLE (colnames) VALUES (valuecolumns)
ValueColumn struct {
Value value.Value
Expr expr.Node
}
// DdlColumn represents the Data Definition Column
DdlColumn struct {
Kw lex.TokenType // initial keyword (identity for normal, constraint, primary)
Null bool // Do we support NULL?
AutoIncrement bool // auto increment
IndexType string // index_type
IndexCols []string // index_col_name
RefTable string // refererence table
RefCols []string // ref cols
Default expr.Node // Default value
DataType string // data type
DataTypeSize int // Data Type Size: varchar(2000)
DataTypeArgs []expr.Node // data type args
Key lex.TokenType // UNIQUE | PRIMARY
Name string // name
Comment string // optional in-line comments
Expr expr.Node // Expression, optional, often Identity.Node but could be composite key
}
// ResultColumns List of ResultColumns used to describe projection response columns
ResultColumns []*ResultColumn
// Result Column used in projection
ResultColumn struct {
Final bool // Is this part of final projection (ie, response)
Name string // Original path/name for query field
ColPos int // Ordinal position in sql (or partial sql) statement
Col *Column // the original sql column
Star bool // Was this a select * ??
As string // aliased
Type value.ValueType // Data Type
}
// Projection describes the results to expect from sql statement
// ie the ResultColumns for a result-set
Projection struct {
Distinct bool
Final bool // Is this a Final Projection? or intermiediate?
colNames map[string]struct{}
Columns ResultColumns
// Memoized pb, we assume this is an immuteable struct so if this is populated use it
pb *ProjectionPb
}
// CommandColumns SQL commands such as:
// set autocommit
// SET @@local.sort_buffer_size=10000;
// USE myschema;
CommandColumns []*CommandColumn
// CommandColumn is single column such as "autocommit"
CommandColumn struct {
Expr expr.Node // column expression
Name string // Original path/name for command field
}
)
func NewSqlDialect() expr.DialectWriter {
return expr.NewKeywordDialect(SqlKeywords)
}
func NewProjection() *Projection {
return &Projection{Columns: make(ResultColumns, 0), colNames: make(map[string]struct{})}
}
func NewResultColumn(as string, ordinal int, col *Column, valtype value.ValueType) *ResultColumn {
rc := ResultColumn{Name: as, As: as, ColPos: ordinal, Col: col, Type: valtype}
if col != nil {
rc.Name = col.SourceField
}
return &rc
}
func NewSqlSelect() *SqlSelect {
req := &SqlSelect{}
req.Columns = make(Columns, 0)
return req
}
func NewSqlInsert() *SqlInsert {
req := &SqlInsert{}
req.Columns = make(Columns, 0)
return req
}
func NewSqlUpdate() *SqlUpdate {
req := &SqlUpdate{}
return req
}
func NewSqlUpsert() *SqlUpsert {
req := &SqlUpsert{}
return req
}
func NewSqlDelete() *SqlDelete {
return &SqlDelete{}
}
func NewPreparedStatement() *PreparedStatement {
return &PreparedStatement{}
}
func NewSqlCreate() *SqlCreate {
req := &SqlCreate{}
return req
}
func NewSqlDrop() *SqlDrop {
req := &SqlDrop{}
return req
}
func NewSqlInto(table string) *SqlInto {
return &SqlInto{Table: table}
}
func NewSqlSource(table string) *SqlSource {
return &SqlSource{Name: table}
}
func NewSqlWhere(where expr.Node) *SqlWhere {
return &SqlWhere{Expr: where}
}
func NewColumnFromToken(tok lex.Token) *Column {
_, r, _ := expr.LeftRight(tok.V)
v := tok.V
if tok.Quote != 0 {
//v = expr.IdentityMaybeQuote(tok.Quote, v)
}
return &Column{
As: tok.V,
sourceQuoteByte: tok.Quote,
asQuoteByte: tok.Quote,
SourceField: r,
SourceOriginal: v,
}
}
func NewColumnValue(tok lex.Token) *Column {
return &Column{
sourceQuoteByte: tok.Quote,
asQuoteByte: tok.Quote,
}
}
func NewColumn(col string) *Column {
return &Column{
As: col,
SourceField: col,
Expr: &expr.IdentityNode{Text: col},
}
}
// The source column name
func (m *ResultColumn) SourceName() string {
if m.Col != nil && m.Col.SourceField != "" {
return m.Col.SourceField
}
return m.Name
}
func (m *ResultColumn) Equal(s *ResultColumn) bool {
if m == nil && s == nil {
return true
}
if m == nil && s != nil {
return false
}
if m != nil && s == nil {
return false
}
if m.Final != s.Final {
return false
}
if m.Name != s.Name {
return false
}
if m.ColPos != s.ColPos {
return false
}
if m.Star != s.Star {
return false
}
if m.As != s.As {
return false
}
if m.Type != s.Type {
return false
}
if m.Col != nil && !m.Col.Equal(s.Col) {
//u.Warnf("Not Equal? %T vs %T", m.Col, s.Col)
//u.Warnf("t!=t: \n\t%#v\n\t%#v", m.Col, s.Col)
return false
}
return true
}
func resultColumnFromPb(pb *ResultColumnPb) *ResultColumn {
s := ResultColumn{}
s.Final = pb.GetFinal()
s.Name = pb.GetName()
s.ColPos = int(pb.GetColPos())
if pb.Column != nil {
s.Col = columnFromPb(pb.Column)
}
s.Star = pb.GetStar()
s.As = pb.GetAs()
s.Type = value.ValueType(pb.GetValueType())
return &s
}
func resultColumnToPb(m *ResultColumn) *ResultColumnPb {
s := &ResultColumnPb{}
if m.Col != nil {
s.Column = m.Col.ToPB()
}
if m.Final {
s.Final = &m.Final
}
if m.Star {
s.Star = &m.Star
}
s.Name = m.Name
s.ColPos = int32(m.ColPos)
s.As = m.As
s.ValueType = int32(m.Type)
return s
}
func (m *Projection) AddColumnShort(colName string, vt value.ValueType) {
//colName = strings.ToLower(colName)
// if _, exists := m.colNames[colName]; exists {
// return
// }
//u.Infof("adding column %s to %v", colName, m.colNames)
//m.colNames[colName] = struct{}{}
m.Columns = append(m.Columns, NewResultColumn(colName, len(m.Columns), nil, vt))
}
func (m *Projection) AddColumn(col *Column, vt value.ValueType) {
//colName := strings.ToLower(col.As)
// if _, exists := m.colNames[colName]; exists {
// return
// }
//m.colNames[colName] = struct{}{}
m.Columns = append(m.Columns, NewResultColumn(col.As, len(m.Columns), col, vt))
}
func (m *Projection) Equal(s *Projection) bool {
if m == nil && s == nil {
return true
}
if m == nil && s != nil {
return false
}
if m != nil && s == nil {
return false
}
if m.Distinct != s.Distinct {
return false
}
if len(m.colNames) != len(s.colNames) {
return false
}
for name := range m.colNames {
_, hasSameName := s.colNames[name]
if !hasSameName {
return false
}
}
if len(m.Columns) != len(s.Columns) {
return false
}
for i, c := range m.Columns {
if !c.Equal(s.Columns[i]) {
//u.Warnf("Not Equal? %T vs %T", c, s.Columns[i])
//u.Warnf("t!=t: \n\t%#v \n\t!= %#v", c, s.Columns[i])
return false
}
}
return true
}
func (m *Projection) FromPB(pb *ProjectionPb) *Projection {
return ProjectionFromPb(pb)
}
func (m *Projection) ToPB() *ProjectionPb {
if m.pb == nil {
m.pb = projectionToPb(m)
}
return m.pb
}
func ProjectionFromPb(pb *ProjectionPb) *Projection {
s := Projection{}
s.Distinct = pb.GetDistinct()
s.colNames = make(map[string]struct{}, len(pb.ColNames))
for _, name := range pb.ColNames {
s.colNames[name] = struct{}{}
}
s.Columns = make(ResultColumns, len(pb.Columns))
for i, pbc := range pb.Columns {
s.Columns[i] = resultColumnFromPb(pbc)
}
return &s
}
func projectionToPb(m *Projection) *ProjectionPb {
s := &ProjectionPb{}
s.Distinct = m.Distinct
if len(m.colNames) > 0 {
s.ColNames = make([]string, 0, len(m.colNames))
for name := range m.colNames {
s.ColNames = append(s.ColNames, name)
}
}
if len(m.Columns) > 0 {
s.Columns = make([]*ResultColumnPb, len(m.Columns))
for i, c := range m.Columns {
s.Columns[i] = resultColumnToPb(c)
}
}
return s
}
func (m *Columns) WriteDialect(w expr.DialectWriter) {
colCt := len(*m)
if colCt == 1 {
(*m)[0].WriteDialect(w)
return
} else if colCt == 0 {
return
}
for i, col := range *m {
if i != 0 {
io.WriteString(w, ", ")
}
col.WriteDialect(w)
}
}
func (m *Columns) String() string {
w := expr.NewDefaultWriter()
m.WriteDialect(w)
return w.String()
}
func (m *Columns) FieldNames() []string {
names := make([]string, len(*m))
for i, col := range *m {
names[i] = col.Key()
}
return names
}
func (m *Columns) UnAliasedFieldNames() []string {
names := make([]string, len(*m))
for i, col := range *m {
_, right, _ := col.LeftRight()
names[i] = right
}
return names
}
func (m *Columns) AliasedFieldNames() []string {
names := make([]string, len(*m))
for i, col := range *m {
names[i] = col.As
}
return names
}
func (m *Columns) ByName(name string) (*Column, bool) {
for _, col := range *m {
//u.Debugf("col.SourceField='%s' key()='%s' As='%s' ", col.SourceField, col.Key(), col.As)
if col.SourceField == name || col.Key() == name {
return col, true
}
}
return nil, false
}
func (m *Columns) ByAs(as string) (*Column, bool) {
for _, col := range *m {
if col.As == as {
return col, true
}
}
return nil, false
}
func (m Columns) Equal(cols Columns) bool {
if len(m) != len(cols) {
return false
}
for i, c := range m {
if !c.Equal(cols[i]) {
return false
}
}
return true
}
func (m *Column) Key() string {
if m.left != "" {
return m.right
}
return m.As
}
func (m *Column) String() string {
w := expr.NewDefaultWriter()
m.WriteDialect(w)
return w.String()
}
func (m *Column) WriteDialect(w expr.DialectWriter) {
if m.Star {
io.WriteString(w, "*")
return
}
exprStr := ""
if m.Expr != nil {
start := w.Len()
m.Expr.WriteDialect(w)
if w.Len() > start {
exprStr = w.String()[start:]
}
}
if m.asQuoteByte != 0 && m.originalAs != "" {
io.WriteString(w, " AS ")
w.WriteIdentity(m.As)
} else if m.originalAs != "" && exprStr != m.originalAs {
io.WriteString(w, " AS ")
w.WriteIdentity(m.originalAs)
} else if m.Expr == nil {
w.WriteIdentity(m.As)
}
if m.Guard != nil {
io.WriteString(w, " IF ")
m.Guard.WriteDialect(w)
}
if m.Order != "" {
io.WriteString(w, " ")
io.WriteString(w, m.Order)
}
}
// Is this a select count(*) column
func (m *Column) CountStar() bool {
if m.Expr == nil {
return false
}
if fn, ok := m.Expr.(*expr.FuncNode); ok {
if len(fn.Args) != 1 {
return false
}
return strings.ToLower(fn.Name) == "count" && fn.Args[0].String() == `*`
}
return false
}
func (m *Column) InFinalProjection() bool {
return m.ParentIndex >= 0
}
func (m *Column) IsLiteral() bool {
if m.Expr == nil {
return false
}
switch n := m.Expr.(type) {
case *expr.FuncNode:
// count(*)
// now()
// tolower(field_name)
idents := expr.FindAllIdentityField(n)
if len(idents) > 0 {
return false
}
if m.Agg && m.CountStar() {
return true
}
case *expr.IdentityNode:
if n.IsBooleanIdentity() {
return true
}
return false
case *expr.StringNode, *expr.NumberNode, *expr.ValueNode:
return true
default:
u.Warnf("Unknown Node column type? %T", n)
}
return false
}
func (m *Column) IsLiteralOrFunc() bool {
if m.Expr == nil {
return false
}
switch n := m.Expr.(type) {
case *expr.FuncNode:
// count(*)
// now()
// tolower(field_name)
return true
case *expr.IdentityNode:
// What about NULL?
if n.IsBooleanIdentity() {
return true
}
return false
case *expr.StringNode, *expr.NumberNode, *expr.ValueNode:
return true
}
return false
}
func (m *Column) Asc() bool {
return strings.ToLower(m.Order) == "asc"
}
func (m *Column) Equal(c *Column) bool {
if m == nil && c == nil {
return true
}
if m == nil && c != nil {
return false
}
if m != nil && c == nil {
return false
}
if m.sourceQuoteByte != c.sourceQuoteByte {
return false
}
if m.asQuoteByte != c.asQuoteByte {
return false
}
if m.originalAs != c.originalAs {
return false
}
if m.left != c.left {
return false
}
if m.right != c.right {
return false
}
if m.ParentIndex != c.ParentIndex {
return false
}
if m.Index != c.Index {
return false
}
if m.SourceIndex != c.SourceIndex {
return false
}
if m.SourceField != c.SourceField {
return false
}
if m.As != c.As {
return false
}
if m.Comment != c.Comment {
return false
}
if m.Order != c.Order {
return false
}
if m.Star != c.Star {
return false
}
if m.Expr != nil {
if !m.Expr.Equal(c.Expr) {
return false
}
}
if m.Guard != nil {
if !m.Guard.Equal(c.Guard) {
return false
}
}
return true
}
// CopyRewrite Create a new copy of this column for rewrite purposes removing alias
func (m *Column) CopyRewrite(alias string) *Column {
left, right, _ := m.LeftRight()
newCol := m.Copy()
//u.Warnf("in rewrite: Alias:'%s' '%s'.'%s' sourcefield:'%v'", alias, left, right, m.SourceField)
if left == alias {
newCol.SourceField = right
newCol.right = right
}
if newCol.Expr != nil {
_, right, _ := expr.LeftRight(newCol.Expr.String())
if right == m.SourceField {
newCol.Expr = &expr.IdentityNode{Text: right}
}
}
return newCol
}
// Copy - deep copy, shared nothing
func (m *Column) Copy() *Column {
return &Column{
sourceQuoteByte: m.sourceQuoteByte,
asQuoteByte: m.asQuoteByte,
originalAs: m.originalAs,
ParentIndex: m.ParentIndex,
Index: m.Index,
SourceField: m.SourceField,
As: m.right,
Comment: m.Comment,
Order: m.Order,
Star: m.Star,
Expr: m.Expr,
Guard: m.Guard,
}
}
func (m *Column) ToPB() *ColumnPb {
n := ColumnPb{}
n.SourceQuote = []byte{m.sourceQuoteByte}
n.AsQuoteByte = []byte{m.asQuoteByte}
if len(m.originalAs) > 0 {
n.OriginalAs = &m.originalAs
}
if len(m.left) > 0 {
n.Left = &m.left
}
if len(m.right) > 0 {
n.Right = &m.right
}
n.ParentIndex = int32(m.ParentIndex)
n.Index = int32(m.Index)
n.SourceIndex = int32(m.SourceIndex)
if len(m.SourceField) > 0 {
n.SourceField = &m.SourceField
}
n.As = m.As
if len(m.Comment) > 0 {
n.Comment = &m.Comment
}
if len(m.Order) > 0 {
n.Order = &m.Order
}
if m.Star {
n.Star = &m.Star
}
if m.Expr != nil {
n.Expr = m.Expr.NodePb()
}
if m.Guard != nil {
n.Guard = m.Guard.NodePb()
}
return &n
}
func columnFromPb(c *ColumnPb) *Column {
return &Column{
sourceQuoteByte: optionalByte(c.GetSourceQuote()),
asQuoteByte: optionalByte(c.GetAsQuoteByte()),
originalAs: c.GetOriginalAs(),
left: c.GetLeft(),
right: c.GetRight(),
ParentIndex: int(c.GetParentIndex()),
Index: int(c.GetIndex()),
SourceIndex: int(c.GetSourceIndex()),
SourceField: c.GetSourceField(),
As: c.GetAs(),
Order: c.GetOrder(),
Star: c.GetStar(),
Expr: expr.NodeFromNodePb(c.GetExpr()),
Guard: expr.NodeFromNodePb(c.GetGuard()),
}
}
// Return left, right values if is of form `table.column` and
// also return true/false for if it even has left/right
func (m *Column) LeftRight() (string, string, bool) {
if m.right == "" {
m.left, m.right, _ = expr.LeftRight(m.As)
}
return m.left, m.right, m.left != ""
}
func (m *PreparedStatement) Keyword() lex.TokenType { return lex.TokenPrepare }
func (m *PreparedStatement) String() string {
w := expr.NewDefaultWriter()
m.WriteDialect(w)
return w.String()
}
func (m *PreparedStatement) WriteDialect(w expr.DialectWriter) {
io.WriteString(w, "PREPARE ")
w.WriteIdentity(m.Alias)
io.WriteString(w, " FROM ")
m.Statement.WriteDialect(w)
}
func (m *SqlSelect) Keyword() lex.TokenType { return lex.TokenSelect }
func (m *SqlSelect) SystemQry() bool { return len(m.From) == 0 && m.schemaqry }
func (m *SqlSelect) SetSystemQry() { m.schemaqry = true }
func (m *SqlSelect) IsLiteral() bool { return len(m.From) == 0 }
func (m *SqlSelect) FromPB(spb *SqlSelectPb) *SqlSelect {
return SqlSelectFromPb(spb)
}
func (m *SqlSelect) ToPbStatement() *SqlStatementPb {
if m.pb == nil {
m.pb = &SqlStatementPb{Select: SqlSelectToPb(m)}
}
return m.pb
}
func (m *SqlSelect) ToPB() *SqlSelectPb {
return m.ToPbStatement().Select
}
func (m *SqlSelect) Copy() *SqlSelect {
pb := m.ToPB()
selCopy := SqlSelectFromPb(pb)
return selCopy
}
// SqlSelectToPb Given a select statement lets convert it into a PB statement
func SqlSelectToPb(m *SqlSelect) *SqlSelectPb {
return sqlSelectToPbDepth(m, 0)
}
func sqlSelectToPbDepth(m *SqlSelect, depth int) *SqlSelectPb {
//u.Debugf("SqlSelectToPb %d? %p", depth, m)
s := SqlSelectPb{}
s.Db = m.Db
s.Raw = m.Raw
s.Star = m.Star
s.Distinct = m.Distinct
s.Limit = int32(m.Limit)
s.Offset = int32(m.Offset)
s.IsAgg = m.isAgg
s.Finalized = m.finalized
s.Schemaqry = m.schemaqry
if len(m.Alias) > 0 {
s.Alias = &m.Alias
}
if m.Where != nil {
s.Where = SqlWhereToPb(m.Where)
}
if m.proj != nil {
s.Projection = projectionToPb(m.proj)
}
if m.Having != nil {
s.Having = m.Having.NodePb()
}
if len(m.Columns) > 0 {
s.Columns = ColumnsToPb(m.Columns)
}
if len(m.GroupBy) > 0 {
s.GroupBy = ColumnsToPb(m.GroupBy)
}
if len(m.OrderBy) > 0 {
s.OrderBy = ColumnsToPb(m.OrderBy)
}
if len(m.From) > 0 && depth == 0 {
s.From = make([]*SqlSourcePb, len(m.From))
for i, from := range m.From {
s.From[i] = from.ToPB()
}
}
if len(m.With) > 0 {
by, err := json.Marshal(m.With)
if err != nil {
u.Errorf("unhandled error json with? %v", err)
} else {
s.With = by
}
}
if m.Into != nil {
s.Into = &m.Into.Table
}
return &s