-
Notifications
You must be signed in to change notification settings - Fork 0
/
consts.go
401 lines (360 loc) · 10 KB
/
consts.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
// Copyright 2020 Author: Ruslan Bikchentaev. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package _go
const (
moduloPgType = "github.com/jackc/pgtype"
moduloGoTools = "github.com/ruslanBik4/gotools"
moduloSql = "database/sql"
)
const (
title = `// Code generated by dbEngine-gen-go from table "%s.%s.%s". DO NOT EDIT.
// Copyright https://github.com/ruslanBik4
package db
import (
"%s"
)
`
colFormat = "\n\t%-21s\t%-13s\t`json:\"%s\"`"
initFormat = "\n\t\t%-21s:\t%s,"
scanFormat = "\n\t\t%s,"
paramsFormat = `
[]any{
%s
},`
caseRefFormat = `
case "%s":
return &r.%s
`
caseColFormat = `
case "%s":
return r.%s
`
formatTable = `// %s implement operations for %[5]s
// DB comment: '%[4]s'
type %[1]s struct {
*psql.Table
Record *%[1]sFields
DoCopyPoll []*%[1]sFields
doCopyPoolCount int
doCopyPoolColumns []string
doCopyValuesCount int
doCopyErr error
lock sync.RWMutex
ticket *time.Ticker
poolDuration time.Duration
}
// New%[1]s create new instance of table object
func New%[1]s(DB *dbEngine.DB) (*%[1]s, error) {
table, ok := DB.Tables["%[3]s"]
if !ok {
return nil, dbEngine.ErrNotFoundTable{Table: "%[3]s"}
}
return &%[1]s{
Table: table.(*psql.Table),
}, nil
}
// New%[1]s create new instance of table object from Connection
// it's necessary if Database create without reading schema of DB
func New%[1]sFromConn(ctx context.Context, conn *psql.Conn) (*%[1]s, error) {
t, err := conn.NewTableWithCheck(ctx, "%[3]s")
if err != nil {
logs.ErrorLog(err, "during NewTableWithCheck")
return nil, err
}
return &%[1]s{
Table: t,
}, nil
}
// implementation pgx.CopyFromSource
// CopyFromSource is the interface used by *Conn.CopyFrom as the source for copy data.
// Next returns true if there is another row and makes the next row data
// available to Values(). When there are no more rows available or an error
// has occurred it returns false.
func (t *%[1]s) Next() bool {
t.doCopyValuesCount++
return t.doCopyValuesCount < len(t.DoCopyPoll)
}
// Values returns the values for the current row.
func (t *%[1]s) Values() ([]any, error) {
res := make([]any, len(t.doCopyPoolColumns))
for i, col := range t.doCopyPoolColumns {
res[i] = t.DoCopyPoll[t.doCopyValuesCount].ColValue(col)
}
return res, nil
}
// Err returns any error that has been encountered by the CopyFromSource. If
// this is not nil *Conn.CopyFrom will abort the copy.
func (t *%[1]s) Err() error {
return t.doCopyErr
}
// InitPoolCopy init environments for CopyFrom operation
// capOfPool define max pool capacity
// d - interval for flash
// columns - names of columns for CopyFrom (all columns of table if it not present)
// chErr - channel for error when CopyFrom return it
// on this case operation will terminated
func (t *%[1]s) InitPoolCopy(ctx context.Context, capOfPool int, chErr *chan error, d time.Duration, columns ...string) {
t.lock.Lock()
defer t.lock.Unlock()
t.DoCopyPoll = make([]*%[1]sFields, 0, capOfPool)
t.doCopyPoolCount = 0
if len(columns) > 0 {
t.doCopyPoolColumns = columns
} else {
t.doCopyPoolColumns = make([]string, len(t.Columns()))
for i, col := range t.Columns() {
t.doCopyPoolColumns[i] = col.Name()
}
}
t.doCopyErr = nil
t.ticket = time.NewTicker(d)
t.poolDuration = d
go func() {
for {
select {
case <-t.ticket.C:
t.lock.Lock()
err := t.doCopy(ctx)
t.lock.Unlock()
if err != nil {
if chErr != nil {
*chErr <- err
}
t.doCopyErr = err
return
}
case <-ctx.Done():
return
}
}
}()
}
// AddToPoolCopy add 'record' into copy pool
func (t *%[1]s) AddToPoolCopy(ctx context.Context, record *%[1]sFields) error {
if t.doCopyErr != nil {
return t.doCopyErr
}
if cap(t.DoCopyPoll) == 0 {
t.InitPoolCopy(ctx, 3, nil, 100 * time.Millisecond)
}
t.lock.Lock()
defer t.lock.Unlock()
t.DoCopyPoll = append(t.DoCopyPoll, record)
t.doCopyPoolCount++
if t.doCopyPoolCount == cap(t.DoCopyPoll) {
err := t.doCopy(ctx)
if err != nil {
return err
}
t.ticket.Reset(t.poolDuration)
}
return nil
}
// FlashPoolAndReset inserted all record from Poll as is
// returns slice of records which were be not inserted
func (t *%[1]s) FlashPoolAndReset(ctx context.Context) ([]*%[1]sFields, error) {
t.ticket.Reset(t.poolDuration)
err := t.doCopy(ctx)
if m, ok := dbEngine.IsErrorDuplicated(err); ok {
logs.ErrorLog(err, m)
return t.InsertPoolAndReset(ctx), err
}
if err != nil {
return nil, err
}
return nil, nil
}
// InsertPoolAndReset inserted all record from Poll as is
// returns slice of records which were be not inserted
func (t *%[1]s) InsertPoolAndReset(ctx context.Context) []*%[1]sFields {
t.lock.Lock()
defer t.lock.Unlock()
columns := t.doCopyPoolColumns
failRecords := make([]*%[1]sFields,0)
allInserted := int64(0)
for _, record := range t.DoCopyPoll {
v := make([]any, len(columns))
for i, name := range columns {
v[i] = record.RefColValue(name)
}
i, err := t.Insert(ctx,
dbEngine.Columns(columns...),
dbEngine.Values(v...),
)
if err != nil {
failRecords = append(failRecords, record)
continue
}
allInserted += i
}
logs.DebugLog("%%d record inserted by InsertPoolAndReset", allInserted)
t.DoCopyPoll = t.DoCopyPoll[:0]
t.doCopyPoolCount = 0
return failRecords
}
// %[1]sFields data object for '%[1]s' columns
type %[1]sFields struct {
// columns of table %s
}`
footer = `
// New%sFields create new instance & fill struct fill for avoid panic
func New%[1]sFields() *%[1]sFields{
return &%[1]sFields{
// init properties %[5]s
}
}
// RefColValue return referral of column
func (r *%[1]sFields) RefColValue(name string) any{
switch name { %s
default:
return nil
}
}
// ColValue return value of column
func (r *%[1]sFields) ColValue(name string) any{
switch name { %[3]s
default:
return nil
}
}
// GetFields implement dbEngine.RowScanner interface
func (r *%[1]sFields) GetFields(columns []dbEngine.Column) []any {
v := make([]any, len(columns))
for i, col := range columns {
v[i] = r.RefColValue( col.Name() )
}
return v
}
// GetValue implement httpgo.RouteDTO interface
func (r *%[1]sFields) GetValue() any {
return r
}
// NewValue implement httpgo.RouteDTO interface
func (r *%[1]sFields) NewValue() any {
return New%[1]sFields()
}
// NewRecord return new row of table
func (t *%[1]s) NewRecord() *%[1]sFields{
t.Record = New%[1]sFields()
return t.Record
}
// GetFields implement dbEngine.RowScanner interface
func (t *%[1]s) GetFields(columns []dbEngine.Column) []any {
if len(columns) == 0 {
columns = t.Columns()
}
return t.NewRecord().GetFields(columns)
}
// SelectSelfScanEach exec request to DB & populate record & call each for each row of query
func (t *%[1]s) SelectSelfScanEach(ctx context.Context, each func(record *%[1]sFields) error, Options ...dbEngine.BuildSqlOptions) error {
return t.SelectAndScanEach(ctx,
func() error {
if each != nil {
return each(t.Record)
}
return nil
}, t, Options ... )
}
// SelectAll run sql according to Options & return slice of record
func (t *%[1]s) SelectAll(ctx context.Context, Options ...dbEngine.BuildSqlOptions) (res []*%[1]sFields, err error) {
err = t.SelectAndScanEach(ctx,
func() error {
res = append(res, t.Record)
return nil
}, t, Options ... )
if err != nil {
logs.ErrorLog(err, "during doCopy")
return nil, err
}
return res, nil
}
// Insert new record into table
func (t *%[1]s) Insert(ctx context.Context, Options ...dbEngine.BuildSqlOptions) (int64, error) {
if len(Options) == 0 {
v := make([]any, 0, len(t.Columns()))
columns := make([]string, 0, len(t.Columns()))
for _, col := range t.Columns() {
if col.AutoIncrement() {
continue
}
columns = append(columns, col.Name())
v = append(v, t.Record.ColValue( col.Name() ) )
}
Options = append(
Options,
dbEngine.Columns(columns...),
dbEngine.Values(v... ),
)
}
return t.Table.Insert(ctx, Options...)
}
// Update record of table according to Options
func (t *%[1]s) Update(ctx context.Context, Options ...dbEngine.BuildSqlOptions) (int64, error) {
if len(Options) == 0 {
v := make([]any, 0, len(t.Columns()))
priV := make([]any, 0)
columns := make([]string, 0, len(t.Columns()))
priColumns := make([]string, 0, len(t.Columns()))
for _, col := range t.Columns() {
if col.Primary() {
priColumns = append( priColumns, col.Name() )
priV = append(priV, t.Record.ColValue( col.Name() ))
continue
}
columns = append( columns, col.Name() )
v = append(v, t.Record.ColValue( col.Name() ) )
}
Options = append(
Options,
dbEngine.Columns(columns...),
dbEngine.WhereForSelect(priColumns...),
dbEngine.Values(append(v, priV...)... ),
)
}
return t.Table.Update(ctx, Options...)
}
// Upsert insert new Record into table according to Options or update if this record exists
func (t *%[1]s) Upsert(ctx context.Context, Options ...dbEngine.BuildSqlOptions) (int64, error) {
if len(Options) == 0 {
v := make([]any, 0, len(t.Columns()))
priV := make([]any, 0)
columns := make([]string, 0, len(t.Columns()))
priColumns := make([]string, 0, len(t.Columns()))
for _, col := range t.Columns() {
if col.Primary() {
priColumns = append( priColumns, col.Name() )
priV = append(priV, t.Record.ColValue( col.Name() ))
}
if col.AutoIncrement() {
continue
}
columns = append( columns, col.Name() )
v = append(v, t.Record.ColValue( col.Name() ) )
}
Options = append(
Options,
dbEngine.Columns(columns...),
dbEngine.WhereForSelect(priColumns...),
dbEngine.Values(v... ),
)
}
return t.Table.Upsert(ctx, Options...)
}
func (t *%[1]s) doCopy(ctx context.Context) error {
if len(t.DoCopyPoll) == 0 {
return nil
}
t.doCopyValuesCount = -1
i, err := t.DoCopy(ctx, t, t.doCopyPoolColumns...)
if err != nil {
logs.ErrorLog(err, "during doCopy")
return err
}
logs.DebugLog("%%d record insert with CopyFrom", i)
t.DoCopyPoll = t.DoCopyPoll[:0]
t.doCopyPoolCount = 0
return nil
}
`
)