-
Notifications
You must be signed in to change notification settings - Fork 5
/
pika_psql_experimental.go
73 lines (58 loc) · 1.45 KB
/
pika_psql_experimental.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
// SPDX-FileCopyrightText: Copyright (c) 2023-2024, Ctrl IQ, Inc. All rights reserved
// SPDX-License-Identifier: Apache-2.0
package pika
import (
"context"
"fmt"
"reflect"
)
func (b *basePsql[T]) findID(x *T) any {
elem := reflect.ValueOf(x).Elem()
// Check if ID is a field
idField := elem.FieldByName("ID")
if idField.IsValid() {
return idField.Interface()
}
// Also check for Id field
idField = elem.FieldByName("Id")
if idField.IsValid() {
return idField.Interface()
}
// Return nil if ID is not a field
return nil
}
func (b *basePsql[T]) F(keyval ...any) QuerySet[T] {
args := NewArgs()
var queries []string
for i := 0; i < len(keyval); i += 2 {
args.Set(keyval[i].(string), keyval[i+1])
filter := fmt.Sprintf("%s=:%s", keyval[i].(string), keyval[i].(string))
queries = append(queries, filter)
}
logger.Debugf("F: %s", queries)
return b.Args(args).Filter(queries...)
}
func (b *basePsql[T]) D(ctx context.Context, x *T) error {
id := b.findID(x)
if id == nil {
return fmt.Errorf("id not found")
}
qs := b.F("id", id)
return qs.Delete(ctx)
}
func (b *basePsql[T]) Transaction(ctx context.Context) (QuerySet[T], error) {
ts := NewPostgreSQLFromDB(b.psql.DB())
err := ts.Begin(ctx)
if err != nil {
return nil, err
}
return Q[T](ts), nil
}
func (b *basePsql[T]) U(ctx context.Context, x *T) error {
id := b.findID(x)
if id == nil {
return fmt.Errorf("id not found")
}
qs := b.F("id", id)
return qs.Update(ctx, x)
}