-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdriver.go
More file actions
1663 lines (1428 loc) · 40.5 KB
/
driver.go
File metadata and controls
1663 lines (1428 loc) · 40.5 KB
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 kdb
import (
"bytes"
"database/sql"
"errors"
"fmt"
"github.com/sdming/kdb/ansi"
"reflect"
"strconv"
"strings"
)
// // Queryer is a interface that query expression
// type Queryer interface {
// Query(source string, exp Expression) (sql.Rows, error)
// }
// // Execer is a interface that execute expression
// type Execer interface {
// Exec(source string, exp Expression) (sql.Result, error)
// }
type Driver interface {
Compiler
}
// Compiler is a interface that compile expression to native sql & args
type Compiler interface {
Compile(source string, exp Expression) (query string, args []interface{}, err error)
}
var _compilers = make(map[string]Compiler)
// RegisterCompiler makes a compiler available by the provided driver name.
func RegisterCompiler(driver string, compiler Compiler) {
if compiler == nil {
panic("register compiler is nil")
}
_compilers[driver] = compiler
}
// GetCompiler return a a compiler by driver name
func GetCompiler(driver string) (Compiler, error) {
c, ok := _compilers[driver]
if !ok {
return nil, errors.New(fmt.Sprint("can not get compiler:", driver))
}
return c, nil
}
// Schemaer is a interface that get schema of table,view,function
type Schemaer interface {
// Table return schema of table,view
Table(db *sql.DB, name string) (*ansi.DbTable, error)
// Function return schema of store procedure,function
Function(db *sql.DB, name string) (*ansi.DbFunction, error)
}
var _schemaers = make(map[string]Schemaer)
// RegisterSchemaer makes a schemaer available by the provided driver name.
func RegisterSchemaer(driver string, schemaer Schemaer) {
if schemaer == nil {
panic("register schemaer is nil")
}
_schemaers[driver] = schemaer
}
// GetSchemaer return a a schemaer by driver name
func GetSchemaer(driver string) (Schemaer, error) {
schema, ok := _schemaers[driver]
if !ok {
return nil, errors.New(fmt.Sprint("can not get schemaer:", driver))
}
return schema, nil
}
// Dialecter is interface of sql dialect
type Dialecter interface {
// Name return mysql,postgres,oracle,mssql,sqlite,...
Name() string
// SupportNamedParameter, like @para1
SupportNamedParameter() bool
// SupportIndexedParameter, like $1
SupportIndexedParameter() bool
// ParameterPlaceHolder, like ?, $, @
ParameterPlaceHolder() string
// QuoteString quote s as sql native string
QuoteString(s string) string
// Quote quote object name, like 'table', [table]
Quote(string) string
// TableSql return sql to query table schema of name
TableSql(name string) string
// ColumnsSql return sql to query table columns schema
ColumnsSql(name string) string
// FunctionSql return sql to query function schema of name
FunctionSql(name string) string
// ParametersSql return sql to query procedure paramters schema
ParametersSql(name string) string
// DbType convert native data type to ansi.DbType
DbType(nativeType string) ansi.DbType
// SplitStatement return string to split sql statement; return ; generally
SplitStatement() string
}
var _dialecters = make(map[string]Dialecter)
// RegisterDialecter makes a dialecter available by the provided driver name.
func RegisterDialecter(driver string, dialecter Dialecter) {
if dialecter == nil {
panic("register dialecter is nil")
}
_dialecters[driver] = dialecter
}
// GetDialecter return a a dialecter by driver name
func GetDialecter(driver string) (Dialecter, error) {
d, ok := _dialecters[driver]
if !ok {
return nil, errors.New(fmt.Sprint("can not get dialecter:", driver))
}
return d, nil
}
// DefaultDialecter return AnsiDialecter
func DefaultDialecter() Dialecter {
return AnsiDialecter{}
}
// AnsiDialecter is ansi sql dialect
type AnsiDialecter struct {
}
// Name return "ansi"
func (ad AnsiDialecter) Name() string {
return "ansi"
}
// SupportNamedParameter return false
func (ad AnsiDialecter) SupportNamedParameter() bool {
return false
}
// SupportIndexedParameter return false
func (ad AnsiDialecter) SupportIndexedParameter() bool {
return false
}
// ParameterPlaceHolder return ?
func (ad AnsiDialecter) ParameterPlaceHolder() string {
return " ? "
}
// QuoteString quote s as sql native string
func (ad AnsiDialecter) QuoteString(s string) string {
return "'" + s + "'"
}
// Quote quote s as "s"
func (ad AnsiDialecter) Quote(s string) string {
return "\"" + s + "\""
}
// TableSql return ""
func (ansi AnsiDialecter) TableSql(name string) string {
return ""
}
// ColumnsSql return sql to query table columns schema
func (ansi AnsiDialecter) ColumnsSql(name string) string {
return ""
}
// FunctionSql return ""
func (ad AnsiDialecter) FunctionSql(s string) string {
return ""
}
// ParametersSql return sql to query procedure paramters schema
func (ad AnsiDialecter) ParametersSql(name string) string {
return ""
}
// SplitStatement return ;
func (ad AnsiDialecter) SplitStatement() string {
return " ; "
}
func (ad AnsiDialecter) DbType(nativeType string) ansi.DbType {
switch strings.ToLower(nativeType) {
case "xml", "tinytext", "mediumtext", "longtext", "ntext", "text", "sysname", "sql_variant", "note", "memo", "clob":
return ansi.String
case "char", "character", "nchar", "varchar", "nvarchar", "string", "longvarchar", "longchar", "varyingcharacter":
return ansi.String
case "nativecharacter", "native character", "nativevaryingcharacter", "character varying":
return ansi.String
case "bit", "bool", "boolean", "yesno", "logical":
return ansi.Boolean
case "tinyint unsigned", "uint16", "smallint unsigned", "uint32", "integer unsigned", "uint64", "bigint unsigned", "unsigned, bigint", "int2", "int8":
return ansi.Int
case "tinyint", "smallint", "int", "mediumint", "bigint", "int16", "int32", "int64", "integer", "long":
return ansi.Int
case "bigserial", "serial", "smallserial":
return ansi.Int
case "identity", "counter", "autoincrement":
return ansi.Int
case "decimal", "newdecimal", "numeric":
return ansi.Numeric
case "currency", "money", "smallmoney":
return ansi.Numeric
case "float", "real", "double", "double precision":
return ansi.Float
case "date", "smalldate":
return ansi.Date
case "time", "datetime", "datetime2", "smalldatetime", "timestamp", "timestamp without time zone", "timestamp with time zone":
return ansi.DateTime
case "year":
return ansi.Int
case "image", "varbinary", "binary", "blob", "tinyblob", "mediumblob", "longblob", "oleobject", "general", "bit varying", "bytea":
return ansi.Bytes
case "uniqueidentifier", "guid", "uuid":
return ansi.Guid
default:
return ansi.Var
}
return ansi.Var
}
// SqliteDialecter is sqlite dialect
type SqliteDialecter struct {
AnsiDialecter
}
// Name return "mssql"
func (sqlite SqliteDialecter) Name() string {
return "sqlite"
}
// Table return schema of table,view
func (sqlite SqliteDialecter) Table(db *sql.DB, name string) (table *ansi.DbTable, err error) {
query := fmt.Sprintf(`SELECT name, type FROM sqlite_master WHERE name = '%s'; `, name)
var rows *sql.Rows
if rows, err = db.Query(query); err != nil {
return
}
var t *ansi.DbTable
for rows.Next() {
tt := ansi.NewTable()
if err = rows.Scan(&tt.Name, &tt.Type); err != nil {
} else {
t = tt
}
}
if err = rows.Err(); err != nil {
return
}
if t == nil {
err = errors.New("table doesn't exist:" + name)
return
}
query = fmt.Sprintf("PRAGMA table_info(%s)", t.Name)
if rows, err = db.Query(query); err != nil {
return
}
for rows.Next() {
col := ansi.DbColumn{}
var dflt sql.NullString
if err = rows.Scan(&col.Position, &col.Name, &col.NativeType, &col.IsNullable, &dflt, &col.IsPrimaryKey); err != nil {
//
} else {
col.DbType = sqlite.DbType(col.NativeType)
col.IsNullable = col.IsNullable == false
t.Columns = append(t.Columns, col)
}
}
if err = rows.Err(); err != nil {
return
}
table = t
return
}
// Function return schema of store procedure,function
func (sqlite SqliteDialecter) Function(db *sql.DB, name string) (*ansi.DbFunction, error) {
return nil, errors.New("sqlite doesn't support store procedure")
}
// MssqlDialecter is ms sql server dialect
type MssqlDialecter struct {
AnsiDialecter
}
// Name return "mssql"
func (mssql MssqlDialecter) Name() string {
return "mssql"
}
// Quote quote s as [s]
func (mssql MssqlDialecter) Quote(s string) string {
return "[" + s + "]"
}
// TableSql return sql to query table schema
func (mssql MssqlDialecter) TableSql(name string) string {
return fmt.Sprintf("SELECT TABLE_CATALOG AS [catalog], TABLE_SCHEMA AS [schema], TABLE_NAME AS [name], TABLE_TYPE AS [type] FROM information_schema.[TABLES] WHERE TABLE_NAME = '%s' ", name)
}
// ColumnsSql return sql to query table columns schema
func (mssql MssqlDialecter) ColumnsSql(name string) string {
// return fmt.Sprintf(`
// select c.[name], c.column_id as [position], c.is_nullable as [nullable],
// t.name as [datatype],
// c.max_length as [length],
// c.[precision],
// c.[scale],
// c.is_identity as [autoincrement],
// case when (c.is_identity = 1 or c.is_computed = 1) then 1 else 0 end as [readonly],
// isnull(ict.primarykey,0) AS [primarykey]
// from
// sys.columns c
// inner join sys.types t on c.user_type_id = t.user_type_id
// left join
// (
// select ic.column_id, 1 primarykey
// from sys.indexes i
// inner join sys.index_columns ic on i.object_id = ic.object_id and i.index_id = ic.index_id
// where i.object_id = object_id('%s') and i.is_primary_key = 1
// ) as ict on c.column_id = ict.column_id
// where
// c.object_id = object_id('%s')
// order by
// c.column_id
// ;
// `, name, name)
return fmt.Sprintf(`
SELECT
isc.COLUMN_NAME AS [name], isc.[ORDINAL_POSITION] AS [position], CASE isc.[IS_NULLABLE] WHEN 'YES' THEN 1 ELSE 0 END as [nullable], isc.[DATA_TYPE] AS [datatype],
ISNULL(isc.[CHARACTER_MAXIMUM_LENGTH],0) AS [length], ISNULL(isc.[NUMERIC_PRECISION],0) AS [precision], ISNULL(isc.[NUMERIC_SCALE],0) AS [scale],
c.is_identity as [autoincrement],
CASE WHEN (c.is_identity = 1 or c.is_computed = 1) THEN 1 else 0 end as [readonly],
ISNULL(ict.primarykey,0) AS [primarykey]
FROM
[INFORMATION_SCHEMA].[COLUMNS] isc
INNER JOIN sys.columns c on c.object_id = object_id(isc.table_name) AND c.name = isc.COLUMN_NAME
LEFT JOIN
(
SELECT ic.column_id, 1 primarykey
FROM sys.indexes i
INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
where i.object_id = object_id('%s') and i.is_primary_key = 1
) AS ict on c.column_id = ict.column_id
WHERE
isc.table_name = '%s' AND c.object_id = object_id('%s')
ORDER BY
isc.[ORDINAL_POSITION] ;
`, name, name, name)
}
// FunctionSql return sql to query procedure schema
func (mssql MssqlDialecter) FunctionSql(name string) string {
return fmt.Sprintf("SELECT ROUTINE_CATALOG AS [catalog], ROUTINE_SCHEMA AS [schema], ROUTINE_NAME as [name] FROM information_schema.ROUTINES WHERE ROUTINE_NAME = '%s' ;", name)
}
// ParametersSql return sql to query procedure paramters schema
func (mssql MssqlDialecter) ParametersSql(name string) string {
return fmt.Sprintf("SELECT Substring(PARAMETER_NAME,2,len(PARAMETER_NAME)-1) as [name], ORDINAL_POSITION as [position], PARAMETER_MODE as [dirmode], DATA_TYPE as [datatype],ISNULL(CHARACTER_MAXIMUM_LENGTH,0) as [length], ISNULL(NUMERIC_PRECISION,0) as [precision], ISNULL(NUMERIC_SCALE,0) as [scale] FROM information_schema.PARAMETERS WHERE SPECIFIC_NAME = '%s' ORDER BY ORDINAL_POSITION", name)
}
// MysqlDialecter is Mysql dialect
type MysqlDialecter struct {
AnsiDialecter
}
// Name return "mysql"
func (mysql MysqlDialecter) Name() string {
return "mysql"
}
// QuoteString quote s as sql native string
func (mysql MysqlDialecter) QuoteString(s string) string {
return "\"" + s + "\""
}
// Quote quote s as 's'
func (mysql MysqlDialecter) Quote(s string) string {
return "'" + s + "'"
}
// TableSql return sql to query table schema
func (mysql MysqlDialecter) TableSql(name string) string {
// http://dev.mysql.com/doc/refman/5.1/en/tables-table.html
return fmt.Sprintf("SELECT TABLE_CATALOG AS `catalog`, TABLE_SCHEMA AS `schema`, TABLE_NAME AS `name`, TABLE_TYPE AS `type` FROM information_schema.`TABLES` WHERE TABLE_NAME = '%s' AND TABLE_SCHEMA= DATABASE() ", name)
}
// ColumnsSql return sql to query table columns schema
func (mysql MysqlDialecter) ColumnsSql(name string) string {
// http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
// show columns from ttable
return fmt.Sprintf("SELECT COLUMN_NAME as `name`, ORDINAL_POSITION as `position`, CASE IS_NULLABLE WHEN 'YES' THEN TRUE ELSE FALSE END as `nullable`, DATA_TYPE as `datatype`, IFNULL(CHARACTER_MAXIMUM_LENGTH,0) as `length`, IFNULL(NUMERIC_PRECISION,0) as `precision`, IFNULL(NUMERIC_SCALE,0) as `scale`, CASE WHEN EXTRA LIKE '%%auto_increment%%' THEN TRUE ELSE FALSE END AS `autoincrement`, CASE WHEN EXTRA LIKE '%%auto_increment%%' THEN TRUE ELSE FALSE END AS `readonly`, CASE WHEN COLUMN_KEY = 'PRI' THEN TRUE ELSE FALSE END AS `primarykey` FROM information_schema.COLUMNS WHERE TABLE_NAME = '%s' and TABLE_SCHEMA= DATABASE() ORDER BY ORDINAL_POSITION ;", name)
}
// FunctionSql return sql to query procedure schema
func (mysql MysqlDialecter) FunctionSql(name string) string {
//http://dev.mysql.com/doc/refman/5.1/en/routines-table.html
return fmt.Sprintf("SELECT ROUTINE_CATALOG AS `catalog`, ROUTINE_SCHEMA AS `schema`, ROUTINE_NAME as `name` FROM information_schema.ROUTINES WHERE ROUTINE_NAME = '%s' AND ROUTINE_SCHEMA = DATABASE(); ", name)
}
// ParametersSql return sql to query procedure paramters schema
func (mysql MysqlDialecter) ParametersSql(name string) string {
return fmt.Sprintf("SELECT PARAMETER_NAME as `name`, ORDINAL_POSITION as `position`, PARAMETER_MODE as `dirmode`, DATA_TYPE as `datatype`, IFNULL(CHARACTER_MAXIMUM_LENGTH,0) as `length`, IFNULL(NUMERIC_PRECISION,0) as `precision`, IFNULL(NUMERIC_SCALE,0) as `scale` FROM information_schema.PARAMETERS WHERE SPECIFIC_NAME = '%s' and SPECIFIC_SCHEMA = DATABASE() ORDER BY ORDINAL_POSITION", name)
}
// PostgreSQLDialecter is PostgreSQL dialect
type PostgreSQLDialecter struct {
AnsiDialecter
}
// Name return "postgres"
func (pgsql PostgreSQLDialecter) Name() string {
return "postgres"
}
// SupportIndexedParameter regturn true
func (pgsql PostgreSQLDialecter) SupportIndexedParameter() bool {
return true
}
// ParameterPlaceHolder return $
func (pgsql PostgreSQLDialecter) ParameterPlaceHolder() string {
return "$"
}
// QuoteString quote s as sql native string
func (pgsql PostgreSQLDialecter) QuoteString(s string) string {
return "'" + s + "'"
}
// Quote quote s as 's'
func (pgsql PostgreSQLDialecter) Quote(s string) string {
return "\"" + s + "\""
}
// Table return sql to query table schema
func (pgsql PostgreSQLDialecter) TableSql(name string) string {
// http://www.postgresql.org/docs/9.2/static/infoschema-tables.html
return fmt.Sprintf(`
select
table_catalog as "catalog",
table_schema as "schema",
table_name as "name",
table_type as "type"
from
information_schema.tables
where
table_name = '%s'
and table_schema = current_schema()
and table_schema not in ('pg_catalog', 'information_schema'); `, name)
}
// Columns return sql to query table columns schema
func (pgsql PostgreSQLDialecter) ColumnsSql(name string) string {
// http://www.postgresql.org/docs/9.2/static/infoschema-columns.html
return fmt.Sprintf(`
select
column_name as "name",
ordinal_position as "position",
case is_nullable when 'YES' then true else false end as "nullable",
data_type as "datatype",
COALESCE(character_maximum_length,0) as "length",
COALESCE(numeric_precision,0) as "precision",
COALESCE(numeric_scale,0) as "scale",
case when pg_get_serial_sequence(table_name, column_name) is null then false else true end as "autoincrement",
case is_updatable when 'YES' then false else true end as "readonly",
case when exists (
select
kc.column_name
from
information_schema.table_constraints tc,
information_schema.key_column_usage kc
where
kc.table_name = c.table_name and kc.table_schema =c.table_schema and kc.column_name = c.column_name
and tc.constraint_type = 'PRIMARY KEY'
and kc.table_name = tc.table_name and kc.table_schema = tc.table_schema and kc.constraint_name = tc.constraint_name
) then true else false end as "primarykey"
from
information_schema.columns c
where
table_name = '%s'
and table_schema = current_schema()
order by
ordinal_position ;
`, name)
}
// Function return sql to query procedure schema
func (pgsql PostgreSQLDialecter) FunctionSql(name string) string {
//http://www.postgresql.org/docs/9.2/static/infoschema-routines.html
return fmt.Sprintf(`select routine_catalog as "catalog", routine_schema as "schema", routine_name as "name" from information_schema.routines where routine_name = '%s' and routine_schema = current_schema() ;`, name)
}
// Parameters return sql to query procedure paramters schema
func (pgsql PostgreSQLDialecter) ParametersSql(name string) string {
return fmt.Sprintf(`
select
p.parameter_name as "name", p.ordinal_position as "position", p.parameter_mode as "dirmode", p.data_type as "datatype", COALESCE(p.character_maximum_length,0) as "length", COALESCE(p.numeric_precision,0) as "precision", COALESCE(p.numeric_scale,0) as "scale"
from
information_schema.parameters p,
information_schema.routines r
where
p.specific_catalog = r.specific_catalog and p.specific_schema = r. specific_schema and p.specific_name = r.specific_name
and r.routine_name = '%s' and r.routine_schema = current_schema()
order by
ordinal_position ;
`, name)
}
// OracleSQLDialecter is oracle dialect
type OracleSQLDialecter struct {
AnsiDialecter
}
// Name return "oracle"
func (oracle OracleSQLDialecter) Name() string {
return "oracle"
}
// ParameterPlaceHolder return :
func (oracle OracleSQLDialecter) ParameterPlaceHolder() string {
return ":"
}
// SupportNamedParameter return true
func (oracle OracleSQLDialecter) SupportNamedParameter() bool {
return true
}
// SupportIndexedParameter regturn true
func (oracle OracleSQLDialecter) SupportIndexedParameter() bool {
return true
}
// Quote doesn't quote identifier
func (oracle OracleSQLDialecter) Quote(s string) string {
return s
}
// Table return sql to query table schema
func (oracle OracleSQLDialecter) TableSql(name string) string {
// http://docs.oracle.com/cd/E11882_01/server.112/e25513/statviews_2117.htm#REFRN20286
return fmt.Sprintf(`
select
TABLESPACE_NAME as catalog,
TABLESPACE_NAME as schema,
TABLE_NAME as name,
DECODE(TABLESPACE_NAME, 'SYS', 'System', 'SYSTEM', 'System', 'SYSMAN', 'System','CTXSYS', 'System','MDSYS', 'System','OLAPSYS', 'System', 'ORDSYS', 'System','OUTLN', 'System', 'WKSYS', 'System','WMSYS', 'System','XDB', 'System','ORDPLUGINS', 'System','User') AS type
from
user_tables
where
TABLE_NAME = '%s'
`, name)
}
// Columns return sql to query table columns schema
func (oracle OracleSQLDialecter) ColumnsSql(name string) string {
// http://docs.oracle.com/cd/E11882_01/server.112/e25513/statviews_2103.htm#REFRN20277
return fmt.Sprintf(`
select
COLUMN_NAME as name,
COLUMN_ID as position,
case NULLABLE when 'Y' then '1' else '0' end as nullable,
DATA_TYPE as datatype,
COALESCE(CHAR_LENGTH,0) as length,
COALESCE(DATA_PRECISION,0) as precision,
COALESCE(DATA_SCALE,0) as scale ,
to_char(0) as autoincrement,
to_char(0) as readonly,
case when exists (
select cc.COLUMN_NAME
from all_cons_columns cc inner join all_constraints cs on cs.CONSTRAINT_NAME = cc.CONSTRAINT_NAME and cc.OWNER = cs.OWNER
where cs.CONSTRAINT_TYPE = 'P' and cs.TABLE_NAME = '%s' and cc.COLUMN_NAME = c.COLUMN_NAME
) then '1' else '0' end as primarykey
from
user_tab_columns c
where
TABLE_NAME = '%s'
order by
COLUMN_ID
`, name, name)
}
// Function return sql to query procedure schema
func (oracle OracleSQLDialecter) FunctionSql(name string) string {
return fmt.Sprintf(`select distinct OWNER as catalog, OWNER as schema, OBJECT_NAME as name from all_procedures where OBJECT_NAME = '%s' and OWNER = (select sys_context('USERENV','SESSION_USER') from dual) `, name)
}
// Parameters return sql to query procedure paramters schema
func (oracle OracleSQLDialecter) ParametersSql(name string) string {
// select sys_context('USERENV','SESSION_USER') from dual
return fmt.Sprintf(`
select distinct
ARGUMENT_NAME as name, POSITION as position,
IN_OUT as dirmode,
DATA_TYPE as datatype,
COALESCE(CHAR_LENGTH,0) as length,
COALESCE(DATA_PRECISION,0) as precision,
COALESCE(DATA_SCALE,0) as scale
from
ALL_ARGUMENTS
where
DATA_LEVEL = 0 AND OBJECT_NAME = '%s' AND OWNER = (select sys_context('USERENV','SESSION_USER') from dual)
order by
POSITION
`, name)
}
// SplitStatement return nothing
func (oracle OracleSQLDialecter) SplitStatement() string {
return " "
}
// SqlDriver is ansi sql compiler
type SqlDriver struct {
Dialecter Dialecter
}
// NewSqlDriver return a SqlDriver
func NewSqlDriver(dialecter Dialecter) Compiler {
return &SqlDriver{Dialecter: dialecter}
}
// Compile compile expression to ansi sql
func (c *SqlDriver) Compile(source string, exp Expression) (query string, args []interface{}, err error) {
if exp == nil {
err = errors.New("compile expression is nil")
return
}
switch exp.Node() {
case NodeText:
t, _ := exp.(*Text)
return c.compileText(t, source)
case NodeProcedure:
p, _ := exp.(*Procedure)
return c.compileProcedure(p, source)
case NodeQuery, NodeUpdate, NodeInsert, NodeDelete:
return NewStmtCompiler(c.Dialecter).Compile(exp, source)
}
err = errors.New(fmt.Sprint("compile expression does support type:", exp.Node()))
return
}
func (c *SqlDriver) compileText(text *Text, source string) (query string, args []interface{}, err error) {
if text == nil || text.Sql == "" {
err = errors.New("text is nil or sql of text is empty")
return
}
if len(text.Parameters) == 0 {
query = text.Sql
return
}
placeHolder := c.Dialecter.ParameterPlaceHolder()
paramters := make([]interface{}, 0, len(text.Parameters))
mode := 0
paraIndex := 1
switch {
case c.Dialecter.SupportNamedParameter():
mode = 1
case c.Dialecter.SupportIndexedParameter():
mode = 2
}
b := []byte(text.Sql)
buffer := &bytes.Buffer{}
state := 0
for {
if state == 0 {
index := bytes.IndexByte(b, '{')
if index >= 0 {
buffer.Write(b[:index])
b = b[index+1:]
state = 1
} else {
break
}
} else {
index := bytes.IndexByte(b, '}')
if index > 0 {
name := string(bytes.TrimSpace((b[:index])))
p, ok := text.FindParameter(name)
if !ok {
err = errors.New("text can not find parameter:" + name)
return
}
buffer.WriteString(placeHolder)
switch mode {
case 0:
paramters = append(paramters, p.Value)
case 1:
buffer.WriteString(name)
paramters = append(paramters, p.Value)
case 2:
buffer.WriteString(strconv.Itoa(paraIndex))
paraIndex++
paramters = append(paramters, p.Value)
}
b = b[index+1:]
state = 0
} else {
err = errors.New("text sql format is invalid")
return
}
}
}
buffer.Write(b)
query = buffer.String()
args = paramters
return
}
func (c *SqlDriver) compileMysqlProcedure(sp *Procedure, source string) (query string, args []interface{}, err error) {
l := len(sp.Parameters)
paramters := make([]interface{}, 0, l)
buffer := &sqlWriter{}
returnName := sp.ReturnParameterName()
hasOut := false
for i := 0; i < l; i++ {
p := sp.Parameters[i]
if p.Dir == ansi.DirInOut {
buffer.Print("SET @", p.Name, " = ?; \n")
paramters = append(paramters, p.Value)
}
}
if returnName == "" {
buffer.WriteString("CALL ")
} else {
buffer.WriteString("SET @" + returnName)
}
buffer.WriteString(sp.Name)
buffer.WriteString(" ( ")
for i := 0; i < l; i++ {
if i > 0 {
buffer.WriteString(", ")
}
p := sp.Parameters[i]
if p.Dir == ansi.DirIn {
buffer.WriteString("?")
paramters = append(paramters, p.Value)
} else if p.Dir == ansi.DirInOut {
buffer.Print("@", p.Name)
hasOut = true
} else if p.Dir == ansi.DirOut {
buffer.Print("@", p.Name)
hasOut = true
}
}
buffer.WriteString(" );")
if hasOut || returnName != "" {
buffer.WriteString("\nSELECT ")
delimit := false
for i := 0; i < l; i++ {
p := sp.Parameters[i]
if p.IsOut() || p.Dir == ansi.DirReturn {
if delimit {
buffer.WriteString(", ")
}
buffer.Print("@", p.Name)
delimit = true
}
}
buffer.WriteString("; ")
}
query = buffer.String()
args = paramters
return
}
func (c *SqlDriver) compileOracleProcedure(sp *Procedure, source string) (query string, args []interface{}, err error) {
l := len(sp.Parameters)
paramters := make([]interface{}, 0, l)
w := &sqlWriter{}
// no parameter
if l == 0 {
w.WriteString("begin " + sp.Name + "(); end; ")
query = w.String()
args = paramters
return
}
index := 0
split := false
retName := sp.ReturnParameterName()
if retName == "" {
w.WriteString("begin " + sp.Name + "( ")
} else {
w.WriteString("begin :" + retName + ":= " + sp.Name + "( ")
}
for i := 0; i < l; i++ {
p := sp.Parameters[i]
if split {
w.Comma()
}
split = true
if p.Dir != ansi.DirReturn {
w.WriteString(p.Name + "=>:" + p.Name)
index++
paramters = append(paramters, p.Value)
}
}
w.WriteString(" ); end; ")
// if sp.HasOutParameter() || retName != "" {
// w.WriteString("select ")
// split = false
// for i := 0; i < l; i++ {
// p := sp.Parameters[i]
// if p.IsOut() || p.Dir == ansi.DirReturn {
// if split {
// w.Comma()
// }
// split = true
// w.WriteString(":" + p.Name)
// }
// }
// }
query = w.String()
args = paramters
return
}
func (c *SqlDriver) compileMssqlProcedure(sp *Procedure, source string) (query string, args []interface{}, err error) {
////exec sp_executesql N'update ttable set cdatetime=getdate() where cint > @P1 ',N'@P1 bigint',42
l := len(sp.Parameters)
paramters := make([]interface{}, 0, l)
split := false
w := &sqlWriter{}
if !sp.HasOutParameter() {
w.Print("exec ", sp.Name, " ")
for i := 0; i < l; i++ {
p := sp.Parameters[i]
if p.Dir == ansi.DirReturn {
continue
}
if split {
w.Comma()
}
split = true
w.WriteString("?")
paramters = append(paramters, p.Value)
}
query = w.String()
args = paramters
return
}
for i := 0; i < l; i++ {
p := sp.Parameters[i]
if p.IsOut() {
nativeType := "nvarchar(max)"
if p.Value != nil {
switch p.Value.(type) {
case int, uint, int8, int16, int32, int64, uint8, uint16, uint32, uint64:
nativeType = "bigint"
case float32, float64:
nativeType = "decimal(18,10)"
case bool:
nativeType = "bit"
}
}
w.Print("declare @kdbp", strconv.Itoa(i), " ", nativeType, "\n")
w.Print("set @kdbp", strconv.Itoa(i), "= ?\n")
paramters = append(paramters, p.Value)
}
}
split = false
w.Print("exec ", sp.Name, " ")
for i := 0; i < l; i++ {
p := sp.Parameters[i]
if p.Dir == ansi.DirReturn {
continue
}
if split {
w.Comma()
}
split = true
if p.Dir == ansi.DirIn {
w.Print("@", p.Name, "=? ")
paramters = append(paramters, p.Value)
} else {
w.Print("@", p.Name, "=@kdbp", strconv.Itoa(i), " output")
}
}
split = false
w.LineBreak()
w.WriteString("select ")
for i := 0; i < l; i++ {
p := sp.Parameters[i]
if p.IsOut() {
if split {
w.Comma()
}
split = true
w.Print("@kdbp", strconv.Itoa(i))
}
}
// declare @p2 int
// set @p2=4
// declare @p3 int
// set @p3=3
// exec usp_inout @x=1,@y=@p2 output,@sum=@p3 output
// select @p2, @p3
query = w.String()
args = paramters
fmt.Print(query)
return
}
func (c *SqlDriver) compilePostgresProcedure(sp *Procedure, source string) (query string, args []interface{}, err error) {
l := len(sp.Parameters)
paramters := make([]interface{}, 0, l)
w := &sqlWriter{}
index := 1
w.WriteString("SELECT * FROM ")
w.WriteString(sp.Name)
w.OpenParentheses()
for i := 0; i < l; i++ {
p := sp.Parameters[i]
if p.IsIn() {
if index > 1 {
w.Comma()
}
w.WriteString(c.Dialecter.ParameterPlaceHolder())
w.WriteString(strconv.Itoa(index))
paramters = append(paramters, p.Value)
index++
}
}
w.CloseParentheses()
w.WriteString(ansi.StatementSplit)
query = w.String()
args = paramters
return
}
func (c *SqlDriver) compileProcedure(sp *Procedure, source string) (query string, args []interface{}, err error) {
if sp == nil || sp.Name == "" {
err = errors.New("procedure is nil or name of procedure is empty")
return