Debian Codegraph @

model_query.go

raw symbols SCIP
1 package dbx
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "reflect"
8 )
9
10 type (
11 // TableModel is the interface that should be implemented by models which have unconventional table names.
12 TableModel interface {
13 TableName() string
14 }
15
16 // ModelQuery represents a query associated with a struct model.
17 ModelQuery struct {
18 db *DB
19 ctx context.Context
20 builder Builder
21 model *structValue
22 exclude []string
23 lastError error
24 }
25 )
26
27 var (
28 MissingPKError = errors.New("missing primary key declaration")
29 CompositePKError = errors.New("composite primary key is not supported")
30 )
31
32 func NewModelQuery(model interface{}, fieldMapFunc FieldMapFunc, db *DB, builder Builder) *ModelQuery {
33 q := &ModelQuery{
34 db: db,
35 ctx: db.ctx,
36 builder: builder,
37 model: newStructValue(model, fieldMapFunc, db.TableMapper),
38 }
39 if q.model == nil {
40 q.lastError = VarTypeError("must be a pointer to a struct representing the model")
41 }
42 return q
43 }
44
45 // Context returns the context associated with the query.
46 func (q *ModelQuery) Context() context.Context {
47 return q.ctx
48 }
49
50 // WithContext associates a context with the query.
51 func (q *ModelQuery) WithContext(ctx context.Context) *ModelQuery {
52 q.ctx = ctx
53 return q
54 }
55
56 // Exclude excludes the specified struct fields from being inserted/updated into the DB table.
57 func (q *ModelQuery) Exclude(attrs ...string) *ModelQuery {
58 q.exclude = attrs
59 return q
60 }
61
62 // Insert inserts a row in the table using the struct model associated with this query.
63 //
64 // By default, it inserts *all* public fields into the table, including those nil or empty ones.
65 // You may pass a list of the fields to this method to indicate that only those fields should be inserted.
66 // You may also call Exclude to exclude some fields from being inserted.
67 //
68 // If a model has an empty primary key, it is considered auto-incremental and the corresponding struct
69 // field will be filled with the generated primary key value after a successful insertion.
70 func (q *ModelQuery) Insert(attrs ...string) error {
71 if q.lastError != nil {
72 return q.lastError
73 }
74 cols := q.model.columns(attrs, q.exclude)
75 pkName := ""
76 for name, value := range q.model.pk() {
77 if isAutoInc(value) {
78 delete(cols, name)
79 pkName = name
80 break
81 }
82 }
83
84 if pkName == "" {
85 _, err := q.builder.Insert(q.model.tableName, Params(cols)).WithContext(q.ctx).Execute()
86 return err
87 }
88
89 // handle auto-incremental PK
90 query := q.builder.Insert(q.model.tableName, Params(cols)).WithContext(q.ctx)
91 pkValue, err := insertAndReturnPK(q.db, query, pkName)
92 if err != nil {
93 return err
94 }
95
96 pkField := indirect(q.model.dbNameMap[pkName].getField(q.model.value))
97 switch pkField.Kind() {
98 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
99 pkField.SetUint(uint64(pkValue))
100 default:
101 pkField.SetInt(pkValue)
102 }
103
104 return nil
105 }
106
107 func insertAndReturnPK(db *DB, query *Query, pkName string) (int64, error) {
108 if db.DriverName() != "postgres" && db.DriverName() != "pgx" {
109 result, err := query.Execute()
110 if err != nil {
111 return 0, err
112 }
113 return result.LastInsertId()
114 }
115
116 // specially handle postgres (lib/pq) as it doesn't support LastInsertId
117 returning := fmt.Sprintf(" RETURNING %s", db.QuoteColumnName(pkName))
118 query.sql += returning
119 query.rawSQL += returning
120 var pkValue int64
121 err := query.Row(&pkValue)
122 return pkValue, err
123 }
124
125 func isAutoInc(value interface{}) bool {
126 v := reflect.ValueOf(value)
127 switch v.Kind() {
128 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
129 return v.Int() == 0
130 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
131 return v.Uint() == 0
132 case reflect.Ptr:
133 return v.IsNil() || isAutoInc(v.Elem())
134 case reflect.Invalid:
135 return true
136 }
137 return false
138 }
139
140 // Update updates a row in the table using the struct model associated with this query.
141 // The row being updated has the same primary key as specified by the model.
142 //
143 // By default, it updates *all* public fields in the table, including those nil or empty ones.
144 // You may pass a list of the fields to this method to indicate that only those fields should be updated.
145 // You may also call Exclude to exclude some fields from being updated.
146 func (q *ModelQuery) Update(attrs ...string) error {
147 if q.lastError != nil {
148 return q.lastError
149 }
150 pk := q.model.pk()
151 if len(pk) == 0 {
152 return MissingPKError
153 }
154
155 cols := q.model.columns(attrs, q.exclude)
156 for name := range pk {
157 delete(cols, name)
158 }
159 _, err := q.builder.Update(q.model.tableName, Params(cols), HashExp(pk)).WithContext(q.ctx).Execute()
160 return err
161 }
162
163 // Delete deletes a row in the table using the primary key specified by the struct model associated with this query.
164 func (q *ModelQuery) Delete() error {
165 if q.lastError != nil {
166 return q.lastError
167 }
168 pk := q.model.pk()
169 if len(pk) == 0 {
170 return MissingPKError
171 }
172 _, err := q.builder.Delete(q.model.tableName, HashExp(pk)).WithContext(q.ctx).Execute()
173 return err
174 }