-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
3218 lines (2930 loc) · 96.1 KB
/
Copy pathdb.go
File metadata and controls
3218 lines (2930 loc) · 96.1 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 relica provides a lightweight, type-safe database query builder for Go.
//
// Relica offers a fluent API for building SQL queries with support for:
// - Multiple databases (PostgreSQL, MySQL, SQLite)
// - Zero production dependencies
// - Prepared statement caching
// - Transaction management
// - Advanced SQL features (JOINs, aggregates, subqueries, CTEs)
//
// # Quick Start
//
// Install:
//
// go get github.com/coregx/relica
//
// Basic usage:
//
// db, err := relica.Open("postgres", "user=postgres dbname=myapp")
// if err != nil {
// log.Fatal(err)
// }
// defer db.Close()
//
// var users []User
// err = db.Select("id", "name").From("users").All(&users)
//
// # Features
//
// CRUD Operations:
//
// // SELECT with Expression API
// db.Select().From("users").Where(relica.Eq("id", 123)).One(&user)
//
// // INSERT via Model API (recommended)
// user := User{Name: "Alice", Email: "alice@example.com"}
// db.Model(&user).Insert()
//
// // UPDATE
// db.Update("users").
// Set(map[string]any{"status": "active"}).
// Where(relica.Eq("id", 123)).
// Execute()
//
// // DELETE
// db.Delete("users").Where(relica.Eq("id", 123)).Execute()
package relica
import (
"context"
"database/sql"
"errors"
"log/slog"
"reflect"
"sort"
"time"
"github.com/coregx/relica/internal/core"
"github.com/coregx/relica/internal/logger"
"github.com/coregx/relica/internal/util"
)
// DB represents a database connection with query building capabilities.
//
// DB provides a fluent API for constructing and executing SQL queries
// in a type-safe manner. It wraps the underlying database/sql connection
// and adds features like:
// - Prepared statement caching (LRU eviction, <60ns hit latency)
// - Query builder with method chaining
// - Transaction management (all isolation levels)
// - Multi-database support (PostgreSQL, MySQL, SQLite)
//
// Example:
//
// db, err := relica.Open("postgres", "user=postgres dbname=myapp")
// if err != nil {
// log.Fatal(err)
// }
// defer db.Close()
//
// var users []User
// err = db.Builder().
// Select("id", "name", "email").
// From("users").
// Where("active = ?", true).
// OrderBy("name").
// All(&users)
type DB struct {
db *core.DB
}
// QueryBuilder constructs type-safe queries.
//
// The query builder provides a fluent interface for building
// SELECT, INSERT, UPDATE, DELETE, UPSERT, and batch operations.
// All queries are cached and executed with prepared statements.
//
// Example:
//
// qb := db.Builder()
// qb.Select("*").From("users").Where("status = ?", 1).All(&users)
type QueryBuilder struct {
qb *core.QueryBuilder
}
// QueryPlan represents a unified query execution plan from database EXPLAIN.
// It provides performance metrics, index usage analysis, and database-specific details.
// Returned by [SelectQuery.Explain] and [SelectQuery.ExplainAnalyze].
//
// Fields populated by EXPLAIN (always available):
// - Cost, EstimatedRows, UsesIndex, IndexName, FullScan, RawOutput, Database
//
// Fields populated only by EXPLAIN ANALYZE (require actual execution):
// - ActualRows, ActualTime, BuffersHit, BuffersMiss, RowsExamined, RowsProduced
type QueryPlan = core.QueryPlan
// SelectQuery represents a SELECT query being built.
//
// SelectQuery supports a wide range of SQL features including:
// - JOINs (INNER, LEFT, RIGHT, FULL, CROSS)
// - Aggregates (COUNT, SUM, AVG, MIN, MAX)
// - GROUP BY and HAVING
// - ORDER BY, LIMIT, OFFSET
// - Set operations (UNION, INTERSECT, EXCEPT)
// - Common Table Expressions (WITH, WITH RECURSIVE)
// - Subqueries (in FROM, WHERE, SELECT clauses)
//
// Example:
//
// sq := db.Builder().
// Select("u.name", "COUNT(*) as order_count").
// From("users u").
// InnerJoin("orders o", "o.user_id = u.id").
// GroupBy("u.id", "u.name").
// Having("COUNT(*) > ?", 10).
// OrderBy("order_count DESC")
// sq.All(&results)
type SelectQuery struct {
sq *core.SelectQuery
}
// Tx represents a database transaction.
//
// Transactions provide ACID guarantees and support all standard
// isolation levels. All queries executed through a transaction's
// builder automatically participate in that transaction.
//
// Example:
//
// tx, err := db.Begin(ctx)
// if err != nil {
// return err
// }
// defer tx.Rollback() // Safe to call even after Commit
//
// _, err = tx.Insert("users", data).Execute()
// if err != nil {
// return err
// }
//
// return tx.Commit()
type Tx struct {
tx *core.Tx
}
// ModelQuery provides CRUD operations for struct models.
//
// ModelQuery simplifies database operations by automatically inferring
// table names and primary keys from struct definitions, similar to ozzo-dbx.
//
// The table name is determined by:
// 1. TableName() method if model implements interface{ TableName() string }
// 2. Otherwise: struct name lowercased with 's' suffix (e.g., User → users)
//
// The primary key is detected from:
// 1. Field with db:"id" tag
// 2. Field with db:"*_id" tag (e.g., db:"user_id")
// 3. Field named "ID"
//
// Example:
//
// type User struct {
// ID int `db:"id"`
// Name string `db:"name"`
// Email string `db:"email"`
// }
//
// func (User) TableName() string { return "users" }
//
// user := User{Name: "Alice", Email: "alice@example.com"}
// err := db.Model(&user).Insert()
//
// user.Status = "active"
// err = db.Model(&user).Update() // Auto WHERE by primary key.
//
// err = db.Model(&user).Delete() // Auto WHERE by primary key.
type ModelQuery struct {
mq *core.ModelQuery
}
// BeforeInserter is implemented by models that need pre-insert logic.
// If a struct implements this interface, Model().Insert() and Model().Upsert()
// call BeforeInsert() before autoid generation and query execution.
//
// Use cases: setting timestamps, generating custom IDs, validation.
//
// Example:
//
// type User struct {
// ID int64 `db:"id,pk"`
// PublicID string `db:"public_id,autoid:usr"`
// CreatedAt time.Time `db:"created_at"`
// }
//
// func (u *User) BeforeInsert() error {
// u.CreatedAt = time.Now()
// return nil
// }
type BeforeInserter = core.BeforeInserter
// Query represents a built query ready for execution.
//
// Query encapsulates the SQL string, parameters, and execution context.
// It provides methods for executing the query and scanning results.
//
// Example:
//
// q := db.Builder().Select("*").From("users").Where("id = ?", 123).Build()
// var user User
// err := q.One(&user)
type Query struct {
q *core.Query
err error // Error from query construction (e.g., struct conversion).
}
// TxOptions represents transaction options including isolation level.
//
// Example:
//
// opts := &relica.TxOptions{
// Isolation: sql.LevelSerializable,
// ReadOnly: true,
// }
// tx, err := db.BeginTx(ctx, opts)
type TxOptions = core.TxOptions
// PoolStats represents database connection pool statistics.
// It provides insights into connection pool health and usage patterns.
type PoolStats = core.PoolStats
// Option is a functional option for configuring DB.
//
// Example:
//
// db, err := relica.Open("postgres", dsn,
// relica.WithMaxOpenConns(100),
// relica.WithMaxIdleConns(50))
type Option = core.Option
// Expression represents a database expression for building complex WHERE clauses.
//
// Expressions provide a type-safe way to construct SQL conditions without
// writing raw SQL strings. They support nesting and composition.
//
// Example:
//
// expr := relica.And(
// relica.Eq("status", 1),
// relica.Or(
// relica.GreaterThan("age", 18),
// relica.Eq("verified", true),
// ),
// )
// db.Builder().Select("*").From("users").Where(expr).All(&users)
type Expression = core.Expression
// HashExp represents a hash-based expression using column-value pairs.
//
// HashExp provides a convenient map syntax for simple equality conditions.
// Special values are handled automatically:
// - nil → "column IS NULL"
// - []any → "column IN (...)"
//
// Example:
//
// db.Builder().Select("*").From("users").Where(relica.HashExp{
// "status": 1,
// "role": []string{"admin", "moderator"},
// "deleted_at": nil,
// }).All(&users)
type HashExp = core.HashExp
// LikeExp represents a LIKE expression with automatic escaping.
//
// LikeExp provides pattern matching with automatic escaping of
// SQL wildcard characters (%, _).
//
// Example:
//
// db.Builder().Select("*").From("users").Where(
// relica.Like("name", "john%"),
// ).All(&users)
type LikeExp = core.LikeExp
// ============================================================================
// DB Methods
// ============================================================================
// Open creates a new database connection with optional configuration.
//
// The driverName parameter specifies the database driver:
// - "postgres" - PostgreSQL
// - "mysql" - MySQL
// - "sqlite3" - SQLite
//
// The dsn parameter is the database-specific connection string.
//
// Example:
//
// db, err := relica.Open("postgres", "user=postgres dbname=myapp",
// relica.WithMaxOpenConns(100),
// relica.WithMaxIdleConns(50))
// if err != nil {
// log.Fatal(err)
// }
// defer db.Close()
func Open(driverName, dsn string, opts ...Option) (*DB, error) {
coreDB, err := core.Open(driverName, dsn, opts...)
if err != nil {
return nil, err
}
return &DB{db: coreDB}, nil
}
// NewDB creates a database connection.
//
// Deprecated: Use Open instead. NewDB will be removed in a future version.
//
// Example:
//
// db, err := relica.NewDB("postgres", dsn)
func NewDB(driverName, dsn string) (*DB, error) {
coreDB, err := core.NewDB(driverName, dsn)
if err != nil {
return nil, err
}
return &DB{db: coreDB}, nil
}
// WrapDB wraps an existing *sql.DB connection with Relica's query builder.
//
// The caller is responsible for managing the connection lifecycle (including Close()).
// This is useful when you need to:
// - Use Relica with an externally managed connection pool
// - Integrate with existing code that already has a *sql.DB instance
// - Apply custom connection pool settings before wrapping
//
// Example:
//
// sqlDB, _ := sql.Open("postgres", dsn)
// sqlDB.SetMaxOpenConns(100)
// sqlDB.SetConnMaxLifetime(time.Hour)
// db := relica.WrapDB(sqlDB, "postgres")
// defer sqlDB.Close() // Caller's responsibility
func WrapDB(sqlDB *sql.DB, driverName string) *DB {
coreDB := core.WrapDB(sqlDB, driverName)
return &DB{db: coreDB}
}
// Close releases all database resources including the connection pool
// and statement cache.
//
// After calling Close, the DB instance should not be used.
//
// Example:
//
// db, _ := relica.Open("postgres", dsn)
// defer db.Close()
func (d *DB) Close() error {
return d.db.Close()
}
// SqlDB returns the underlying *sql.DB connection.
// Useful for connection pool tuning, health checks, or database/sql methods.
// Do NOT call Close() on the returned value — use [DB.Close] instead.
func (d *DB) SqlDB() *sql.DB {
return d.db.SqlDB()
}
// PingContext verifies the database connection is alive.
// Use for health checks and connection validation at startup.
func (d *DB) PingContext(ctx context.Context) error {
return d.db.PingContext(ctx)
}
// DriverName returns the database driver name (e.g., "postgres", "mysql", "sqlite3").
func (d *DB) DriverName() string {
return d.db.DriverName()
}
// WithContext returns a new DB with the given context.
//
// The context will be used for all subsequent query operations
// unless overridden at the query level.
//
// Example:
//
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// defer cancel()
// db := db.WithContext(ctx)
// db.Builder().Select("*").From("users").All(&users)
func (d *DB) WithContext(ctx context.Context) *DB {
return &DB{db: d.db.WithContext(ctx)}
}
// Stats returns database connection pool statistics.
//
// Stats provides insights into connection pool usage including:
// - Number of open/idle/in-use connections
// - Wait count and duration
// - Connections closed due to max lifetime/idle time
// - Health check status (if enabled)
//
// Example:
//
// stats := db.Stats()
// fmt.Printf("Open: %d, Idle: %d, InUse: %d\n",
// stats.OpenConnections, stats.Idle, stats.InUse)
// if !stats.Healthy {
// log.Warn("Database health check failed")
// }
func (d *DB) Stats() PoolStats {
return d.db.Stats()
}
// IsHealthy returns true if the database connection is healthy.
// Always returns true if health checks are disabled.
//
// This is a convenience method that calls Stats() internally.
//
// Example:
//
// if !db.IsHealthy() {
// log.Error("Database connection unhealthy")
// // Attempt reconnection or alert
// }
func (d *DB) IsHealthy() bool {
return d.db.IsHealthy()
}
// WarmCache pre-warms the statement cache by preparing frequently-used queries.
//
// This improves performance at startup by avoiding cache misses for common queries.
// The queries are prepared synchronously in the order provided.
// Returns the number of successfully prepared queries and any error encountered.
//
// Example:
//
// n, err := db.WarmCache([]string{
// "SELECT * FROM users WHERE id = ?",
// "INSERT INTO logs (message, level) VALUES (?, ?)",
// "UPDATE users SET last_login = ? WHERE id = ?",
// })
// if err != nil {
// log.Warn("Failed to warm cache", "error", err, "warmed", n)
// }
func (d *DB) WarmCache(queries []string) (int, error) {
return d.db.WarmCache(queries)
}
// PinQuery marks a query as pinned in the statement cache, preventing eviction.
//
// Pinned queries remain in cache indefinitely, useful for frequently-used queries.
// Returns false if the query is not in cache (call WarmCache first).
//
// Example:
//
// // Warm and pin critical queries
// queries := []string{"SELECT * FROM users WHERE id = ?"}
// db.WarmCache(queries)
// db.PinQuery(queries[0]) // Will never be evicted
func (d *DB) PinQuery(query string) bool {
return d.db.PinQuery(query)
}
// UnpinQuery removes the pin from a cached query, allowing normal LRU eviction.
//
// Returns false if the query is not in cache or not pinned.
//
// Example:
//
// db.UnpinQuery("SELECT * FROM users WHERE id = ?")
func (d *DB) UnpinQuery(query string) bool {
return d.db.UnpinQuery(query)
}
// Builder returns a new QueryBuilder for constructing queries.
//
// The query builder provides a fluent interface for building
// SELECT, INSERT, UPDATE, DELETE, and UPSERT queries.
//
// Example:
//
// db.Builder().
// Select("*").
// From("users").
// Where("id = ?", 123).
// One(&user)
func (d *DB) Builder() *QueryBuilder {
return &QueryBuilder{qb: d.db.Builder()}
}
// NewQuery creates a raw SQL query for execution.
// Use this for queries that don't fit the query builder pattern,
// or when you need manual control over prepared statement lifecycle.
//
// Example:
//
// var count int
// err := db.NewQuery("SELECT COUNT(*) FROM users").Row(&count)
//
// // With parameters
// var user User
// err := db.NewQuery("SELECT * FROM users WHERE id = ?").Bind(1).One(&user)
//
// // With Prepare for repeated execution
// q := db.NewQuery("SELECT * FROM users WHERE status = ?").Prepare()
// defer q.Close()
// for _, status := range statuses {
// q.Bind(status).All(&users)
// }
func (d *DB) NewQuery(query string) *Query {
return &Query{q: d.db.NewQuery(query)}
}
// Model creates a ModelQuery for performing CRUD operations on a struct model.
//
// The model must be a pointer to a struct. The table name and primary key
// are automatically inferred from the struct definition.
//
// Table name resolution:
// 1. If model implements TableName() string, use that value
// 2. Otherwise, use struct name lowercased + 's' (e.g., User → users)
//
// Primary key detection:
// 1. Field with db:"id" tag
// 2. Field with db:"*_id" tag (e.g., db:"user_id")
// 3. Field named "ID"
//
// Example:
//
// type User struct {
// ID int `db:"id"`
// Name string `db:"name"`
// Email string `db:"email"`
// }
//
// func (User) TableName() string { return "users" }
//
// // INSERT - auto table name.
// user := User{Name: "Alice", Email: "alice@example.com"}
// err := db.Model(&user).Insert()
//
// // UPDATE - auto WHERE by primary key.
// user.Status = "active"
// err = db.Model(&user).Update()
//
// // DELETE - auto WHERE by primary key.
// err = db.Model(&user).Delete()
//
// // Field control.
// err = db.Model(&user).Exclude("CreatedAt", "UpdatedAt").Insert()
// err = db.Model(&user).Table("users_archive").Insert()
func (d *DB) Model(model any) *ModelQuery {
return &ModelQuery{mq: d.db.Model(model)}
}
// Select creates a new SELECT query.
//
// This is a convenience method equivalent to db.Builder().Select(cols...).
// For advanced queries (CTEs, subqueries, UNION), use db.Builder() directly.
//
// Example:
//
// var users []User
// err := db.Select("id", "name", "email").
// From("users").
// Where("active = ?", true).
// OrderBy("name").
// All(&users)
//
// // For wildcard selection
// err := db.Select("*").From("users").All(&users)
//
// // For advanced features, use Builder()
// err := db.Builder().
// With("stats", statsQuery).
// Select("*").
// From("stats").
// All(&results)
func (d *DB) Select(cols ...string) *SelectQuery {
return d.Builder().Select(cols...)
}
// Insert creates a new INSERT query.
//
// This is a convenience method equivalent to db.Builder().Insert(table, data).
// For batch inserts, use db.Builder().BatchInsert().
//
// Example:
//
// result, err := db.Insert("users", map[string]any{
// "name": "Alice",
// "email": "alice@example.com",
// }).Execute()
// if err != nil {
// return err
// }
// rows, _ := result.RowsAffected()
// fmt.Printf("Inserted %d row(s)\n", rows)
//
// // For batch operations, use Builder()
// result, err := db.Builder().
// BatchInsert("users", []string{"name", "email"}).
// Values("Alice", "alice@example.com").
// Values("Bob", "bob@example.com").
// Execute()
func (d *DB) Insert(table string, data map[string]any) *Query {
return d.Builder().Insert(table, data)
}
// InsertStruct builds an INSERT query from a struct using db tags.
//
// The struct fields are mapped to database columns using the `db` struct tag.
// Fields without a `db` tag use the field name.
// Fields tagged with `db:"-"` are ignored.
// Unexported fields are automatically skipped.
//
// This method provides type-safe struct-based inserts without manually
// constructing maps. For batch struct inserts, use BatchInsertStruct.
//
// Example:
//
// type User struct {
// ID int `db:"id"`
// Name string `db:"name"`
// Email string `db:"email"`
// Skip int `db:"-"` // ignored
// }
//
// user := User{Name: "Alice", Email: "alice@example.com"}
// result, err := db.InsertStruct("users", &user).Execute()
// if err != nil {
// return err
// }
func (d *DB) InsertStruct(table string, data any) *Query {
return d.Builder().InsertStruct(table, data)
}
// BatchInsertStruct builds a batch INSERT query from a slice of structs.
//
// This method performs batch insertion of multiple structs in a single query,
// which is significantly faster than individual inserts. All structs must
// have the same type and will be inserted with the same column set.
//
// The slice element type must be a struct or pointer to struct.
// Fields are mapped using the same rules as InsertStruct.
//
// Example:
//
// users := []User{
// {Name: "Alice", Email: "alice@example.com"},
// {Name: "Bob", Email: "bob@example.com"},
// }
// result, err := db.BatchInsertStruct("users", users).Execute()
// if err != nil {
// return err
// }
//
// For single struct inserts, use InsertStruct instead.
func (d *DB) BatchInsertStruct(table string, data any) *Query {
return d.Builder().BatchInsertStruct(table, data)
}
// UpdateStruct builds an UPDATE query from a struct using db tags.
//
// Similar to InsertStruct, but for UPDATE operations. The struct fields
// are converted to SET clauses. You must chain a Where() call to specify
// which rows to update.
//
// This method provides type-safe struct-based updates without manually
// constructing maps.
//
// Example:
//
// user := User{Name: "Alice Updated", Status: "active"}
// result, err := db.UpdateStruct("users", &user).
// Where("id = ?", user.ID).
// Execute()
// if err != nil {
// return err
// }
//
// For automatic WHERE clause based on primary key, consider using
// the Model() API (available in v0.6.0+).
func (d *DB) UpdateStruct(table string, data any) *UpdateQuery {
return d.Builder().UpdateStruct(table, data)
}
// Update creates a new UPDATE query.
//
// This is a convenience method equivalent to db.Builder().Update(table).
// For batch updates, use db.Builder().BatchUpdate().
//
// Example:
//
// _, err := db.Update("users").
// Set(map[string]any{"status": "active"}).
// Where("id = ?", 123).
// Execute()
// if err != nil {
// return err
// }
//
// // For batch operations, use Builder()
// _, err := db.Builder().
// BatchUpdate("users", "id").
// Set(1, map[string]any{"status": "active"}).
// Set(2, map[string]any{"status": "inactive"}).
// Execute()
func (d *DB) Update(table string) *UpdateQuery {
return d.Builder().Update(table)
}
// Delete creates a new DELETE query.
//
// This is a convenience method equivalent to db.Builder().Delete(table).
//
// Example:
//
// _, err := db.Delete("users").
// Where("id = ?", 123).
// Execute()
// if err != nil {
// return err
// }
//
// // Delete multiple rows
// _, err := db.Delete("users").
// Where("status = ?", "inactive").
// Execute()
func (d *DB) Delete(table string) *DeleteQuery {
return d.Builder().Delete(table)
}
// BatchInsert creates a new batch INSERT query for inserting multiple rows efficiently.
//
// This is a convenience method equivalent to db.Builder().BatchInsert(table, columns).
//
// Example:
//
// result, err := db.BatchInsert("users", []string{"name", "email"}).
// Values("Alice", "alice@example.com").
// Values("Bob", "bob@example.com").
// Execute()
func (d *DB) BatchInsert(table string, columns []string) *BatchInsertQuery {
return d.Builder().BatchInsert(table, columns)
}
// BatchUpdate creates a new batch UPDATE query for updating multiple rows with different values.
//
// This is a convenience method equivalent to db.Builder().BatchUpdate(table, keyColumn).
//
// Example:
//
// result, err := db.BatchUpdate("users", "id").
// Set(1, map[string]any{"name": "Alice"}).
// Set(2, map[string]any{"name": "Bob"}).
// Execute()
func (d *DB) BatchUpdate(table, keyColumn string) *BatchUpdateQuery {
return d.Builder().BatchUpdate(table, keyColumn)
}
// Upsert creates a new UPSERT query (INSERT ... ON CONFLICT).
//
// This is a convenience method equivalent to db.Builder().Upsert(table, values).
//
// Example:
//
// result, err := db.Upsert("users", map[string]any{
// "email": "alice@example.com",
// "name": "Alice",
// }).OnConflict("email").DoUpdate("name").Execute()
func (d *DB) Upsert(table string, values map[string]any) *UpsertQuery {
return d.Builder().Upsert(table, values)
}
// Begin starts a transaction with default options.
//
// The transaction must be committed or rolled back to release resources.
// It's safe to call Rollback() even after Commit().
//
// Example:
//
// tx, err := db.Begin(ctx)
// if err != nil {
// return err
// }
// defer tx.Rollback() // Safe even after Commit
//
// // Use transaction
// _, err = tx.Insert("users", data).Execute()
// if err != nil {
// return err
// }
//
// return tx.Commit()
func (d *DB) Begin(ctx context.Context) (*Tx, error) {
coreTx, err := d.db.Begin(ctx)
if err != nil {
return nil, err
}
return &Tx{tx: coreTx}, nil
}
// BeginTx starts a transaction with specified options.
//
// Options can specify isolation level and read-only mode:
// - Isolation: sql.LevelReadUncommitted, sql.LevelReadCommitted,
// sql.LevelRepeatableRead, sql.LevelSerializable
// - ReadOnly: true for read-only transactions (some databases optimize these)
//
// Example:
//
// opts := &relica.TxOptions{
// Isolation: sql.LevelSerializable,
// ReadOnly: false,
// }
// tx, err := db.BeginTx(ctx, opts)
func (d *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) {
coreTx, err := d.db.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
return &Tx{tx: coreTx}, nil
}
// Transactional executes f within a transaction with automatic commit/rollback.
//
// If f returns an error, the transaction is rolled back and the error is returned.
// If f panics, the transaction is rolled back and the panic is re-raised.
// If f completes successfully, the transaction is committed.
//
// This helper simplifies transaction management and ensures proper cleanup
// in all code paths, including panics.
//
// Example:
//
// err := db.Transactional(ctx, func(tx *relica.Tx) error {
// user := User{Name: "Alice", Email: "alice@example.com"}
// if err := tx.Model(&user).Insert(); err != nil {
// return err // Auto rollback
// }
//
// account := Account{UserID: user.ID, Balance: 100}
// if err := tx.Model(&account).Insert(); err != nil {
// return err // Auto rollback
// }
//
// return nil // Auto commit
// })
func (d *DB) Transactional(ctx context.Context, f func(*Tx) error) error {
return d.db.Transactional(ctx, func(coreTx *core.Tx) error {
return f(&Tx{tx: coreTx})
})
}
// TransactionalTx executes f within a transaction with custom options.
//
// Options can specify isolation level and read-only mode.
// If f returns an error, the transaction is rolled back and the error is returned.
// If f panics, the transaction is rolled back and the panic is re-raised.
// If f completes successfully, the transaction is committed.
//
// Example:
//
// opts := &relica.TxOptions{
// Isolation: sql.LevelSerializable,
// ReadOnly: false,
// }
// err := db.TransactionalTx(ctx, opts, func(tx *relica.Tx) error {
// // Perform operations within serializable transaction.
// return tx.Model(&user).Update()
// })
func (d *DB) TransactionalTx(ctx context.Context, opts *TxOptions, f func(*Tx) error) error {
return d.db.TransactionalTx(ctx, opts, func(coreTx *core.Tx) error {
return f(&Tx{tx: coreTx})
})
}
// ExecContext executes a raw SQL query (INSERT/UPDATE/DELETE).
//
// This bypasses the query builder and executes SQL directly.
// Use this for queries that aren't supported by the query builder
// or when you need maximum control.
//
// Example:
//
// result, err := db.ExecContext(ctx,
// "UPDATE users SET status = ? WHERE id = ?",
// 1, 123)
// if err != nil {
// return err
// }
// rowsAffected, _ := result.RowsAffected()
func (d *DB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
return d.db.ExecContext(ctx, query, args...)
}
// QueryContext executes a raw SQL query and returns rows.
//
// This bypasses the query builder and executes SQL directly.
// You are responsible for closing the returned rows.
//
// Example:
//
// rows, err := db.QueryContext(ctx,
// "SELECT * FROM users WHERE status = ?", 1)
// if err != nil {
// return err
// }
// defer rows.Close()
//
// for rows.Next() {
// // Process rows
// }
func (d *DB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
return d.db.QueryContext(ctx, query, args...)
}
// QueryRowContext executes a raw SQL query expected to return at most one row.
//
// This bypasses the query builder and executes SQL directly.
//
// Example:
//
// var count int
// err := db.QueryRowContext(ctx,
// "SELECT COUNT(*) FROM users").Scan(&count)
func (d *DB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row {
return d.db.QueryRowContext(ctx, query, args...)
}
// QuoteTableName quotes a table name using the database's identifier quoting style.
//
// This is useful when building dynamic SQL queries.
//
// Example:
//
// quoted := db.QuoteTableName("users")
// // PostgreSQL: "users"
// // MySQL: `users`
func (d *DB) QuoteTableName(table string) string {
return d.db.QuoteTableName(table)
}
// QuoteColumnName quotes a column name using the database's identifier quoting style.
//
// This is useful when building dynamic SQL queries.
//
// Example:
//
// quoted := db.QuoteColumnName("user_id")
// // PostgreSQL: "user_id"
// // MySQL: `user_id`
func (d *DB) QuoteColumnName(column string) string {
return d.db.QuoteColumnName(column)
}
// GenerateParamName generates a dialect-specific parameter placeholder for the given index.
// For PostgreSQL, returns "$1", "$2", etc. For MySQL/SQLite, returns "?".
//
// This is useful when building dynamic SQL queries where you need
// the correct placeholder syntax for the active database driver.
//
// Example:
//
// ph1 := db.GenerateParamName(1) // PostgreSQL: "$1", MySQL/SQLite: "?"
// ph2 := db.GenerateParamName(2) // PostgreSQL: "$2", MySQL/SQLite: "?"
func (d *DB) GenerateParamName(index int) string {
return d.db.GenerateParamName(index)
}
// Unwrap returns the underlying core.DB for advanced use cases.
//
// This method is provided for edge cases where direct access to
// internal types is needed. Most users should not need this.
//
// Example:
//
// coreDB := db.Unwrap()