/
utils.go
734 lines (649 loc) · 22.7 KB
/
utils.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
/*
Copyright 2019, Cossack Labs Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package encryptor
import (
"context"
"errors"
"strconv"
"strings"
"sync"
"github.com/sirupsen/logrus"
"github.com/cossacklabs/acra/decryptor/base"
"github.com/cossacklabs/acra/encryptor/config"
"github.com/cossacklabs/acra/sqlparser"
)
// InvalidPlaceholderIndex value that represent invalid index for sql placeholders
const InvalidPlaceholderIndex = -1
var (
errNotFoundtable = errors.New("not found table for alias")
errNotSupported = errors.New("not supported type of sql node")
errTableAlreadyMatched = errors.New("aliased table name already matched")
errAliasedTableNotMatched = errors.New("aliases table not matched")
errEmptyTableExprs = errors.New("empty table exprs")
)
// ColumnInfo info object that represent column data
type ColumnInfo struct {
Name string
Table string
Alias string
}
// ParseQuerySettings parse list of select query settings based on schemaStore
func ParseQuerySettings(ctx context.Context, statement *sqlparser.Select, schemaStore config.TableSchemaStore) ([]*QueryDataItem, error) {
columns, err := MapColumnsToAliases(statement, schemaStore)
if err != nil {
logrus.WithError(err).Errorln("Can't extract columns from SELECT statement")
return nil, err
}
querySelectSettings := make([]*QueryDataItem, 0, len(columns))
for _, data := range columns {
if data != nil {
if schema := schemaStore.GetTableSchema(data.Table); schema != nil {
var setting *QueryDataItem = nil
if data.Name == "*" {
for _, name := range schema.Columns() {
setting = nil
if columnSetting := schema.GetColumnEncryptionSettings(name); columnSetting != nil {
setting = NewQueryDataItem(columnSetting, data.Table, name, "")
}
querySelectSettings = append(querySelectSettings, setting)
}
} else {
if columnSetting := schema.GetColumnEncryptionSettings(data.Name); columnSetting != nil {
setting = NewQueryDataItem(columnSetting, data.Table, data.Name, data.Alias)
}
querySelectSettings = append(querySelectSettings, setting)
}
continue
}
}
querySelectSettings = append(querySelectSettings, nil)
}
return querySelectSettings, nil
}
// FilterTableExpressions check if sqlparser.Statement contains TableExprs
func FilterTableExpressions(statement sqlparser.Statement) (sqlparser.TableExprs, error) {
switch query := statement.(type) {
case *sqlparser.Select:
return query.From, nil
case *sqlparser.Update:
return query.TableExprs, nil
case *sqlparser.Delete:
return query.TableExprs, nil
case *sqlparser.Insert:
// only support INSERT INTO table2 SELECT * FROM test_table WHERE data1='somedata' syntax for INSERTs
if selectInInsert, ok := query.Rows.(*sqlparser.Select); ok {
return selectInInsert.From, nil
}
return nil, ErrUnsupportedQueryType
default:
return nil, ErrUnsupportedQueryType
}
}
// GetColumnSetting get ColumnEncryptionSetting from schemaStore based on tableName and column
func GetColumnSetting(column *sqlparser.ColName, tableName string, schemaStore config.TableSchemaStore) config.ColumnEncryptionSetting {
schema := schemaStore.GetTableSchema(tableName)
if schema == nil {
return nil
}
// Also leave out those columns which are not searchable.
columnName := column.Name.ValueForConfig()
return schema.GetColumnEncryptionSettings(columnName)
}
// GetWhereStatements parse all Where expressions
func GetWhereStatements(stmt sqlparser.Statement) ([]*sqlparser.Where, error) {
var whereStatements []*sqlparser.Where
err := sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch nodeType := node.(type) {
case *sqlparser.Where:
whereStatements = append(whereStatements, nodeType)
case sqlparser.JoinCondition:
whereStatements = append(whereStatements, &sqlparser.Where{
Type: "on",
Expr: nodeType.On,
})
}
return true, nil
}, stmt)
return whereStatements, err
}
// FindColumnInfo get ColumnInfo from TableExprs, ColName and TableSchemaStore
func FindColumnInfo(fromExpr sqlparser.TableExprs, colName *sqlparser.ColName, schemaStore config.TableSchemaStore) (ColumnInfo, error) {
var alias = colName.Qualifier.Name.RawValue()
var columnName = colName.Name.ValueForConfig()
if alias == "" {
columnTable, err := getMatchedTable(fromExpr, colName, schemaStore)
if err != nil {
return ColumnInfo{}, err
}
alias = columnTable
}
info, err := findTableName(alias, columnName, fromExpr)
if err != nil {
return ColumnInfo{}, err
}
info.Alias = alias
return info, nil
}
// MapColumnsToAliases parse slice of ColumnInfo from sqlparser.Select and config.TableSchemaStore
func MapColumnsToAliases(selectQuery *sqlparser.Select, tableSchemaStore config.TableSchemaStore) ([]*ColumnInfo, error) {
out := make([]*ColumnInfo, 0, len(selectQuery.SelectExprs))
var joinTables []string
var joinAliases map[string]string
if joinExp, ok := selectQuery.From[0].(*sqlparser.JoinTableExpr); ok {
joinTables = make([]string, 0)
joinAliases = make(map[string]string)
if ok := parseJoinTablesInfo(joinExp, &joinTables, joinAliases); !ok {
return nil, errUnsupportedExpression
}
}
for _, expr := range selectQuery.SelectExprs {
aliased, ok := expr.(*sqlparser.AliasedExpr)
if ok {
// processing queries like `select (select value from table2) from table1`
// subquery should return only one value
subQuery, ok := aliased.Expr.(*sqlparser.Subquery)
if ok {
if subSelect, ok := subQuery.Select.(*sqlparser.Select); ok {
if len(subSelect.SelectExprs) != 1 {
return nil, errUnsupportedExpression
}
if _, ok := subSelect.SelectExprs[0].(*sqlparser.StarExpr); ok {
return nil, errUnsupportedExpression
}
subColumn, err := MapColumnsToAliases(subSelect, tableSchemaStore)
if err != nil {
return nil, err
}
out = append(out, subColumn...)
continue
}
}
colName, ok := aliased.Expr.(*sqlparser.ColName)
if ok {
info, err := FindColumnInfo(selectQuery.From, colName, tableSchemaStore)
if err == nil {
out = append(out, &info)
continue
}
}
}
starExpr, ok := expr.(*sqlparser.StarExpr)
if ok {
if len(joinTables) > 0 {
if !starExpr.TableName.Name.IsEmpty() {
joinTable, ok := joinAliases[starExpr.TableName.Name.ValueForConfig()]
if !ok {
return nil, errUnsupportedExpression
}
out = append(out, &ColumnInfo{Table: joinTable, Name: allColumnsName, Alias: allColumnsName})
continue
}
for i := len(joinTables) - 1; i >= 0; i-- {
out = append(out, &ColumnInfo{Table: joinTables[i], Name: allColumnsName, Alias: allColumnsName})
}
continue
}
tableName, err := getFirstTableWithoutAlias(selectQuery.From)
if err == nil {
out = append(out, &ColumnInfo{Table: tableName, Name: allColumnsName, Alias: allColumnsName})
} else {
if len(selectQuery.From) == 1 {
tableNameStr, err := getTableNameWithoutAliases(selectQuery.From[0])
if err != nil {
return nil, err
}
out = append(out, &ColumnInfo{Table: tableNameStr, Name: allColumnsName, Alias: allColumnsName})
continue
}
tableNameStr, err := findTableName(starExpr.TableName.Name.RawValue(), starExpr.TableName.Name.RawValue(), selectQuery.From)
if err != nil {
return nil, err
}
out = append(out, &ColumnInfo{Table: tableNameStr.Table, Name: allColumnsName, Alias: allColumnsName})
}
continue
}
out = append(out, nil)
}
return out, nil
}
// ParsePlaceholderIndex parse placeholder index if SQLVal is PgPlaceholder/ValArg otherwise return error and InvalidPlaceholderIndex
func ParsePlaceholderIndex(placeholder *sqlparser.SQLVal) (int, error) {
updateMapByPlaceholderPart := func(part string) (int, error) {
text := string(placeholder.Val)
index, err := strconv.Atoi(strings.TrimPrefix(text, part))
if err != nil {
logrus.WithField("placeholder", text).WithError(err).Warning("Cannot parse placeholder")
return InvalidPlaceholderIndex, err
}
// Placeholders use 1-based indexing and "values" (Go slice) are 0-based.
index--
return index, nil
}
switch placeholder.Type {
case sqlparser.PgPlaceholder:
// PostgreSQL placeholders look like "$1". Parse the number out of them.
return updateMapByPlaceholderPart("$")
case sqlparser.ValArg:
// MySQL placeholders look like ":v1". Parse the number out of them.
return updateMapByPlaceholderPart(":v")
}
return InvalidPlaceholderIndex, ErrInvalidPlaceholder
}
// ParseSearchQueryPlaceholdersSettings parse encryption settings of statement with placeholders
func ParseSearchQueryPlaceholdersSettings(statement sqlparser.Statement, schemaStore config.TableSchemaStore) map[int]config.ColumnEncryptionSetting {
tableExps, err := filterTableExpressions(statement)
if err != nil {
logrus.Debugln("Unsupported search query")
return nil
}
// Walk through WHERE clauses of a SELECT statements...
whereExprs, err := GetWhereStatements(statement)
if err != nil {
logrus.WithError(err).Debugln("Failed to extract WHERE clauses")
return nil
}
placeHolderSettings := make(map[int]config.ColumnEncryptionSetting)
for _, whereExpr := range whereExprs {
err = sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
comparisonExpr, ok := node.(*sqlparser.ComparisonExpr)
if !ok {
return true, nil
}
var colName *sqlparser.ColName
switch expr := comparisonExpr.Left.(type) {
case *sqlparser.ColName:
colName = expr
case *sqlparser.SubstrExpr:
colName = expr.Name
}
columnInfo, err := FindColumnInfo(tableExps, colName, schemaStore)
if err != nil {
return true, nil
}
lColumnSetting := GetColumnSetting(colName, columnInfo.Table, schemaStore)
if lColumnSetting == nil {
return true, nil
}
if !lColumnSetting.IsSearchable() && !lColumnSetting.IsConsistentTokenization() {
return true, nil
}
if sqlVal, ok := comparisonExpr.Right.(*sqlparser.SQLVal); ok && isSupportedSQLVal(sqlVal) {
if comparisonExpr.Operator == sqlparser.EqualStr || comparisonExpr.Operator == sqlparser.NotEqualStr || comparisonExpr.Operator == sqlparser.NullSafeEqualStr {
placeholderIndex, err := ParsePlaceholderIndex(sqlVal)
if err == ErrInvalidPlaceholder {
return true, nil
} else if err != nil {
return false, err
}
placeHolderSettings[placeholderIndex] = lColumnSetting
}
}
return true, nil
}, whereExpr)
}
return placeHolderSettings
}
const queryDataItemKey = "query_data_items"
// SaveQueryDataItemsToClientSession save slice of QueryDataItem into ClientSession
func SaveQueryDataItemsToClientSession(session base.ClientSession, items []*QueryDataItem) {
session.SetData(queryDataItemKey, items)
}
// DeleteQueryDataItemsFromClientSession delete items from ClientSession
func DeleteQueryDataItemsFromClientSession(session base.ClientSession) {
session.DeleteData(queryDataItemKey)
}
// QueryDataItemsFromClientSession return QueryDataItems from ClientSession if saved otherwise nil
func QueryDataItemsFromClientSession(session base.ClientSession) []*QueryDataItem {
data, ok := session.GetData(queryDataItemKey)
if !ok {
return nil
}
items, ok := data.([]*QueryDataItem)
if ok {
return items
}
return nil
}
var bindPlaceholdersPool = sync.Pool{New: func() interface{} {
return make(map[int]config.ColumnEncryptionSetting, 32)
}}
const placeholdersSettingKey = "bind_encryption_settings"
// PlaceholderSettingsFromClientSession return stored in client session ColumnEncryptionSettings related to placeholders
// or create new and save in session
func PlaceholderSettingsFromClientSession(session base.ClientSession) map[int]config.ColumnEncryptionSetting {
data, ok := session.GetData(placeholdersSettingKey)
if !ok {
//logger := logging.GetLoggerFromContext(session.Context())
value := bindPlaceholdersPool.Get().(map[int]config.ColumnEncryptionSetting)
//logger.WithField("session", session).WithField("value", value).Debugln("Create placeholders")
session.SetData(placeholdersSettingKey, value)
return value
}
items, ok := data.(map[int]config.ColumnEncryptionSetting)
if ok {
return items
}
return nil
}
// DeletePlaceholderSettingsFromClientSession delete items from ClientSession
func DeletePlaceholderSettingsFromClientSession(session base.ClientSession) {
data := PlaceholderSettingsFromClientSession(session)
if data == nil {
logrus.Warningln("Invalid type of PlaceholderSettings")
session.DeleteData(placeholdersSettingKey)
// do nothing because it's invalid
return
}
for key := range data {
delete(data, key)
}
bindPlaceholdersPool.Put(data)
session.DeleteData(placeholdersSettingKey)
}
// parseJoinTablesInfo recursively read and save sql join structure info, aliases map is used to save association between tables and its aliases,
// tables slice is used to collect certain order of tables (saved in reverse order of declaration).
// JoinTableExpr structure represent a recursive tree where RightExpr and LeftExpr are corresponded leaf node
// recursive processing starts from RightExpr leaf to the LeftExpr one, and when cast LeftExpr to AliasedTableExpr is successful
// it means that we reach last leaf in the tree.
func parseJoinTablesInfo(joinExp *sqlparser.JoinTableExpr, tables *[]string, aliases map[string]string) bool {
aliased, ok := joinExp.LeftExpr.(*sqlparser.AliasedTableExpr)
if ok {
// here we reach the last leaf in the JoinTableExpr recursive tree, processing SHOULD be stopped in this block.
// and we should process remaining RightExpr and LeftExpr leafs more before exit.
ok := getRightJoinTableInfo(joinExp, tables, aliases)
if !ok {
return false
}
_, ok = aliased.Expr.(*sqlparser.Subquery)
if ok {
// add subquery processing if needed
return true
}
tableName, ok := aliased.Expr.(sqlparser.TableName)
if !ok {
return false
}
alias := aliased.As.RawValue()
if aliased.As.RawValue() == "" {
alias = tableName.Name.RawValue()
}
*tables = append(*tables, tableName.Name.RawValue())
aliases[alias] = tableName.Name.RawValue()
return true
}
ok = getRightJoinTableInfo(joinExp, tables, aliases)
if !ok {
return false
}
joinExp, ok = joinExp.LeftExpr.(*sqlparser.JoinTableExpr)
if !ok {
return false
}
return parseJoinTablesInfo(joinExp, tables, aliases)
}
// getRightJoinTableInfo return tableName and its alias for right join table
// in case of more complex JOINs constructions like `JOIN (table1 AS t1 JOIN table2 AS t2 ON ... JOIN table3 ...) ON ...`
// represented by sqlparser.ParenTableExpr it runs parseJoinTablesInfo itself recursively to collect tableName and its alias info inside this block
func getRightJoinTableInfo(joinExp *sqlparser.JoinTableExpr, tables *[]string, aliases map[string]string) bool {
parentExpr, ok := joinExp.RightExpr.(*sqlparser.ParenTableExpr)
if ok {
for _, expr := range parentExpr.Exprs {
innerJoinExpr, ok := expr.(*sqlparser.JoinTableExpr)
if !ok {
continue
}
return parseJoinTablesInfo(innerJoinExpr, tables, aliases)
}
}
rAliased, ok := joinExp.RightExpr.(*sqlparser.AliasedTableExpr)
if !ok {
return false
}
tableName, ok := rAliased.Expr.(sqlparser.TableName)
if !ok {
return false
}
alias := rAliased.As.RawValue()
if rAliased.As.RawValue() == "" {
alias = tableName.Name.RawValue()
}
if _, ok := aliases[alias]; !ok {
*tables = append(*tables, tableName.Name.RawValue())
aliases[alias] = tableName.Name.RawValue()
}
return true
}
// getJoinFirstTableWithoutAlias recursively process JoinTableExpr tree until it reaches the first table in JOIN declarations
// used to handle queries like this `select table1.column1, column2, column3 from table1 join table2 as t2` and match column2 to table1
func getJoinFirstTableWithoutAlias(joinExp *sqlparser.JoinTableExpr) (string, bool) {
aliased, ok := joinExp.LeftExpr.(*sqlparser.AliasedTableExpr)
if ok {
return getNonAliasedName(aliased)
}
joinExp, ok = joinExp.LeftExpr.(*sqlparser.JoinTableExpr)
if !ok {
return "", false
}
return getJoinFirstTableWithoutAlias(joinExp)
}
// getFirstTableWithoutAlias search table name from "FROM" expression which has not any alias
// if more than one table specified without alias then return errNotFoundTable
func getFirstTableWithoutAlias(fromExpr sqlparser.TableExprs) (string, error) {
if len(fromExpr) == 0 {
return "", errEmptyTableExprs
}
if joinExp, ok := fromExpr[0].(*sqlparser.JoinTableExpr); ok {
tableName, ok := getJoinFirstTableWithoutAlias(joinExp)
if !ok {
return "", errNotFoundtable
}
return tableName, nil
}
var name string
for _, tblExpr := range fromExpr {
aliased, ok := tblExpr.(*sqlparser.AliasedTableExpr)
if !ok {
continue
}
tName, ok := getNonAliasedName(aliased)
if !ok {
continue
}
if name != "" {
return "", errors.New("more than 1 table without alias")
}
name = tName
}
if name == "" {
return "", errNotFoundtable
}
return name, nil
}
func getMatchedTable(fromExpr sqlparser.TableExprs, colName *sqlparser.ColName, tableSchemaStore config.TableSchemaStore) (string, error) {
if len(fromExpr) == 0 {
return "", errEmptyTableExprs
}
if joinExp, ok := fromExpr[0].(*sqlparser.JoinTableExpr); ok {
tableName, ok := getJoinFirstTableWithoutAlias(joinExp)
if !ok {
return "", errNotFoundtable
}
return tableName, nil
}
isTableColumn := func(tableSchema config.TableSchema, colName *sqlparser.ColName) bool {
for _, column := range tableSchema.Columns() {
if column == colName.Name.ValueForConfig() {
return true
}
}
return false
}
var alisedName string
for _, exp := range fromExpr {
aliased, ok := exp.(*sqlparser.AliasedTableExpr)
if !ok {
continue
}
tableName, ok := aliased.Expr.(sqlparser.TableName)
if !ok {
return "", errUnsupportedExpression
}
tableSchema := tableSchemaStore.GetTableSchema(tableName.Name.ValueForConfig())
if tableSchema == nil {
continue
}
if isTableColumn(tableSchema, colName) {
getTableName := getAliasedName
if aliased.As.IsEmpty() {
getTableName = getNonAliasedName
}
tName, ok := getTableName(aliased)
if !ok {
return "", errUnsupportedExpression
}
if alisedName != "" {
logrus.WithField("alias", alisedName).Infoln("Ambiguous column found, several tables contain the same column")
return "", errTableAlreadyMatched
}
alisedName = tName
}
}
if alisedName == "" {
return "", errAliasedTableNotMatched
}
return alisedName, nil
}
func getAliasedName(aliased *sqlparser.AliasedTableExpr) (string, bool) {
if _, ok := aliased.Expr.(sqlparser.TableName); !ok {
return "", false
}
if aliased.As.IsEmpty() {
return "", false
}
return aliased.As.ValueForConfig(), true
}
func getNonAliasedName(aliased *sqlparser.AliasedTableExpr) (string, bool) {
if !aliased.As.IsEmpty() {
return "", false
}
tableName, ok := aliased.Expr.(sqlparser.TableName)
if !ok {
return "", false
}
return tableName.Name.ValueForConfig(), true
}
func getTableNameWithoutAliases(expr sqlparser.TableExpr) (string, error) {
aliased, ok := expr.(*sqlparser.AliasedTableExpr)
if !ok {
return "", errNotFoundtable
}
tableName, ok := aliased.Expr.(sqlparser.TableName)
if !ok {
return "", errNotFoundtable
}
return tableName.Name.RawValue(), nil
}
func findTableName(alias, columnName string, expr sqlparser.SQLNode) (ColumnInfo, error) {
switch val := expr.(type) {
case sqlparser.TableExprs:
// FROM table1, table2, join ....
// search through list of tables by specific type of sql node (AliasedTableExpr, Join, ...)
for _, tblExpr := range val {
result, err := findTableName(alias, columnName, tblExpr)
if err == nil {
return result, nil
}
}
return ColumnInfo{}, errNotFoundtable
case sqlparser.TableName:
// table1, should be equal to end alias value
if alias == val.Name.ValueForConfig() {
return ColumnInfo{Name: columnName, Table: alias}, nil
}
return ColumnInfo{}, errNotFoundtable
case *sqlparser.AliasedTableExpr:
if val.As.IsEmpty() {
return findTableName(alias, columnName, val.Expr)
}
if val.As.RawValue() == alias {
if tblName, ok := val.Expr.(sqlparser.TableName); ok {
return findTableName(tblName.Name.ValueForConfig(), columnName, val.Expr)
}
return findTableName("", columnName, val.Expr)
}
case *sqlparser.Subquery:
return findTableName(alias, columnName, val.Select)
case *sqlparser.Select:
for _, expr := range val.SelectExprs {
if aliasExpr, ok := expr.(*sqlparser.AliasedExpr); ok {
if aliasExpr.As.IsEmpty() {
// select t1.col1
switch aliasVal := aliasExpr.Expr.(type) {
case *sqlparser.ColName:
if aliasVal.Qualifier.IsEmpty() {
// select col1
if aliasVal.Name.EqualString(columnName) {
// find first table in FROM list
firstTable, err := getFirstTableWithoutAlias(val.From)
if err != nil {
continue
}
return ColumnInfo{Name: columnName, Table: firstTable}, nil
}
} else {
// t1.col1 == col1 so we should find source name of t1.
if aliasVal.Name.EqualString(columnName) {
return findTableName(aliasVal.Qualifier.Name.RawValue(), aliasVal.Name.String(), val.From)
}
}
continue
}
} else if aliasExpr.As.EqualString(alias) || (alias == "" && aliasExpr.As.EqualString(columnName)) {
// select t1.col1 as columnName
switch aliasVal := aliasExpr.Expr.(type) {
case *sqlparser.ColName:
if aliasVal.Qualifier.Name.RawValue() == "" {
firstTable, err := getFirstTableWithoutAlias(val.From)
if err != nil {
return ColumnInfo{}, err
}
return findTableName(firstTable, aliasVal.Name.String(), val.From)
}
return findTableName(aliasVal.Qualifier.Name.RawValue(), aliasVal.Name.String(), val.From)
}
}
}
}
case *sqlparser.JoinTableExpr:
result, err := findTableName(alias, columnName, val.LeftExpr)
if err == errNotFoundtable {
return findTableName(alias, columnName, val.RightExpr)
}
return result, err
case *sqlparser.Union:
// may be different pairs of table + column at same position of result row
return ColumnInfo{}, errNotSupported
case *sqlparser.ParenSelect:
return findTableName(alias, columnName, val.Select)
case *sqlparser.ParenTableExpr:
for _, exr := range val.Exprs {
result, err := findTableName(alias, columnName, exr)
if err == nil {
return result, nil
}
}
return ColumnInfo{}, errNotFoundtable
}
return ColumnInfo{}, errNotFoundtable
}