-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdb.go
1760 lines (1647 loc) · 56.8 KB
/
db.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 db
import (
"context"
"fmt"
"sync"
"time"
"go.uber.org/atomic"
)
type DialectName string
// Supported dialect
const (
SQLITE DialectName = "sqlite" // SQLITE is the SQLite driver name
SQLITE3 DialectName = "sqlite3" // SQLITE3 is the SQLite driver name
POSTGRES DialectName = "postgres" // POSTGRES is the PostgreSQL driver name
MYSQL DialectName = "mysql" // MYSQL is the MySQL driver name
MSSQL DialectName = "mssql" // MSSQL is the Microsoft SQL Server driver name
CLICKHOUSE DialectName = "clickhouse" // CLICKHOUSE is the ClickHouse driver name
CASSANDRA DialectName = "cassandra" // CASSANDRA is the Cassandra driver name
ELASTICSEARCH DialectName = "elasticsearch" // ELASTICSEARCH is the Elasticsearch driver name
OPENSEARCH DialectName = "opensearch" // OPENSEARCH is the OpenSearch driver name
)
// Special conditions for searching
const (
// SpecialConditionIsNull can be used as a value in search conditions to check if a field is NULL
// Example usage:
// Where: map[string][]string{
// "email": []string{"isnull()"}, // Will generate: WHERE email IS NULL
// }
SpecialConditionIsNull = "isnull()"
// SpecialConditionIsNotNull can be used as a value in search conditions to check if a field is NOT NULL
// Example usage:
// Where: map[string][]string{
// "email": []string{"notnull()"}, // Will generate: WHERE email IS NOT NULL
// }
SpecialConditionIsNotNull = "notnull()"
)
// Connector is an interface for registering database connectors without knowing the specific connector implementations.
// It provides methods to create connection pools and determine the dialect name for a given database scheme.
//
// To add a new database adapter:
//
// 1. Create a new file named after your database (e.g., db/sql/newdb.go or db/newdb/newdb.go)
//
// 2. Define your connector struct:
// ```go
// type newDBConnector struct{}
// ```
//
// 3. Register your connector in init():
// ```
// func init() {
// // You can register multiple schema names for the same connector
// for _, dbNameStyle := range []string{"newdb", "newdb-alt"} {
// if err := db.Register(dbNameStyle, &newDBConnector{}); err != nil {
// panic(err)
// }
// }
// }
// ```
//
// 4. Implement ConnectionPool method:
// ```go
// func (c *newDBConnector) ConnectionPool(cfg db.Config) (db.Database, error) {
// // Parse connection string if needed
// // Initialize connection pool
// // Set connection parameters (max connections, timeouts, etc)
// // Return database interface implementation
// }
// ```
//
// 5. Implement DialectName method:
// ```go
// func (c *newDBConnector) DialectName(scheme string) (db.DialectName, error) {
// return db.NEWDB, nil // Add your dialect to DialectName type
// }
// ```
//
// 6. Import your adapter package in the main application:
// ```go
// import (
// _ "github.com/acronis/perfkit/db/newdb" // newdb driver
// )
// ```
// This is required for the init() function to be called and register the adapter.
// Example of importing existing adapters:
// ```go
// import (
// _ "github.com/acronis/perfkit/db/es" // es drivers
// _ "github.com/acronis/perfkit/db/sql" // sql drivers
// )
// ```
//
// Common implementation patterns:
// - SQL databases: Extend sqlDatabase struct and use database/sql package
// - NoSQL databases: Create custom Database interface implementation
// - Always include proper error handling with descriptive messages
// - Implement connection string parsing and validation
// - Handle connection pool management
// - Support query logging where applicable
type Connector interface {
// ConnectionPool creates a new database connection pool using the provided configuration
ConnectionPool(cfg Config) (Database, error)
// DialectName returns the database dialect name for a given connection scheme
DialectName(scheme string) (DialectName, error)
}
var (
// dbRegistry stores registered database connectors mapped by their schema names
dbRegistry = make(map[string]Connector)
registryLock = sync.Mutex{}
)
// Register registers a database connector for a given schema.
// This function is typically called from init() functions in database-specific packages.
// Returns an error if the schema is already registered.
//
// Example usage:
//
// func init() {
// if err := db.Register("mysql", &mysqlConnector{}); err != nil {
// panic(err)
// }
// }
func Register(schema string, conn Connector) error {
registryLock.Lock()
defer registryLock.Unlock()
if _, ok := dbRegistry[schema]; ok {
return fmt.Errorf("schema %s already exists", schema)
}
dbRegistry[schema] = conn
return nil
}
// Config is a struct for database configuration settings
type Config struct {
// ConnString is the database connection string/URL. Format varies by database type:
// - Cassandra: cql://user:pass@host:port/keyspace
// - ClickHouse: clickhouse://host:port/dbname
// - MSSQL: sqlserver://user:pass@host:port/dbname
// - MySQL: mysql://user:pass@host:port/dbname
// - PostgreSQL: postgres://user:pass@host:port/dbname
// - SQLite: sqlite:///path/to/file.db or sqlite://:memory:
// - Elasticsearch/OpenSearch: es://user:pass@host:port
ConnString string
// MaxOpenConns controls the maximum number of open connections to the database.
// Usage by database:
// - Cassandra: Uses math.Max(1, MaxOpenConns) for connection pool size
// - ClickHouse: Uses math.Max(1, MaxConnLifetime) for max connections
// - MSSQL: Uses math.Max(1, MaxOpenConns) for both max open and idle connections
// - MySQL: Uses math.Max(1, MaxOpenConns) for both max open and idle connections
// - PostgreSQL: Uses math.Max(1, MaxOpenConns) for both max open and idle connections
// - SQLite: Sets max open and idle connections directly
// - Elasticsearch/OpenSearch: Not used (managed by client library)
MaxOpenConns int
// MaxConnLifetime is the maximum amount of time a connection may be reused.
// Usage by database:
// - Cassandra: Not used
// - ClickHouse: Used if > 0 to set connection max lifetime
// - MSSQL: Used if > 0 to set connection max lifetime
// - MySQL: Used if > 0 to set connection max lifetime
// - PostgreSQL: Sets connection max lifetime directly
// - SQLite: Not used
// - Elasticsearch/OpenSearch: Not used
MaxConnLifetime time.Duration
// MaxPacketSize controls the maximum size of network packets/requests.
// Usage by database:
// - MySQL: Added to connection string as maxAllowedPacket parameter
// - All other databases: Not used
MaxPacketSize int
// QueryStringInterpolation controls how SQL queries are constructed for inserts:
//
// When false (default, recommended):
// - Uses parameterized queries with placeholders
// - Values are passed separately from the query string
// - Provides better SQL injection protection
// - Different placeholder syntax per dialect:
// - PostgreSQL: Uses $1, $2, $3, etc.
// Example:
// ```sql
// INSERT INTO users(id, name) VALUES ($1, $2), ($3, $4);
// -- values passed separately: [1, "john", 2, "jane"]
// ```
// - Other SQL databases: Uses ?
// Example:
// ```sql
// INSERT INTO users(id, name) VALUES (?, ?), (?, ?);
// -- values passed separately: [1, "john", 2, "jane"]
// ```
//
// When true:
// - Uses string interpolation
// - Values are converted to strings and embedded directly in the query
// - Each value is formatted according to its type and dialect
// - Less secure but may be needed for specific database requirements
// Example:
// ```sql
// INSERT INTO users(id, name) VALUES (1, 'john'), (2, 'jane');
// ```
//
// Security Considerations:
// - Prefer parameterized queries (false) for better SQL injection protection
// - Use string interpolation (true) only when required by specific database features
// - Values are still escaped according to dialect rules when using interpolation
QueryStringInterpolation bool
// DryRun controls whether SQL operations are actually executed:
//
// When true:
// - Queries are logged but not executed
// - All operations return success without affecting the database
// - Useful for testing and debugging SQL generation
// - Logs include special markers for skipped operations
//
// Examples of logged output:
// 1. Single line queries:
// ```sql
// -- INSERT INTO users(id, name) VALUES (1, 'john') -- skip because of 'dry-run' mode
// ```
//
// 2. Multi-line queries:
// ```sql
// -- skip because of 'dry-run' mode
// /*
// BEGIN BATCH
// INSERT INTO users(id, name) VALUES (1, 'john');
// INSERT INTO users(id, name) VALUES (2, 'jane');
// APPLY BATCH;
// */
// ```
//
// 3. Transactions:
// ```sql
// -- BEGIN -- skip because of 'dry-run' mode
// -- INSERT INTO users(id) VALUES (1) -- skip because of 'dry-run' mode
// -- COMMIT -- skip because of 'dry-run' mode
// ```
DryRun bool
// UseTruncate controls table cleanup behavior:
//
// When true:
// - Uses TRUNCATE TABLE instead of DROP TABLE
// - Keeps table structure but removes all data
// - Different behavior per dialect:
// - PostgreSQL: "TRUNCATE TABLE tablename CASCADE"
// - Others: "TRUNCATE TABLE tablename"
//
// When false:
// - Uses "DROP TABLE IF EXISTS tablename"
// - Removes both data and table structure
// - Consistent behavior across all dialects
//
// Example Usage:
// 1. With UseTruncate = true:
// ```sql
// -- PostgreSQL
// TRUNCATE TABLE users CASCADE;
//
// -- Other databases
// TRUNCATE TABLE users;
// ```
//
// 2. With UseTruncate = false:
// ```sql
// DROP TABLE IF EXISTS users;
// ```
//
// Use Cases:
// - Set true when you want to preserve table structure:
// - Keeping indexes and constraints
// - Maintaining foreign key relationships
// - Faster when recreating same data structure
// - Set false when you want complete removal:
// - Clean slate for schema changes
// - Removing test databases
// - Full cleanup operations
UseTruncate bool
// TLSEnabled controls whether TLS/HTTPS is used for Elasticsearch connections:
//
// When true:
// - Uses HTTPS scheme for connections
// - Automatically enabled when username/password are provided
// - Requires proper TLS configuration
//
// Example URL transformations:
// ```go
// // TLSEnabled = false
// "http://localhost:9200"
//
// // TLSEnabled = true
// "https://localhost:9200"
// ```
TLSEnabled bool
// TLSCACert contains the CA certificate for TLS verification
//
// When provided:
// - Creates a new certificate pool with the provided CA cert
// - Used to verify server certificates
// - Required for secure production deployments
//
// When empty:
// - Uses InsecureSkipVerify=true (not recommended for production)
// - Allows any server certificate
// - Useful for development/testing
//
// Example usage:
// ```go
// cfg := db.Config{
// TLSEnabled: true,
// TLSCACert: []byte("-----BEGIN CERTIFICATE-----\n..."),
// }
// ```
//
// Security considerations:
// 1. Always provide TLSCACert in production
// 2. TLS is automatically enabled with authentication
// 3. Verify server identity to prevent MITM attacks
TLSCACert []byte
// QueryLogger logs all SQL queries before execution
// When configured:
// 1. Regular Queries:
// ```sql
// SELECT * FROM users WHERE id > 100;
// ```
//
// 2. Prepared Statements:
// ```sql
// PREPARE stmt FROM 'SELECT * FROM users WHERE id = $1';
// EXECUTE stmt;
// DEALLOCATE PREPARE stmt;
// ```
//
// 3. DryRun Mode:
// ```sql
// -- INSERT INTO users(id, name) VALUES (1, 'john') -- skip because of 'dry-run' mode
// ```
//
// 4. Multi-line Queries:
// ```sql
// -- skip because of 'dry-run' mode
// /*
// BEGIN BATCH
// INSERT INTO users(id, name) VALUES (1, 'john');
// INSERT INTO users(id, name) VALUES (2, 'jane');
// APPLY BATCH;
// */
// ```
QueryLogger Logger
// ReadRowsLogger logs the data returned from queries
// When configured:
// 1. Regular Row Output:
// ```
// Row: id=1 name="john" age=25
// Row: id=2 name="jane" age=30
// ```
//
// 2. With UseTruncate=true:
// ```
// Row: id=1 name="john" age=25
// Row: id=2 name="jane" age=30
// ... truncated ...
// ```
// Note: Truncates after maxRowsToPrint (10) rows
//
// 3. Single Row Queries:
// ```
// Row: count=42
// ```
//
// Usage Example:
// ```go
// type customLogger struct{}
//
// func (l *customLogger) Log(format string, args ...interface{}) {
// fmt.Printf(format + "\n", args...)
// }
//
// cfg := db.Config{
// QueryLogger: &customLogger{},
// ReadRowsLogger: &customLogger{},
// }
// ```
ReadRowsLogger Logger
// ExplainLogger receives query execution plan output when Explain is true.
// The output format varies by dialect:
//
// 1. PostgreSQL:
// ```sql
// SELECT * FROM users WHERE id > 100;
// [args]
// Seq Scan on users (cost=0.00..35.50 rows=500 width=244)
// Filter: (id > 100)
// Planning Time: 0.083 ms
// Execution Time: 0.184 ms
// ```
//
// 2. MySQL:
// ```sql
// SELECT * FROM users WHERE id > 100;
// [args]
// id: 1
// select_type: SIMPLE
// table: users
// type: range
// possible_keys: PRIMARY
// key: PRIMARY
// rows: 500
// ```
//
// 3. SQLite:
// ```sql
// SELECT * FROM users WHERE id > 100;
// [args]
// ID: 1, Parent: 0, Not Used: 0, Detail: SCAN TABLE users
// ```
//
// 4. Cassandra:
// ```sql
// TRACING ON; SELECT * FROM users WHERE id > 100;
// [args]
// <tracing output>
// ```
//
// Implementation details:
// - Activated when both Explain=true and ExplainLogger is set
// - Adds EXPLAIN prefix to queries based on dialect
// - Captures and formats execution plan output
// - Works with Select(), Query(), and QueryRow() operations
// - Returns error if explain not supported by dialect
ExplainLogger Logger
// SystemLogger logs system-level database operations and events.
// Primary uses:
// 1. Embedded PostgreSQL:
// - Logs database initialization and shutdown
// - Reports data directory creation and usage
// - Captures PostgreSQL server logs
// Example output:
// ```
// -- embedded postgres: creating data dir: /home/user/.embedded-postgres-go/data
// -- embedded postgres: using data dir: /home/user/.embedded-postgres-go/data
// -- embedded postgres: database system is ready to accept connections
// ```
//
// 2. Other Database Systems:
// - Logs critical system events
// - Reports initialization status
// - Captures server-side messages
SystemLogger Logger
}
// Open opens a database connection using the provided configuration.
// The function works in the following steps:
//
// 1. Parse the connection string to extract the scheme:
// ```go
// "mysql://user:pass@localhost:3306/dbname" -> scheme: "mysql"
// "postgres://localhost:5432/mydb" -> scheme: "postgres"
// "es://localhost:9200" -> scheme: "es"
// ```
//
// 2. Look up the registered connector for the scheme:
// - Uses dbRegistry to find the appropriate Connector implementation
// - Returns error if no connector is registered for the scheme
//
// 3. Create connection pool using the connector:
// - Calls ConnectionPool() on the found connector
// - Passes the complete Config struct to the connector
// - Returns the Database interface implementation
//
// Example usage:
//
// ```go
// cfg := db.Config{
// ConnString: "mysql://user:pass@localhost:3306/dbname",
// MaxOpenConns: 10,
// MaxConnLifetime: time.Minute * 5,
// }
// db, err := db.Open(cfg)
// if err != nil {
// log.Fatal(err)
// }
// defer db.Close()
// ```
//
// Supported database types (when appropriate drivers are imported):
// - MySQL: "mysql://"
// - PostgreSQL: "postgres://" or "postgresql://"
// - SQLite: "sqlite://"
// - MSSQL: "mssql://" or "sqlserver://"
// - Cassandra: "cql://"
// - ClickHouse: "clickhouse://"
// - Elasticsearch: "es://" or "elastic://" or "elasticsearch://"
// - OpenSearch: "os://" or "opensearch://"
func Open(cfg Config) (Database, error) {
var scheme, _, err = ParseScheme(cfg.ConnString)
if err != nil {
return nil, fmt.Errorf("failed to parse %s to scheme: %v", cfg.ConnString, err)
}
registryLock.Lock()
var conn, ok = dbRegistry[scheme]
registryLock.Unlock()
if !ok {
return nil, fmt.Errorf("scheme %s doesn't exist in registry", scheme)
}
return conn.ConnectionPool(cfg)
}
// GetDialectName returns the database dialect name for a given connection string.
// This is useful when you need to know the database type without actually
// establishing a connection.
//
// The function works similarly to Open:
// 1. Parses the connection string to get the scheme
// 2. Looks up the registered connector
// 3. Calls DialectName() on the connector
//
// Returns a DialectName enum value that identifies the database type:
// - db.MYSQL for MySQL
// - db.POSTGRES for PostgreSQL
// - db.SQLITE for SQLite
// - db.MSSQL for SQL Server
// - db.CASSANDRA for Cassandra
// - db.CLICKHOUSE for ClickHouse
// - db.ELASTICSEARCH for Elasticsearch
// - db.OPENSEARCH for OpenSearch
//
// Example usage:
//
// ```go
// dialect, err := db.GetDialectName("mysql://localhost:3306/dbname")
// if err != nil {
// log.Fatal(err)
// }
// switch dialect {
// case db.MYSQL:
// // Handle MySQL specific logic
// case db.POSTGRES:
// // Handle PostgreSQL specific logic
// }
// ```
//
// Note: The appropriate database driver must be imported for the scheme
// to be recognized, even though no connection is established.
func GetDialectName(cs string) (DialectName, error) {
var scheme, _, err = ParseScheme(cs)
if err != nil {
return "", fmt.Errorf("failed to parse %s to scheme: %v", cs, err)
}
registryLock.Lock()
var conn, ok = dbRegistry[scheme]
registryLock.Unlock()
if !ok {
return "", fmt.Errorf("scheme %s doesn't exist in registry", scheme)
}
return conn.DialectName(scheme)
}
// Logger is an interface for logging database operations.
// Example implementation:
//
// ```go
// type customLogger struct{}
//
// func (l *customLogger) Log(format string, args ...interface{}) {
// fmt.Printf(format + "\n", args...)
// }
//
// cfg := db.Config{
// QueryLogger: &customLogger{},
// ReadRowsLogger: &customLogger{},
// }
// ```
//
// Note: The Logger interface is designed to be simple and flexible,
// allowing for easy integration with existing logging systems.
type Logger interface {
Log(format string, args ...interface{})
}
// Page is a struct for storing pagination information
// Example usage:
//
// ctrl := &SelectCtrl{
// Fields: []string{"id", "name", "created_at"},
// Where: map[string][]string{
// "status": {"active"},
// },
// Page: Page{
// Limit: 10, // Number of rows to return
// Offset: 20, // Skip first 20 rows
// },
// }
//
// Note: If Limit is 0 or negative, pagination is disabled and all matching rows are returned.
type Page struct {
Limit int64
Offset int64
}
// SelectCtrl is a struct for storing select control information
type SelectCtrl struct {
// Fields specifies which columns to return in the query result
// - Empty array means select all columns
// - ["COUNT(0)"] means select count
// - ["column1", "column2"] means select specific columns
Fields []string
// Where contains filter conditions for the query
// The map key is the column name and the value array contains one or more conditions
// Supported filter functions:
// - No function: exact match (e.g. "value")
// - lt: less than (e.g. "lt(5)")
// - le: less than or equal (e.g. "le(5)")
// - gt: greater than (e.g. "gt(5)")
// - ge: greater than or equal (e.g. "ge(5)")
// - ne: not equal (e.g. "ne(value)")
// - like: contains substring (e.g. "like(value)")
// - hlike: starts with (e.g. "hlike(value)")
// - tlike: ends with (e.g. "tlike(value)")
// Special conditions:
// - "isnull()": matches NULL values
// - "notnull()": matches non-NULL values
Where map[string][]string
// Order specifies the sort order for results
// Supported order functions:
// - asc(column): ascending order
// - desc(column): descending order
// - nearest(column;operator;value): proximity search (e.g. "nearest(vector;L2;[1,2,3])")
Order []string
// Page controls result pagination
Page Page
// OptimizeConditions enables query optimization for better performance.
// When enabled, the following optimizations are applied:
//
// 1. Integer Field Optimization:
// - Combines multiple range conditions into a single range
// - Example: ["gt(123)", "lt(129)", "124"] -> only keeps "124" as it satisfies both conditions
// - Example: ["gt(123)", "le(129)"] -> converts to range min=123, max=130
// - Eliminates redundant conditions
// - Returns empty result if conditions are contradictory (e.g., "gt(129)", "le(121)")
//
// 2. Enum String Optimization:
// - Converts string-based enum values to their integer representations
// - Combines multiple conditions into a minimal set
// - Example: ["normal", "high"] -> converts to [0, 20] (internal enum values)
// - Example: ["gt(normal)", "le(belowNormal)"] -> returns empty as conditions contradict
// - Optimizes range queries on enum values
//
// 3. Time Field Optimization:
// - Normalizes time values to UTC
// - Combines overlapping time ranges
// - Example: ["gt(2023-03-28)", "lt(2023-03-29)"] -> converts to min/max time range
// - Example: ["2023-03-28", "lt(2023-03-29)"] -> keeps only exact match if within range
// - Supports various time formats (RFC3339, Unix timestamp, etc.)
// - Returns empty result for impossible time ranges
//
// The optimization process:
// 1. Analyzes all conditions for a field
// 2. Converts values to their internal representations
// 3. Determines the effective range or set of values
// 4. Eliminates redundant or contradictory conditions
// 5. May convert multiple conditions into a single optimized form
//
// Example optimizations:
// ```go
// // Original conditions
// ctrl := &SelectCtrl{
// Where: map[string][]string{
// "id": {"gt(123)", "lt(129)", "124", "126"},
// "priority": {"gt(normal)", "le(high)"},
// "created_at": {"gt(2023-03-28)", "lt(2023-03-29)"},
// },
// OptimizeConditions: true,
// }
//
// // Optimized to
// // id: ["124", "126"] (only values that satisfy all ranges)
// // priority: [10, 20] (converted to internal enum values within range)
// // created_at: range from 2023-03-28 to 2023-03-29
// ```
OptimizeConditions bool
}
// Examples:
//
// 1. Simple exact match filter:
// ```go
// ctrl := &SelectCtrl{
// Where: map[string][]string{
// "id": {"1"},
// },
// }
// ```
//
// 2. Multiple conditions on same field:
// ```go
// ctrl := &SelectCtrl{
// Where: map[string][]string{
// "id": {"1", "2"}, // Translates to: id IN (1, 2)
// },
// }
// ```
//
// 3. Range conditions:
// ```go
// ctrl := &SelectCtrl{
// Where: map[string][]string{
// "age": {"gt(18)", "lt(65)"}, // Translates to: age > 18 AND age < 65
// },
// }
// ```
//
// 4. String matching:
// ```go
// ctrl := &SelectCtrl{
// Where: map[string][]string{
// "name": {"like(john)"}, // Translates to: name LIKE '%john%'
// },
// }
// ```
//
// 5. Sorting and pagination:
// ```go
// ctrl := &SelectCtrl{
// Order: []string{"desc(created_at)"},
// Page: Page{
// Limit: 10,
// Offset: 0,
// },
// }
// ```
//
// 6. Count query:
// ```go
// ctrl := &SelectCtrl{
// Fields: []string{"COUNT(0)"},
// }
// ```
//
// 7. Select specific fields with conditions:
// ```go
// ctrl := &SelectCtrl{
// Fields: []string{"name", "age"},
// Where: map[string][]string{
// "state": {"active"},
// "age": {"ge(18)"},
// },
// }
// ```
//
// 8. UUID field matching:
// ```go
// ctrl := &SelectCtrl{
// Where: map[string][]string{
// "uuid": {"00000000-0000-0000-0000-000000000001"},
// },
// }
// ```
//
// 9. Time range query:
// ```go
// ctrl := &SelectCtrl{
// Where: map[string][]string{
// "enqueue_time": {"gt(10000)", "lt(20000)"}, // Unix timestamp range
// },
// }
// ```
// databaseSelector provides methods for querying data from the database
type databaseSelector interface {
// Select queries data from a table using the provided selection control parameters.
// It supports filtering, sorting, field selection and pagination through the SelectCtrl struct.
Select(tableName string, c *SelectCtrl) (Rows, error)
}
// InsertStats is a struct for storing insert statistics
type InsertStats struct {
Successful int64
Failed int64
Total int64
ExpectedSuccesses int64
}
func (s *InsertStats) String() string {
return fmt.Sprintf("successful: %d, failed: %d, total: %d", s.Successful, s.Failed, s.Total)
}
// databaseInserter provides methods for inserting data into the database
type databaseInserter interface {
// BulkInsert inserts multiple rows into a table in a single operation.
// Parameters:
// - tableName: name of the table to insert into
// - rows: slice of rows, where each row is a slice of values matching columnNames
// - columnNames: names of the columns in the order they appear in rows
//
// The function supports different database dialects with optimized implementations:
//
// SQL Databases (PostgreSQL, MySQL, etc.):
// - Uses parameterized queries by default for SQL injection protection
// - Falls back to string interpolation if QueryStringInterpolation is true
// - Generates multi-value INSERT statements for better performance
// Example:
// ```go
// err := db.BulkInsert("users",
// [][]interface{}{
// {1, "john", 25},
// {2, "jane", 30},
// },
// []string{"id", "name", "age"})
// ```
// Generates: "INSERT INTO users(id, name, age) VALUES ($1, $2, $3), ($4, $5, $6);"
//
// Cassandra:
// - Uses batch statements for multiple inserts
// - Wraps multiple inserts in BEGIN BATCH/APPLY BATCH
// Example:
// ```go
// err := db.BulkInsert("users",
// [][]interface{}{
// {1, "john", 25},
// {2, "jane", 30},
// },
// []string{"id", "name", "age"})
// ```
// Generates:
// ```sql
// BEGIN BATCH
// INSERT INTO users(id, name, age) VALUES (?, ?, ?);
// INSERT INTO users(id, name, age) VALUES (?, ?, ?);
// APPLY BATCH;
// ```
//
// Elasticsearch:
// - Uses bulk API for efficient indexing
// - Automatically adds @timestamp if not provided
// - Supports JSON document structure
// Example:
// ```go
// err := db.BulkInsert("users",
// [][]interface{}{
// {time.Now(), 1, "john", []string{"admin", "user"}},
// {time.Now(), 2, "jane", []string{"user"}},
// },
// []string{"@timestamp", "id", "name", "roles"})
// ```
//
// Common Features:
// - Validates that row length matches column names length
// - Handles empty input gracefully (returns nil)
// - Returns detailed error messages for invalid inputs
// - Supports transactions when used within Session.Transact()
//
// Returns error if:
// - Row length doesn't match column names length
// - Database execution fails
// - Invalid data types for the specified columns
BulkInsert(tableName string, rows [][]interface{}, columnNames []string) error
}
// databaseQuerier provides low-level query execution methods.
// This interface is implemented by both direct database connections and transactions.
//
// Example usage:
//
// ```go
// // Direct query execution
// db.Exec("INSERT INTO users (name, age) VALUES (?, ?)", "John", 30)
//
// // Single row query
// var name string
// row := db.QueryRow("SELECT name FROM users WHERE id = ?", 1)
// row.Scan(&name)
//
// // Multiple rows query
// rows, _ := db.Query("SELECT id, name FROM users WHERE age > ?", 18)
// defer rows.Close()
// for rows.Next() {
// var id int
// var name string
// rows.Scan(&id, &name)
// }
// ```
//
// Features:
// - Context support for cancellation and timeouts
// - Query parameter binding for SQL injection protection
// - Result interface for getting LastInsertId and RowsAffected
// - Row and Rows interfaces for scanning results
// - Automatic resource cleanup (when using defer rows.Close())
// - Query explain support for debugging and optimization
type databaseQuerier interface {
// Exec executes a query that doesn't return rows
// Example: INSERT, UPDATE, DELETE statements
Exec(format string, args ...interface{}) (Result, error)
// QueryRow executes a query that returns a single row
// Example: SELECT for unique key lookups
QueryRow(format string, args ...interface{}) Row
// Query executes a query that returns multiple rows
// Example: SELECT with WHERE clause matching multiple records
Query(format string, args ...interface{}) (Rows, error)
}
// Result is an interface for database query results
// It provides methods to get information about the executed query
type Result interface {
// LastInsertId returns the ID generated for an AUTO_INCREMENT column by the last INSERT operation
// Note: Not all databases support this (e.g., PostgreSQL requires RETURNING clause)
LastInsertId() (int64, error)
// RowsAffected returns the number of rows affected by an INSERT, UPDATE, or DELETE operation
// Note: Some databases like ClickHouse might not support this functionality
RowsAffected() (int64, error)
}
// Stmt is an interface for database prepared statements
// Prepared statements help prevent SQL injection and improve performance
// for queries that are executed multiple times
//
// Example usage:
//
// ```go
// // Prepare the statement
// stmt, err := db.Prepare("INSERT INTO users (name, age) VALUES (?, ?)")
// if err != nil {
// return err
// }
// defer stmt.Close() // Always close statements to free resources
//
// // Execute multiple times with different parameters
// result, err := stmt.Exec("John", 30)
// if err != nil {
// return err
// }
// affected, _ := result.RowsAffected()
//
// result, err = stmt.Exec("Jane", 25)
// ```
//
// Different SQL dialects use different parameter placeholders:
//
// ```go
// // MySQL, SQLite: Use ?
// "INSERT INTO users VALUES (?, ?)"
//
// // PostgreSQL: Use $1, $2, etc.
// "INSERT INTO users VALUES ($1, $2)"
//
// // MSSQL: Use @ParamName
// "INSERT INTO users VALUES (@Name, @Age)"
// stmt.Exec(sql.Named("Name", "John"), sql.Named("Age", 30))
// ```
type Stmt interface {
// Exec executes the prepared statement with the given arguments
Exec(args ...any) (Result, error)
// Close releases the database resources associated with the statement
Close() error
}
// databaseQueryPreparer provides methods for preparing statements
type databaseQueryPreparer interface {
// Prepare creates a prepared statement for later queries or executions
//
// Example usage in a transaction:
// ```go
// err := db.Transact(func(tx DatabaseAccessor) error {
// stmt, err := tx.Prepare("INSERT INTO users VALUES (?, ?)")
// if err != nil {