-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepository.go
More file actions
779 lines (745 loc) · 22 KB
/
repository.go
File metadata and controls
779 lines (745 loc) · 22 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
package norm
import (
"context"
"fmt"
"reflect"
"strings"
pgxv5 "github.com/jackc/pgx/v5"
core "github.com/kintsdev/norm/internal/core"
)
// Condition is a placeholder for typed conditions
// moved to conditions.go
// Repository defines generic CRUD operations for type T
type Repository[T any] interface {
Create(ctx context.Context, entity *T) error
CreateBatch(ctx context.Context, entities []*T) error
GetByID(ctx context.Context, id any) (*T, error)
Update(ctx context.Context, entity *T) error
UpdatePartial(ctx context.Context, id any, fields map[string]any) error
Delete(ctx context.Context, id any) error
SoftDelete(ctx context.Context, id any) error
SoftDeleteAll(ctx context.Context) (int64, error)
Restore(ctx context.Context, id any) error
PurgeTrashed(ctx context.Context) (int64, error)
Find(ctx context.Context, conditions ...Condition) ([]*T, error)
FindOne(ctx context.Context, conditions ...Condition) (*T, error)
Count(ctx context.Context, conditions ...Condition) (int64, error)
Exists(ctx context.Context, conditions ...Condition) (bool, error)
WithTrashed() Repository[T]
OnlyTrashed() Repository[T]
FindPage(ctx context.Context, page PageRequest, conditions ...Condition) (Page[T], error)
CreateCopyFrom(ctx context.Context, entities []*T, columns ...string) (int64, error)
Upsert(ctx context.Context, entity *T, conflictCols []string, updateCols []string) error
}
// repo is a minimal placeholder implementation to compile
type repo[T any] struct {
kn *KintsNorm
exec dbExecuter
mode softDeleteMode
}
type softDeleteMode int
const (
softModeDefault softDeleteMode = iota
softModeWithTrashed
softModeOnlyTrashed
)
// NewRepository creates a new generic repository
func NewRepository[T any](kn *KintsNorm) Repository[T] {
var exec dbExecuter
// auto-route reads to readPool when configured
if kn.readPool != nil {
exec = routingExecuter{kn: kn}
} else {
exec = kn.pool
if kn.breaker != nil {
exec = breakerExecuter{kn: kn, exec: exec}
}
}
return &repo[T]{kn: kn, exec: exec}
}
// NewRepositoryWithExecutor creates a repository bound to a specific executor (pool or tx)
func NewRepositoryWithExecutor[T any](kn *KintsNorm, exec dbExecuter) Repository[T] {
return &repo[T]{kn: kn, exec: exec}
}
func (r *repo[T]) WithTrashed() Repository[T] { nr := *r; nr.mode = softModeWithTrashed; return &nr }
func (r *repo[T]) OnlyTrashed() Repository[T] { nr := *r; nr.mode = softModeOnlyTrashed; return &nr }
// audit emits an audit entry if a global audit hook is registered
func (r *repo[T]) audit(ctx context.Context, action AuditAction, entityID any, entity any, query string, err error) {
if r.kn == nil || r.kn.auditHook == nil {
return
}
r.kn.auditHook.OnAudit(ctx, AuditEntry{
Action: action,
Table: r.tableName(),
EntityID: entityID,
Entity: entity,
Query: query,
Err: err,
})
}
func (r *repo[T]) tableName() string {
var t T
typ := reflect.TypeOf(t)
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
return core.ToSnakeCase(typ.Name()) + "s"
}
func (r *repo[T]) Create(ctx context.Context, entity *T) error {
if entity == nil {
return &ORMError{Code: ErrCodeValidation, Message: "nil entity"}
}
// model hook: BeforeCreate
if bc, ok := any(entity).(BeforeCreate); ok {
if err := bc.BeforeCreate(ctx); err != nil {
return err
}
}
execFn := func() error {
val := reflect.Indirect(reflect.ValueOf(entity))
typ := val.Type()
mapper := core.StructMapper(typ)
cols := make([]string, 0, typ.NumField())
placeholders := make([]string, 0, typ.NumField())
args := make([]any, 0, typ.NumField())
idx := 1
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if f.PkgPath != "" {
continue
}
col := f.Tag.Get("db")
if col == "" {
col = core.ToSnakeCase(f.Name)
}
if mapper.AutoIncrement && strings.EqualFold(col, mapper.PrimaryColumn) {
continue
}
// Prefer `norm` tag; fallback to legacy `orm`
orm := f.Tag.Get("norm")
if orm == "" {
orm = f.Tag.Get("orm")
}
// skip ignored fields
low := strings.ToLower(orm)
if strings.Contains(low, "-") || strings.Contains(low, "ignore") {
continue
}
fv := val.Field(i)
if strings.Contains(orm, "default:") && fv.IsZero() {
continue
}
cols = append(cols, col)
placeholders = append(placeholders, fmt.Sprintf("$%d", idx))
args = append(args, fv.Interface())
idx++
}
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", r.tableName(), strings.Join(cols, ", "), strings.Join(placeholders, ", "))
_, err := r.exec.Exec(ctx, query, args...)
if err != nil {
return wrapPgError(err, query, args)
}
return nil
}
if r.kn != nil {
if err := r.kn.withRetry(ctx, execFn); err != nil {
return err
}
} else {
if err := execFn(); err != nil {
return err
}
}
// model hook: AfterCreate
if ac, ok := any(entity).(AfterCreate); ok {
if err := ac.AfterCreate(ctx); err != nil {
return err
}
}
r.audit(ctx, AuditActionCreate, nil, entity, "", nil)
return nil
}
func (r *repo[T]) CreateBatch(ctx context.Context, entities []*T) error {
if len(entities) == 0 {
return nil
}
// Wrap in a transaction for atomicity when pool is available
if r.kn != nil && r.kn.pool != nil {
tx, err := r.kn.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx) //nolint:errcheck
txExec := dbExecuter(tx)
if r.kn.breaker != nil {
txExec = breakerExecuter{kn: r.kn, exec: tx}
}
txRepo := &repo[T]{kn: r.kn, exec: txExec, mode: r.mode}
for _, e := range entities {
if err := txRepo.Create(ctx, e); err != nil {
return err
}
}
return tx.Commit(ctx)
}
// Fallback: sequential creates when pool is not directly available
for _, e := range entities {
if err := r.Create(ctx, e); err != nil {
return err
}
}
return nil
}
func (r *repo[T]) GetByID(ctx context.Context, id any) (*T, error) {
var out []T
qb := r.kn.Query().Table(r.tableName()).Where("id = ?", id).Limit(1)
// Apply soft-delete default filter if model has deleted_at
var t T
if core.ModelHasSoftDelete(reflect.TypeOf(t)) {
switch r.mode {
case softModeOnlyTrashed:
qb = qb.Where("deleted_at IS NOT NULL")
case softModeWithTrashed:
// no filter
default:
qb = qb.Where("deleted_at IS NULL")
}
}
if err := qb.Find(ctx, &out); err != nil {
return nil, err
}
if len(out) == 0 {
return nil, &ORMError{Code: ErrCodeNotFound, Message: "not found"}
}
return &out[0], nil
}
func (r *repo[T]) Update(ctx context.Context, entity *T) error {
// model hook: BeforeUpdate
if bu, ok := any(entity).(BeforeUpdate); ok {
if err := bu.BeforeUpdate(ctx); err != nil {
return err
}
}
val := reflect.Indirect(reflect.ValueOf(entity))
typ := val.Type()
mapper := core.StructMapper(typ)
if mapper.PrimaryColumn == "" {
return &ORMError{Code: ErrCodeValidation, Message: "no primary key"}
}
sets := []string{}
args := []any{}
idx := 1
var id any
// discover columns that should be set to NOW() on update
onUpdateNow := r.onUpdateNowColumns(typ)
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if f.PkgPath != "" {
continue
}
col := f.Tag.Get("db")
if col == "" {
col = core.ToSnakeCase(f.Name)
}
v := val.Field(i).Interface()
if strings.EqualFold(col, mapper.PrimaryColumn) {
id = v
continue
}
// optimistic locking: version column gets incremented
if strings.EqualFold(col, mapper.VersionColumn) && mapper.VersionColumn != "" {
sets = append(sets, fmt.Sprintf("%s = %s + 1", col, col))
continue
}
if onUpdateNow[col] {
sets = append(sets, fmt.Sprintf("%s = NOW()", col))
continue
}
sets = append(sets, fmt.Sprintf("%s = $%d", col, idx))
args = append(args, v)
idx++
}
if id == nil {
return &ORMError{Code: ErrCodeValidation, Message: "missing primary key value"}
}
// add conditions for optimistic locking if versionColumn present
if mapper.VersionColumn != "" {
// read current version value from entity
curVersion := reflect.Indirect(reflect.ValueOf(entity)).FieldByNameFunc(func(n string) bool { return strings.EqualFold(core.ToSnakeCase(n), mapper.VersionColumn) }).Interface()
args = append(args, id, curVersion)
query := fmt.Sprintf("UPDATE %s SET %s WHERE %s = $%d AND %s = $%d", r.tableName(), strings.Join(sets, ", "), mapper.PrimaryColumn, idx, mapper.VersionColumn, idx+1)
tag, err := r.exec.Exec(ctx, query, args...)
if err != nil {
return wrapPgError(err, query, args)
}
if tag.RowsAffected() == 0 {
return &ORMError{Code: ErrCodeTransaction, Message: "optimistic lock conflict"}
}
r.audit(ctx, AuditActionUpdate, id, entity, query, nil)
return nil
}
args = append(args, id)
query := fmt.Sprintf("UPDATE %s SET %s WHERE %s = $%d", r.tableName(), strings.Join(sets, ", "), mapper.PrimaryColumn, idx)
_, err := r.exec.Exec(ctx, query, args...)
if err != nil {
return wrapPgError(err, query, args)
}
// model hook: AfterUpdate
if au, ok := any(entity).(AfterUpdate); ok {
if err := au.AfterUpdate(ctx); err != nil {
return err
}
}
r.audit(ctx, AuditActionUpdate, id, entity, query, nil)
return nil
}
func (r *repo[T]) UpdatePartial(ctx context.Context, id any, fields map[string]any) error {
// discover on_update:now() columns for T
var t T
typ := reflect.TypeOf(t)
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
onUpdateNow := r.onUpdateNowColumns(typ)
if len(fields) == 0 {
if len(onUpdateNow) == 0 {
return nil
}
sets := make([]string, 0, len(onUpdateNow))
for col := range onUpdateNow {
sets = append(sets, fmt.Sprintf("%s = NOW()", col))
}
query := fmt.Sprintf("UPDATE %s SET %s WHERE id = $1", r.tableName(), strings.Join(sets, ", "))
_, err := r.exec.Exec(ctx, query, id)
return err
}
idx := 1
sets := make([]string, 0, len(fields))
args := make([]any, 0, len(fields)+1)
provided := map[string]struct{}{}
for col, v := range fields {
sets = append(sets, fmt.Sprintf("%s = $%d", col, idx))
args = append(args, v)
idx++
provided[strings.ToLower(col)] = struct{}{}
}
// add NOW() for on_update columns not explicitly provided
for col := range onUpdateNow {
if _, ok := provided[strings.ToLower(col)]; !ok {
sets = append(sets, fmt.Sprintf("%s = NOW()", col))
}
}
args = append(args, id)
query := fmt.Sprintf("UPDATE %s SET %s WHERE id = $%d", r.tableName(), strings.Join(sets, ", "), idx)
_, err := r.exec.Exec(ctx, query, args...)
return err
}
func (r *repo[T]) Delete(ctx context.Context, id any) error {
// dispatch hooks on zero-value model if implemented
var t T
if bd, ok := any(&t).(BeforeDelete); ok {
if err := bd.BeforeDelete(ctx, id); err != nil {
return err
}
} else if bdv, ok := any(t).(BeforeDelete); ok {
if err := bdv.BeforeDelete(ctx, id); err != nil {
return err
}
}
query := fmt.Sprintf("DELETE FROM %s WHERE id = $1", r.tableName())
_, err := r.exec.Exec(ctx, query, id)
if err != nil {
r.audit(ctx, AuditActionDelete, id, nil, query, err)
return err
}
r.audit(ctx, AuditActionDelete, id, nil, query, nil)
if ad, ok := any(&t).(AfterDelete); ok {
if err := ad.AfterDelete(ctx, id); err != nil {
return err
}
} else if adv, ok := any(t).(AfterDelete); ok {
if err := adv.AfterDelete(ctx, id); err != nil {
return err
}
}
return nil
}
func (r *repo[T]) SoftDelete(ctx context.Context, id any) error {
// ensure model supports soft delete
var t T
if !core.ModelHasSoftDelete(reflect.TypeOf(t)) {
return &ORMError{Code: ErrCodeValidation, Message: "soft delete not supported: missing deleted_at column"}
}
if bsd, ok := any(&t).(BeforeSoftDelete); ok {
if err := bsd.BeforeSoftDelete(ctx, id); err != nil {
return err
}
} else if bsdv, ok := any(t).(BeforeSoftDelete); ok {
if err := bsdv.BeforeSoftDelete(ctx, id); err != nil {
return err
}
}
// expects a deleted_at column
query := fmt.Sprintf("UPDATE %s SET deleted_at = NOW() WHERE id = $1", r.tableName())
_, err := r.exec.Exec(ctx, query, id)
if err != nil {
r.audit(ctx, AuditActionSoftDelete, id, nil, query, err)
return err
}
r.audit(ctx, AuditActionSoftDelete, id, nil, query, nil)
if asd, ok := any(&t).(AfterSoftDelete); ok {
if err := asd.AfterSoftDelete(ctx, id); err != nil {
return err
}
} else if asdv, ok := any(t).(AfterSoftDelete); ok {
if err := asdv.AfterSoftDelete(ctx, id); err != nil {
return err
}
}
return nil
}
func (r *repo[T]) SoftDeleteAll(ctx context.Context) (int64, error) {
var t T
if !core.ModelHasSoftDelete(reflect.TypeOf(t)) {
return 0, &ORMError{Code: ErrCodeValidation, Message: "soft delete not supported: missing deleted_at column"}
}
query := fmt.Sprintf("UPDATE %s SET deleted_at = NOW() WHERE deleted_at IS NULL", r.tableName())
tag, err := r.exec.Exec(ctx, query)
if err != nil {
return 0, wrapPgError(err, query, nil)
}
return int64(tag.RowsAffected()), nil
}
func (r *repo[T]) Restore(ctx context.Context, id any) error {
var t T
if !core.ModelHasSoftDelete(reflect.TypeOf(t)) {
return &ORMError{Code: ErrCodeValidation, Message: "restore not supported: missing deleted_at column"}
}
if br, ok := any(&t).(BeforeRestore); ok {
if err := br.BeforeRestore(ctx, id); err != nil {
return err
}
} else if brv, ok := any(t).(BeforeRestore); ok {
if err := brv.BeforeRestore(ctx, id); err != nil {
return err
}
}
query := fmt.Sprintf("UPDATE %s SET deleted_at = NULL WHERE id = $1", r.tableName())
_, err := r.exec.Exec(ctx, query, id)
if err != nil {
r.audit(ctx, AuditActionRestore, id, nil, query, err)
return wrapPgError(err, query, []any{id})
}
r.audit(ctx, AuditActionRestore, id, nil, query, nil)
if ar, ok := any(&t).(AfterRestore); ok {
if err := ar.AfterRestore(ctx, id); err != nil {
return err
}
} else if arv, ok := any(t).(AfterRestore); ok {
if err := arv.AfterRestore(ctx, id); err != nil {
return err
}
}
return nil
}
func (r *repo[T]) PurgeTrashed(ctx context.Context) (int64, error) {
var t T
if !core.ModelHasSoftDelete(reflect.TypeOf(t)) {
return 0, &ORMError{Code: ErrCodeValidation, Message: "purge not supported: missing deleted_at column"}
}
if bp, ok := any(&t).(BeforePurgeTrashed); ok {
if err := bp.BeforePurgeTrashed(ctx); err != nil {
return 0, err
}
} else if bpv, ok := any(t).(BeforePurgeTrashed); ok {
if err := bpv.BeforePurgeTrashed(ctx); err != nil {
return 0, err
}
}
query := fmt.Sprintf("DELETE FROM %s WHERE deleted_at IS NOT NULL", r.tableName())
tag, err := r.exec.Exec(ctx, query)
if err != nil {
r.audit(ctx, AuditActionPurge, nil, nil, query, err)
return 0, wrapPgError(err, query, nil)
}
r.audit(ctx, AuditActionPurge, nil, nil, query, nil)
affected := int64(tag.RowsAffected())
if ap, ok := any(&t).(AfterPurgeTrashed); ok {
if err := ap.AfterPurgeTrashed(ctx, affected); err != nil {
return 0, err
}
} else if apv, ok := any(t).(AfterPurgeTrashed); ok {
if err := apv.AfterPurgeTrashed(ctx, affected); err != nil {
return 0, err
}
}
return affected, nil
}
func (r *repo[T]) Find(ctx context.Context, conditions ...Condition) ([]*T, error) {
qb := r.kn.Query().Table(r.tableName())
for _, c := range conditions {
qb = qb.Where(c.Expr, c.Args...)
}
var t T
if core.ModelHasSoftDelete(reflect.TypeOf(t)) {
switch r.mode {
case softModeOnlyTrashed:
qb = qb.Where("deleted_at IS NOT NULL")
case softModeWithTrashed:
// no filter
default:
qb = qb.Where("deleted_at IS NULL")
}
}
var out []*T
// scan to non-pointer, then take address
var tmp []T
if err := qb.Find(ctx, &tmp); err != nil {
return nil, err
}
for i := range tmp {
out = append(out, &tmp[i])
}
return out, nil
}
func (r *repo[T]) FindOne(ctx context.Context, conditions ...Condition) (*T, error) {
qb := r.kn.Query().Table(r.tableName()).Limit(1)
for _, c := range conditions {
qb = qb.Where(c.Expr, c.Args...)
}
var t T
if core.ModelHasSoftDelete(reflect.TypeOf(t)) {
switch r.mode {
case softModeOnlyTrashed:
qb = qb.Where("deleted_at IS NOT NULL")
case softModeWithTrashed:
// no filter
default:
qb = qb.Where("deleted_at IS NULL")
}
}
var out []T
if err := qb.Find(ctx, &out); err != nil {
return nil, err
}
if len(out) == 0 {
return nil, &ORMError{Code: ErrCodeNotFound, Message: "not found"}
}
return &out[0], nil
}
func (r *repo[T]) Count(ctx context.Context, conditions ...Condition) (int64, error) {
qb := r.kn.Query().Table(r.tableName()).Select("COUNT(*)")
for _, c := range conditions {
qb = qb.Where(c.Expr, c.Args...)
}
var t T
if core.ModelHasSoftDelete(reflect.TypeOf(t)) {
switch r.mode {
case softModeOnlyTrashed:
qb = qb.Where("deleted_at IS NOT NULL")
case softModeWithTrashed:
// no filter
default:
qb = qb.Where("deleted_at IS NULL")
}
}
var rows []map[string]any
if err := qb.Find(ctx, &rows); err != nil {
return 0, err
}
if len(rows) == 0 {
return 0, nil
}
switch v := rows[0]["count"].(type) {
case int64:
return v, nil
case int32:
return int64(v), nil
case int:
return int64(v), nil
default:
return 0, nil
}
}
func (r *repo[T]) Exists(ctx context.Context, conditions ...Condition) (bool, error) {
c, err := r.Count(ctx, conditions...)
return c > 0, err
}
// PageRequest describes pagination and ordering
type PageRequest struct {
Limit int
Offset int
OrderBy string // e.g., "id ASC" or "created_at DESC"
}
// Page represents a paginated result
type Page[T any] struct {
Items []*T
Total int64
Limit int
Offset int
}
// FindPage returns a page of results and total count with the same filters
func (r *repo[T]) FindPage(ctx context.Context, page PageRequest, conditions ...Condition) (Page[T], error) {
total, err := r.Count(ctx, conditions...)
if err != nil {
return Page[T]{}, err
}
qb := r.kn.Query().Table(r.tableName())
for _, c := range conditions {
qb = qb.Where(c.Expr, c.Args...)
}
var t T
if core.ModelHasSoftDelete(reflect.TypeOf(t)) {
switch r.mode {
case softModeOnlyTrashed:
qb = qb.Where("deleted_at IS NOT NULL")
case softModeWithTrashed:
default:
qb = qb.Where("deleted_at IS NULL")
}
}
if page.OrderBy != "" {
qb = qb.OrderBy(page.OrderBy)
}
if page.Limit > 0 {
qb = qb.Limit(page.Limit)
}
if page.Offset > 0 {
qb = qb.Offset(page.Offset)
}
var tmp []T
if err := qb.Find(ctx, &tmp); err != nil {
return Page[T]{}, err
}
items := make([]*T, 0, len(tmp))
for i := range tmp {
items = append(items, &tmp[i])
}
return Page[T]{Items: items, Total: total, Limit: page.Limit, Offset: page.Offset}, nil
}
// CreateCopyFrom performs bulk insert using pgx CopyFrom for high-throughput writes.
// columns must be provided in db column names order.
func (r *repo[T]) CreateCopyFrom(ctx context.Context, entities []*T, columns ...string) (int64, error) {
rows := make([][]any, 0, len(entities))
for _, e := range entities {
vals, err := r.extractValuesByColumns(e, columns)
if err != nil {
return 0, err
}
rows = append(rows, vals)
}
// Acquire a connection from the pool directly for CopyFrom
conn, err := r.kn.pool.Acquire(ctx)
if err != nil {
return 0, err
}
defer conn.Release()
src := pgxv5.CopyFromRows(rows)
n, err := conn.CopyFrom(ctx, pgxv5.Identifier{r.tableName()}, columns, src)
if err != nil {
return 0, wrapPgError(err, fmt.Sprintf("COPY %s (...)", r.tableName()), nil)
}
return n, nil
}
func (r *repo[T]) extractValuesByColumns(entity *T, columns []string) ([]any, error) {
val := reflect.Indirect(reflect.ValueOf(entity))
typ := val.Type()
mapper := core.StructMapper(typ)
out := make([]any, len(columns))
for i, col := range columns {
fi, ok := mapper.FieldsByColumn[strings.ToLower(col)]
if !ok {
return nil, &ORMError{Code: ErrCodeInvalidColumn, Message: fmt.Sprintf("unknown column: %s", col)}
}
out[i] = val.FieldByIndex(fi.Index).Interface()
}
return out, nil
}
// Upsert performs INSERT ... ON CONFLICT (...) DO UPDATE SET col = EXCLUDED.col for given columns
func (r *repo[T]) Upsert(ctx context.Context, entity *T, conflictCols []string, updateCols []string) error {
// model hook: BeforeUpsert
if bu, ok := any(entity).(BeforeUpsert); ok {
if err := bu.BeforeUpsert(ctx); err != nil {
return err
}
}
// Build from reflection
val := reflect.Indirect(reflect.ValueOf(entity))
typ := val.Type()
mapper := core.StructMapper(typ)
cols := []string{}
placeholders := []string{}
args := []any{}
idx := 1
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if f.PkgPath != "" {
continue
}
col := f.Tag.Get("db")
if col == "" {
col = core.ToSnakeCase(f.Name)
}
if mapper.AutoIncrement && strings.EqualFold(col, mapper.PrimaryColumn) {
continue
}
cols = append(cols, col)
placeholders = append(placeholders, fmt.Sprintf("$%d", idx))
args = append(args, val.Field(i).Interface())
idx++
}
setParts := make([]string, 0, len(updateCols))
for _, c := range updateCols {
setParts = append(setParts, fmt.Sprintf("%s = EXCLUDED.%s", c, c))
}
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s) ON CONFLICT (%s) DO UPDATE SET %s", r.tableName(), strings.Join(cols, ", "), strings.Join(placeholders, ", "), strings.Join(conflictCols, ", "), strings.Join(setParts, ", "))
_, err := r.exec.Exec(ctx, query, args...)
if err != nil {
return wrapPgError(err, query, args)
}
// model hook: AfterUpsert
if au, ok := any(entity).(AfterUpsert); ok {
if err := au.AfterUpsert(ctx); err != nil {
return err
}
}
r.audit(ctx, AuditActionUpsert, nil, entity, query, nil)
return nil
}
// onUpdateNowColumns returns a set of db column names that have orm tag on_update:now()
func (r *repo[T]) onUpdateNowColumns(typ reflect.Type) map[string]bool {
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
out := make(map[string]bool)
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if f.PkgPath != "" {
continue
}
// Prefer `norm` tag; fallback to legacy `orm`
orm := f.Tag.Get("norm")
if orm == "" {
orm = f.Tag.Get("orm")
}
low := strings.ToLower(orm)
if strings.Contains(low, "-") || strings.Contains(low, "ignore") {
continue
}
if orm == "" {
continue
}
parts := strings.Split(orm, ",")
for _, p := range parts {
p = strings.TrimSpace(p)
if strings.EqualFold(p, "on_update:now()") {
col := f.Tag.Get("db")
if col == "" {
col = core.ToSnakeCase(f.Name)
}
out[col] = true
}
}
}
return out
}