@an5/orm 1.0.8 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +174 -175
- package/dist/an5Metadata.js +64 -0
- package/dist/an5Orm.d.ts +92 -3
- package/dist/an5Orm.js +697 -206
- package/dist/config.d.ts +9 -1
- package/dist/config.js +13 -18
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -1
- package/dist/generator/src/api.d.ts +35 -0
- package/dist/generator/src/api.js +58 -0
- package/dist/generator/src/code-generator.d.ts +14 -13
- package/dist/generator/src/code-generator.js +249 -225
- package/dist/generator/src/config.d.ts +162 -0
- package/dist/generator/src/config.js +354 -0
- package/dist/generator/src/dialect.d.ts +88 -0
- package/dist/generator/src/dialect.js +318 -0
- package/dist/generator/src/dotnet-generator.d.ts +21 -11
- package/dist/generator/src/dotnet-generator.js +1053 -546
- package/dist/generator/src/field-types.d.ts +96 -0
- package/dist/generator/src/field-types.js +433 -0
- package/dist/generator/src/golang-generator.d.ts +36 -0
- package/dist/generator/src/golang-generator.js +1229 -0
- package/dist/generator/src/index.d.ts +1 -1
- package/dist/generator/src/index.js +137 -88
- package/dist/generator/src/metadata-generator.d.ts +11 -8
- package/dist/generator/src/metadata-generator.js +105 -90
- package/dist/generator/src/parser.d.ts +37 -11
- package/dist/generator/src/parser.js +208 -206
- package/dist/generator/src/push-apply.d.ts +37 -0
- package/dist/generator/src/push-apply.js +109 -0
- package/dist/generator/src/push-schema.d.ts +93 -0
- package/dist/generator/src/push-schema.js +189 -0
- package/dist/generator/src/python-generator.d.ts +37 -9
- package/dist/generator/src/python-generator.js +428 -105
- package/dist/generator/src/rust-generator.d.ts +38 -0
- package/dist/generator/src/rust-generator.js +971 -0
- package/dist/generator/src/suggest.d.ts +17 -0
- package/dist/generator/src/suggest.js +45 -0
- package/dist/generator/src/type-kinds.d.ts +27 -0
- package/dist/generator/src/type-kinds.js +72 -0
- package/dist/generator/src/types.d.ts +60 -27
- package/dist/generator/src/types.js +41 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +19 -8
- package/dist/logger.js +1 -1
- package/dist/migration-core.d.ts +102 -0
- package/dist/migration-core.js +731 -0
- package/dist/orm.d.ts +147 -0
- package/dist/orm.js +1654 -0
- package/dist/provider-support.d.ts +27 -0
- package/dist/provider-support.js +50 -0
- package/dist/scripts/release-cli.d.ts +2 -2
- package/dist/scripts/release-cli.js +115 -115
- package/dist/sql-utils.d.ts +3 -1
- package/dist/sql-utils.js +94 -24
- package/generator/src/api.ts +45 -0
- package/generator/src/code-generator.ts +259 -230
- package/generator/src/config.ts +496 -0
- package/generator/src/dialect.ts +415 -0
- package/generator/src/dotnet-generator.ts +1071 -544
- package/generator/src/field-types.ts +473 -0
- package/generator/src/golang-generator.ts +1267 -0
- package/generator/src/index.ts +146 -116
- package/generator/src/metadata-generator.ts +116 -101
- package/generator/src/parser.ts +234 -202
- package/generator/src/push-apply.ts +148 -0
- package/generator/src/push-schema.ts +250 -0
- package/generator/src/python-generator.ts +480 -114
- package/generator/src/rust-generator.ts +974 -0
- package/generator/src/suggest.ts +41 -0
- package/generator/src/type-kinds.ts +78 -0
- package/generator/src/types.ts +77 -29
- package/package.json +32 -6
|
@@ -0,0 +1,1229 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.GolangGenerator = void 0;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const types_1 = require("./types");
|
|
10
|
+
const type_kinds_1 = require("./type-kinds");
|
|
11
|
+
class GolangGenerator {
|
|
12
|
+
constructor(outputDir) {
|
|
13
|
+
this.outputDir = outputDir;
|
|
14
|
+
if (!fs_1.default.existsSync(this.outputDir)) {
|
|
15
|
+
fs_1.default.mkdirSync(this.outputDir, { recursive: true });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
generate(models) {
|
|
19
|
+
// Remembered for the type mapping: `TIMESTAMP` is a rowversion on SQL Server and
|
|
20
|
+
// a point in time on every other provider.
|
|
21
|
+
this.provider = models[0]?.provider;
|
|
22
|
+
// 1. Generate per-model files like dotnet (<Model>.go) -
|
|
23
|
+
// entity struct + that model's WhereInput/OrderByInput/Args types.
|
|
24
|
+
// Same Go package, so no re-export shim is needed.
|
|
25
|
+
for (const model of models) {
|
|
26
|
+
this.generateModelFile(model);
|
|
27
|
+
}
|
|
28
|
+
// 2. Generate client.go - ORM DbContext + TableClient with full type-safe API
|
|
29
|
+
this.generateClientGo(models);
|
|
30
|
+
// 3. Generate config.go - connection string helpers
|
|
31
|
+
this.generateConfigGo();
|
|
32
|
+
// 4. Generate metadata.go - model-to-table mapping
|
|
33
|
+
this.generateMetadataGo(models);
|
|
34
|
+
}
|
|
35
|
+
// ─── Type mapping ──────────────────────────────────────────────────────────
|
|
36
|
+
/**
|
|
37
|
+
* The Go type for a field.
|
|
38
|
+
*
|
|
39
|
+
* Driven by the declared type, not the generated TypeScript one: that collapses
|
|
40
|
+
* `INT`, `FLOAT` and `DECIMAL` into `number`, which matched none of the branches
|
|
41
|
+
* below and made every numeric column a `string`.
|
|
42
|
+
*/
|
|
43
|
+
mapGoType(field, isOptional) {
|
|
44
|
+
const kind = (0, type_kinds_1.fieldKind)(field, this.provider);
|
|
45
|
+
let goType;
|
|
46
|
+
switch (kind) {
|
|
47
|
+
case 'int':
|
|
48
|
+
goType = 'int';
|
|
49
|
+
break;
|
|
50
|
+
case 'bigint':
|
|
51
|
+
goType = 'int64';
|
|
52
|
+
break;
|
|
53
|
+
case 'float':
|
|
54
|
+
goType = 'float64';
|
|
55
|
+
break;
|
|
56
|
+
case 'bool':
|
|
57
|
+
goType = 'bool';
|
|
58
|
+
break;
|
|
59
|
+
case 'date':
|
|
60
|
+
goType = 'time.Time';
|
|
61
|
+
break;
|
|
62
|
+
case 'bytes':
|
|
63
|
+
goType = '[]byte';
|
|
64
|
+
break;
|
|
65
|
+
case 'vector':
|
|
66
|
+
goType = '[]float32';
|
|
67
|
+
break;
|
|
68
|
+
// A JSON column holds whatever the row put in it; string keeps any value
|
|
69
|
+
// representable, and json.RawMessage would need the import everywhere.
|
|
70
|
+
case 'json':
|
|
71
|
+
goType = 'string';
|
|
72
|
+
break;
|
|
73
|
+
default:
|
|
74
|
+
goType = 'string';
|
|
75
|
+
break;
|
|
76
|
+
}
|
|
77
|
+
if (isOptional && goType !== '[]byte') {
|
|
78
|
+
goType = '*' + goType;
|
|
79
|
+
}
|
|
80
|
+
return goType;
|
|
81
|
+
}
|
|
82
|
+
// ─── <Model>.go (per-model file, like dotnet `<Model>.cs`) ────────────────
|
|
83
|
+
generateModelFile(model) {
|
|
84
|
+
// Single-model file: entity struct + its WhereInput/OrderByInput/Args
|
|
85
|
+
// types. All files share `package an5client`, so callers keep using
|
|
86
|
+
// `an5client.User` etc. regardless of file layout.
|
|
87
|
+
// NOTE: Go rejects unused imports, so `time` is only imported when a
|
|
88
|
+
// field actually maps to `time.Time`.
|
|
89
|
+
const needsTime = model.fields.some(f => this.mapGoType(f, false).includes('time.Time'));
|
|
90
|
+
let content = `// Code generated by an5ORM. DO NOT EDIT.
|
|
91
|
+
package an5client
|
|
92
|
+
|
|
93
|
+
`;
|
|
94
|
+
if (needsTime) {
|
|
95
|
+
content += `import (
|
|
96
|
+
\t"time"
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
`;
|
|
100
|
+
}
|
|
101
|
+
content += this.generateModelStruct(model);
|
|
102
|
+
content += this.generateModelOrmTypes(model);
|
|
103
|
+
fs_1.default.writeFileSync(path_1.default.join(this.outputDir, `${model.name}.go`), content);
|
|
104
|
+
}
|
|
105
|
+
generateModelStruct(model) {
|
|
106
|
+
let content = '';
|
|
107
|
+
if (model.description) {
|
|
108
|
+
content += `// ${model.name} - ${model.description}\n`;
|
|
109
|
+
}
|
|
110
|
+
content += `type ${model.name} struct {\n`;
|
|
111
|
+
for (const field of model.fields) {
|
|
112
|
+
const goType = this.mapGoType(field, field.isOptional);
|
|
113
|
+
const jsonTag = field.isOptional ? `${this.toCamelCase(field.name)},omitempty` : this.toCamelCase(field.name);
|
|
114
|
+
const dbTag = this.toSnakeCase(field.name);
|
|
115
|
+
content += `\t${this.capitalize(field.name)} ${goType} \`json:"${jsonTag}" db:"${dbTag}"\`\n`;
|
|
116
|
+
}
|
|
117
|
+
if (model.relations.length > 0) {
|
|
118
|
+
content += `\n\t// Relations\n`;
|
|
119
|
+
for (const rel of model.relations) {
|
|
120
|
+
const relType = rel.isArray ? `[]${rel.type}` : `*${rel.type}`;
|
|
121
|
+
content += `\t${this.capitalize(rel.name)} ${relType} \`json:"${this.toCamelCase(rel.name)},omitempty"\`\n`;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
content += `}\n\n`;
|
|
125
|
+
return content;
|
|
126
|
+
}
|
|
127
|
+
// ─── metadata.go ───────────────────────────────────────────────────────────
|
|
128
|
+
generateMetadataGo(models) {
|
|
129
|
+
let content = `// Code generated by an5ORM. DO NOT EDIT.
|
|
130
|
+
package an5client
|
|
131
|
+
|
|
132
|
+
// ModelToTable maps model name variations to fully-qualified SQL table names.
|
|
133
|
+
var ModelToTable = map[string]string{
|
|
134
|
+
`;
|
|
135
|
+
for (const model of models) {
|
|
136
|
+
const fullTable = (0, types_1.bracketedTableName)(model);
|
|
137
|
+
for (const prop of this.getAllPropertyVariations(model.name)) {
|
|
138
|
+
content += `\t"${prop}": "${fullTable}",\n`;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
content += `}\n\n`;
|
|
142
|
+
content += `// ModelPrimaryKeys maps model names to their primary key column name.\nvar ModelPrimaryKeys = map[string]string{\n`;
|
|
143
|
+
for (const model of models) {
|
|
144
|
+
const idField = model.fields.find(f => f.isId) ?? model.fields[0];
|
|
145
|
+
const pkCol = idField ? this.toSnakeCase(idField.name) : 'id';
|
|
146
|
+
for (const prop of this.getAllPropertyVariations(model.name)) {
|
|
147
|
+
content += `\t"${prop}": "${pkCol}",\n`;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
content += `}\n`;
|
|
151
|
+
fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'metadata.go'), content);
|
|
152
|
+
}
|
|
153
|
+
// ─── config.go ─────────────────────────────────────────────────────────────
|
|
154
|
+
generateConfigGo() {
|
|
155
|
+
const content = `// Code generated by an5ORM. DO NOT EDIT.
|
|
156
|
+
package an5client
|
|
157
|
+
|
|
158
|
+
import (
|
|
159
|
+
\t"os"
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
// An5Config holds database configuration options for Golang client.
|
|
163
|
+
type An5Config struct {
|
|
164
|
+
\tConnectionString string
|
|
165
|
+
\tDriverName string
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// GetDefaultConnectionString retrieves DATABASE_URL or fallback string.
|
|
169
|
+
func GetDefaultConnectionString() string {
|
|
170
|
+
\tconnStr := os.Getenv("DATABASE_URL")
|
|
171
|
+
\tif connStr == "" {
|
|
172
|
+
\t\tconnStr = "Server=localhost;Database=master;Trusted_Connection=True;TrustServerCertificate=True;"
|
|
173
|
+
\t}
|
|
174
|
+
\treturn connStr
|
|
175
|
+
}
|
|
176
|
+
`;
|
|
177
|
+
fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'config.go'), content);
|
|
178
|
+
}
|
|
179
|
+
// ─── client.go ─────────────────────────────────────────────────────────────
|
|
180
|
+
generateClientGo(models) {
|
|
181
|
+
let content = this.generateClientHeader(models);
|
|
182
|
+
content += this.generateBaseOrmTypes();
|
|
183
|
+
content += this.generateDbContext(models);
|
|
184
|
+
content += this.generateTableClientStruct();
|
|
185
|
+
content += this.generateQueryAndScan();
|
|
186
|
+
content += this.generateWhereBuilder();
|
|
187
|
+
content += this.generateCrudMethods();
|
|
188
|
+
content += this.generateVectorSearch();
|
|
189
|
+
content += this.generateHelpers();
|
|
190
|
+
// NOTE: per-model ORM types live in each `<Model>.go` file.
|
|
191
|
+
fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'client.go'), content);
|
|
192
|
+
}
|
|
193
|
+
generateClientHeader(models) {
|
|
194
|
+
return `// Code generated by an5ORM. DO NOT EDIT.
|
|
195
|
+
package an5client
|
|
196
|
+
|
|
197
|
+
import (
|
|
198
|
+
\t"context"
|
|
199
|
+
\t"database/sql"
|
|
200
|
+
\t"encoding/json"
|
|
201
|
+
\t"fmt"
|
|
202
|
+
\t"math"
|
|
203
|
+
\t"reflect"
|
|
204
|
+
\t"sort"
|
|
205
|
+
\t"strings"
|
|
206
|
+
\t"time"
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
`;
|
|
210
|
+
}
|
|
211
|
+
// ─── Base ORM types (shared filters, sort order) ───────────────────────────
|
|
212
|
+
generateBaseOrmTypes() {
|
|
213
|
+
return `// SortOrder represents ascending or descending sort direction.
|
|
214
|
+
type SortOrder string
|
|
215
|
+
|
|
216
|
+
const (
|
|
217
|
+
\tSortOrderAsc SortOrder = "ASC"
|
|
218
|
+
\tSortOrderDesc SortOrder = "DESC"
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
// StringFilter provides type-safe string field filtering options.
|
|
222
|
+
type StringFilter struct {
|
|
223
|
+
\tEquals *string
|
|
224
|
+
\tNot *string
|
|
225
|
+
\tIn []string
|
|
226
|
+
\tNotIn []string
|
|
227
|
+
\tContains *string
|
|
228
|
+
\tStartsWith *string
|
|
229
|
+
\tEndsWith *string
|
|
230
|
+
\tGt *string
|
|
231
|
+
\tGte *string
|
|
232
|
+
\tLt *string
|
|
233
|
+
\tLte *string
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// NumberFilter provides type-safe numeric field filtering options.
|
|
237
|
+
type NumberFilter struct {
|
|
238
|
+
\tEquals *float64
|
|
239
|
+
\tNot *float64
|
|
240
|
+
\tIn []float64
|
|
241
|
+
\tNotIn []float64
|
|
242
|
+
\tGt *float64
|
|
243
|
+
\tGte *float64
|
|
244
|
+
\tLt *float64
|
|
245
|
+
\tLte *float64
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// IntFilter provides type-safe integer field filtering options.
|
|
249
|
+
type IntFilter struct {
|
|
250
|
+
\tEquals *int
|
|
251
|
+
\tNot *int
|
|
252
|
+
\tIn []int
|
|
253
|
+
\tNotIn []int
|
|
254
|
+
\tGt *int
|
|
255
|
+
\tGte *int
|
|
256
|
+
\tLt *int
|
|
257
|
+
\tLte *int
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// BoolFilter provides type-safe boolean field filtering options.
|
|
261
|
+
type BoolFilter struct {
|
|
262
|
+
\tEquals *bool
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// DateTimeFilter provides type-safe datetime field filtering options.
|
|
266
|
+
type DateTimeFilter struct {
|
|
267
|
+
\tEquals *time.Time
|
|
268
|
+
\tNot *time.Time
|
|
269
|
+
\tIn []time.Time
|
|
270
|
+
\tNotIn []time.Time
|
|
271
|
+
\tGt *time.Time
|
|
272
|
+
\tGte *time.Time
|
|
273
|
+
\tLt *time.Time
|
|
274
|
+
\tLte *time.Time
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Dialect identifies the database engine in use.
|
|
278
|
+
type Dialect string
|
|
279
|
+
|
|
280
|
+
const (
|
|
281
|
+
\tDialectMssql Dialect = "mssql"
|
|
282
|
+
\tDialectPostgres Dialect = "postgres"
|
|
283
|
+
\tDialectSqlite Dialect = "sqlite"
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
// detectDialect infers dialect from a connection string.
|
|
287
|
+
func detectDialect(connStr string) Dialect {
|
|
288
|
+
\tl := strings.ToLower(strings.TrimSpace(connStr))
|
|
289
|
+
\tif strings.HasPrefix(l, "postgres://") || strings.HasPrefix(l, "postgresql://") || strings.Contains(l, "port=5432") {
|
|
290
|
+
\t\treturn DialectPostgres
|
|
291
|
+
\t}
|
|
292
|
+
\tif strings.HasPrefix(l, "sqlite://") || strings.HasPrefix(l, "sqlite:") || strings.HasPrefix(l, "file:") || strings.HasSuffix(l, ".db") || strings.HasSuffix(l, ".sqlite") || strings.HasSuffix(l, ".sqlite3") || l == ":memory:" {
|
|
293
|
+
\t\treturn DialectSqlite
|
|
294
|
+
\t}
|
|
295
|
+
\treturn DialectMssql
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Pointer helpers
|
|
299
|
+
func StringPtr(s string) *string { return &s }
|
|
300
|
+
func IntPtr(i int) *int { return &i }
|
|
301
|
+
func Int64Ptr(i int64) *int64 { return &i }
|
|
302
|
+
func Float64Ptr(f float64) *float64 { return &f }
|
|
303
|
+
func BoolPtr(b bool) *bool { return &b }
|
|
304
|
+
func SortOrderPtr(s SortOrder) *SortOrder { return &s }
|
|
305
|
+
|
|
306
|
+
`;
|
|
307
|
+
}
|
|
308
|
+
// ─── An5DbContext ──────────────────────────────────────────────────────────
|
|
309
|
+
generateDbContext(models) {
|
|
310
|
+
let content = `// An5DbContext represents the main ORM database context.\ntype An5DbContext struct {\n\tDB *sql.DB\n\tDialect Dialect\n`;
|
|
311
|
+
for (const model of models) {
|
|
312
|
+
const name = this.capitalize(model.name);
|
|
313
|
+
content += `\t${name}s *TableClient[${model.name}]\n`;
|
|
314
|
+
content += `\t${name} *TableClient[${model.name}]\n`;
|
|
315
|
+
}
|
|
316
|
+
content += `}
|
|
317
|
+
|
|
318
|
+
// NewAn5DbContext initializes the ORM context (defaults to MSSQL dialect).
|
|
319
|
+
func NewAn5DbContext(db *sql.DB) *An5DbContext {
|
|
320
|
+
\treturn NewAn5DbContextWithConnStr(db, "")
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// NewAn5DbContextWithConnStr initializes the ORM context with dialect detection.
|
|
324
|
+
func NewAn5DbContextWithConnStr(db *sql.DB, connStr string) *An5DbContext {
|
|
325
|
+
\td := detectDialect(connStr)
|
|
326
|
+
\tctx := &An5DbContext{DB: db, Dialect: d}
|
|
327
|
+
`;
|
|
328
|
+
for (const model of models) {
|
|
329
|
+
const name = this.capitalize(model.name);
|
|
330
|
+
content += `\tclient${name} := NewTableClient[${model.name}](db, "${(0, types_1.dottedTableName)(model)}", d)\n`;
|
|
331
|
+
content += `\tctx.${name}s = client${name}\n`;
|
|
332
|
+
content += `\tctx.${name} = client${name}\n`;
|
|
333
|
+
}
|
|
334
|
+
content += `\treturn ctx\n}\n\n`;
|
|
335
|
+
return content;
|
|
336
|
+
}
|
|
337
|
+
// ─── TableClient struct ────────────────────────────────────────────────────
|
|
338
|
+
generateTableClientStruct() {
|
|
339
|
+
return `// TableClient provides generic type-safe ORM operations for model T.
|
|
340
|
+
type TableClient[T any] struct {
|
|
341
|
+
\tDB *sql.DB
|
|
342
|
+
\tDialect Dialect
|
|
343
|
+
\tTableName string
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// NewTableClient creates a typed table client.
|
|
347
|
+
func NewTableClient[T any](db *sql.DB, tableName string, dialect Dialect) *TableClient[T] {
|
|
348
|
+
\treturn &TableClient[T]{
|
|
349
|
+
\t\tDB: db,
|
|
350
|
+
\t\tDialect: dialect,
|
|
351
|
+
\t\tTableName: tableName,
|
|
352
|
+
\t}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// quoteName quotes a column/identifier for the dialect.
|
|
356
|
+
func (c *TableClient[T]) quoteName(name string) string {
|
|
357
|
+
\tif c.Dialect == DialectPostgres || c.Dialect == DialectSqlite {
|
|
358
|
+
\t\treturn \`"\` + strings.ReplaceAll(name, \`"\`, \`""\`) + \`"\`
|
|
359
|
+
\t}
|
|
360
|
+
\treturn "[" + strings.ReplaceAll(name, "]", "]]") + "]"
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// quoteTable quotes a schema.table name for the dialect.
|
|
364
|
+
func (c *TableClient[T]) quoteTable() string {
|
|
365
|
+
\tparts := strings.Split(c.TableName, ".")
|
|
366
|
+
\tquoted := make([]string, len(parts))
|
|
367
|
+
\tfor i, p := range parts {
|
|
368
|
+
\t\tquoted[i] = c.quoteName(p)
|
|
369
|
+
\t}
|
|
370
|
+
\treturn strings.Join(quoted, ".")
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// ph returns a positional placeholder - ? for MSSQL, $N for Postgres.
|
|
374
|
+
func (c *TableClient[T]) ph(n int) string {
|
|
375
|
+
\tif c.Dialect == DialectPostgres {
|
|
376
|
+
\t\treturn fmt.Sprintf("$%d", n)
|
|
377
|
+
\t}
|
|
378
|
+
\treturn "?"
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
`;
|
|
382
|
+
}
|
|
383
|
+
// ─── queryAndScan ──────────────────────────────────────────────────────────
|
|
384
|
+
generateQueryAndScan() {
|
|
385
|
+
return `// queryAndScan executes a raw SELECT and scans results into []T via db struct tags.
|
|
386
|
+
func (c *TableClient[T]) queryAndScan(ctx context.Context, query string, args ...interface{}) ([]T, error) {
|
|
387
|
+
\trows, err := c.DB.QueryContext(ctx, query, args...)
|
|
388
|
+
\tif err != nil {
|
|
389
|
+
\t\treturn nil, err
|
|
390
|
+
\t}
|
|
391
|
+
\tdefer rows.Close()
|
|
392
|
+
|
|
393
|
+
\tvar results []T
|
|
394
|
+
\tcols, err := rows.Columns()
|
|
395
|
+
\tif err != nil {
|
|
396
|
+
\t\treturn nil, err
|
|
397
|
+
\t}
|
|
398
|
+
|
|
399
|
+
\tfor rows.Next() {
|
|
400
|
+
\t\tvar item T
|
|
401
|
+
\t\tval := reflect.ValueOf(&item).Elem()
|
|
402
|
+
\t\tscanArgs := make([]interface{}, len(cols))
|
|
403
|
+
\t\tfor i, colName := range cols {
|
|
404
|
+
\t\t\tfieldVal := findFieldByDbTag(val, colName)
|
|
405
|
+
\t\t\tif fieldVal.IsValid() && fieldVal.CanSet() {
|
|
406
|
+
\t\t\t\tscanArgs[i] = fieldVal.Addr().Interface()
|
|
407
|
+
\t\t\t} else {
|
|
408
|
+
\t\t\t\tvar unused interface{}
|
|
409
|
+
\t\t\t\tscanArgs[i] = &unused
|
|
410
|
+
\t\t\t}
|
|
411
|
+
\t\t}
|
|
412
|
+
\t\tif err := rows.Scan(scanArgs...); err != nil {
|
|
413
|
+
\t\t\treturn nil, err
|
|
414
|
+
\t\t}
|
|
415
|
+
\t\tresults = append(results, item)
|
|
416
|
+
\t}
|
|
417
|
+
\tif err := rows.Err(); err != nil {
|
|
418
|
+
\t\treturn nil, err
|
|
419
|
+
\t}
|
|
420
|
+
\treturn results, nil
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
`;
|
|
424
|
+
}
|
|
425
|
+
// ─── WHERE builder ─────────────────────────────────────────────────────────
|
|
426
|
+
generateWhereBuilder() {
|
|
427
|
+
return `// whereResult holds the SQL WHERE clause and its bound arguments.
|
|
428
|
+
type whereResult struct {
|
|
429
|
+
\tClause string
|
|
430
|
+
\tArgs []interface{}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// buildStringFilter converts a StringFilter to SQL fragments.
|
|
434
|
+
func buildStringFilter(col string, f *StringFilter, args []interface{}, ph func(int) string) (string, []interface{}) {
|
|
435
|
+
\tif f == nil {
|
|
436
|
+
\t\treturn "", args
|
|
437
|
+
\t}
|
|
438
|
+
\tvar parts []string
|
|
439
|
+
\tif f.Equals != nil {
|
|
440
|
+
\t\targs = append(args, *f.Equals)
|
|
441
|
+
\t\tparts = append(parts, col+" = "+ph(len(args)))
|
|
442
|
+
\t}
|
|
443
|
+
\tif f.Not != nil {
|
|
444
|
+
\t\targs = append(args, *f.Not)
|
|
445
|
+
\t\tparts = append(parts, col+" <> "+ph(len(args)))
|
|
446
|
+
\t}
|
|
447
|
+
\tif f.Contains != nil {
|
|
448
|
+
\t\targs = append(args, "%"+*f.Contains+"%")
|
|
449
|
+
\t\tparts = append(parts, col+" LIKE "+ph(len(args)))
|
|
450
|
+
\t}
|
|
451
|
+
\tif f.StartsWith != nil {
|
|
452
|
+
\t\targs = append(args, *f.StartsWith+"%")
|
|
453
|
+
\t\tparts = append(parts, col+" LIKE "+ph(len(args)))
|
|
454
|
+
\t}
|
|
455
|
+
\tif f.EndsWith != nil {
|
|
456
|
+
\t\targs = append(args, "%"+*f.EndsWith)
|
|
457
|
+
\t\tparts = append(parts, col+" LIKE "+ph(len(args)))
|
|
458
|
+
\t}
|
|
459
|
+
\tif f.Gt != nil {
|
|
460
|
+
\t\targs = append(args, *f.Gt)
|
|
461
|
+
\t\tparts = append(parts, col+" > "+ph(len(args)))
|
|
462
|
+
\t}
|
|
463
|
+
\tif f.Gte != nil {
|
|
464
|
+
\t\targs = append(args, *f.Gte)
|
|
465
|
+
\t\tparts = append(parts, col+" >= "+ph(len(args)))
|
|
466
|
+
\t}
|
|
467
|
+
\tif f.Lt != nil {
|
|
468
|
+
\t\targs = append(args, *f.Lt)
|
|
469
|
+
\t\tparts = append(parts, col+" < "+ph(len(args)))
|
|
470
|
+
\t}
|
|
471
|
+
\tif f.Lte != nil {
|
|
472
|
+
\t\targs = append(args, *f.Lte)
|
|
473
|
+
\t\tparts = append(parts, col+" <= "+ph(len(args)))
|
|
474
|
+
\t}
|
|
475
|
+
\tif len(f.In) > 0 {
|
|
476
|
+
\t\tphs := make([]string, len(f.In))
|
|
477
|
+
\t\tfor i, v := range f.In {
|
|
478
|
+
\t\t\targs = append(args, v)
|
|
479
|
+
\t\t\tphs[i] = ph(len(args))
|
|
480
|
+
\t\t}
|
|
481
|
+
\t\tparts = append(parts, col+" IN ("+strings.Join(phs, ", ")+")")
|
|
482
|
+
\t}
|
|
483
|
+
\treturn strings.Join(parts, " AND "), args
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// buildNumberFilter converts a NumberFilter to SQL fragments.
|
|
487
|
+
func buildNumberFilter(col string, f *NumberFilter, args []interface{}, ph func(int) string) (string, []interface{}) {
|
|
488
|
+
\tif f == nil {
|
|
489
|
+
\t\treturn "", args
|
|
490
|
+
\t}
|
|
491
|
+
\tvar parts []string
|
|
492
|
+
\tif f.Equals != nil { args = append(args, *f.Equals); parts = append(parts, col+" = "+ph(len(args))) }
|
|
493
|
+
\tif f.Not != nil { args = append(args, *f.Not); parts = append(parts, col+" <> "+ph(len(args))) }
|
|
494
|
+
\tif f.Gt != nil { args = append(args, *f.Gt); parts = append(parts, col+" > "+ph(len(args))) }
|
|
495
|
+
\tif f.Gte != nil { args = append(args, *f.Gte); parts = append(parts, col+" >= "+ph(len(args))) }
|
|
496
|
+
\tif f.Lt != nil { args = append(args, *f.Lt); parts = append(parts, col+" < "+ph(len(args))) }
|
|
497
|
+
\tif f.Lte != nil { args = append(args, *f.Lte); parts = append(parts, col+" <= "+ph(len(args))) }
|
|
498
|
+
\tif len(f.In) > 0 {
|
|
499
|
+
\t\tphs := make([]string, len(f.In))
|
|
500
|
+
\t\tfor i, v := range f.In { args = append(args, v); phs[i] = ph(len(args)) }
|
|
501
|
+
\t\tparts = append(parts, col+" IN ("+strings.Join(phs, ", ")+")")
|
|
502
|
+
\t}
|
|
503
|
+
\treturn strings.Join(parts, " AND "), args
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// buildIntFilter converts an IntFilter to SQL fragments.
|
|
507
|
+
func buildIntFilter(col string, f *IntFilter, args []interface{}, ph func(int) string) (string, []interface{}) {
|
|
508
|
+
\tif f == nil {
|
|
509
|
+
\t\treturn "", args
|
|
510
|
+
\t}
|
|
511
|
+
\tvar parts []string
|
|
512
|
+
\tif f.Equals != nil { args = append(args, *f.Equals); parts = append(parts, col+" = "+ph(len(args))) }
|
|
513
|
+
\tif f.Not != nil { args = append(args, *f.Not); parts = append(parts, col+" <> "+ph(len(args))) }
|
|
514
|
+
\tif f.Gt != nil { args = append(args, *f.Gt); parts = append(parts, col+" > "+ph(len(args))) }
|
|
515
|
+
\tif f.Gte != nil { args = append(args, *f.Gte); parts = append(parts, col+" >= "+ph(len(args))) }
|
|
516
|
+
\tif f.Lt != nil { args = append(args, *f.Lt); parts = append(parts, col+" < "+ph(len(args))) }
|
|
517
|
+
\tif f.Lte != nil { args = append(args, *f.Lte); parts = append(parts, col+" <= "+ph(len(args))) }
|
|
518
|
+
\tif len(f.In) > 0 {
|
|
519
|
+
\t\tphs := make([]string, len(f.In))
|
|
520
|
+
\t\tfor i, v := range f.In { args = append(args, v); phs[i] = ph(len(args)) }
|
|
521
|
+
\t\tparts = append(parts, col+" IN ("+strings.Join(phs, ", ")+")")
|
|
522
|
+
\t}
|
|
523
|
+
\treturn strings.Join(parts, " AND "), args
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// buildDateTimeFilter converts a DateTimeFilter to SQL fragments.
|
|
527
|
+
func buildDateTimeFilter(col string, f *DateTimeFilter, args []interface{}, ph func(int) string) (string, []interface{}) {
|
|
528
|
+
\tif f == nil {
|
|
529
|
+
\t\treturn "", args
|
|
530
|
+
\t}
|
|
531
|
+
\tvar parts []string
|
|
532
|
+
\tif f.Equals != nil { args = append(args, *f.Equals); parts = append(parts, col+" = "+ph(len(args))) }
|
|
533
|
+
\tif f.Not != nil { args = append(args, *f.Not); parts = append(parts, col+" <> "+ph(len(args))) }
|
|
534
|
+
\tif f.Gt != nil { args = append(args, *f.Gt); parts = append(parts, col+" > "+ph(len(args))) }
|
|
535
|
+
\tif f.Gte != nil { args = append(args, *f.Gte); parts = append(parts, col+" >= "+ph(len(args))) }
|
|
536
|
+
\tif f.Lt != nil { args = append(args, *f.Lt); parts = append(parts, col+" < "+ph(len(args))) }
|
|
537
|
+
\tif f.Lte != nil { args = append(args, *f.Lte); parts = append(parts, col+" <= "+ph(len(args))) }
|
|
538
|
+
\treturn strings.Join(parts, " AND "), args
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
`;
|
|
542
|
+
}
|
|
543
|
+
// ─── CRUD methods ──────────────────────────────────────────────────────────
|
|
544
|
+
generateCrudMethods() {
|
|
545
|
+
return `// FindMany returns multiple records. Use model-specific FindManyArgs for type-safe filtering.
|
|
546
|
+
// Example: db.User.FindMany(ctx, &UserFindManyArgs{ Where: &UserWhereInput{ Name: &StringFilter{Contains: "Jo"} } })
|
|
547
|
+
func (c *TableClient[T]) FindMany(ctx context.Context, args interface{}) ([]T, error) {
|
|
548
|
+
clause, orderBy, take, skip, selectCols, queryArgs := c.parseArgs(args)
|
|
549
|
+
table := c.quoteTable()
|
|
550
|
+
var query string
|
|
551
|
+
if len(selectCols) > 0 {
|
|
552
|
+
quoted := make([]string, len(selectCols))
|
|
553
|
+
for i, col := range selectCols {
|
|
554
|
+
quoted[i] = c.quoteName(col)
|
|
555
|
+
}
|
|
556
|
+
query = "SELECT " + strings.Join(quoted, ", ") + " FROM " + table
|
|
557
|
+
} else {
|
|
558
|
+
query = "SELECT * FROM " + table
|
|
559
|
+
}
|
|
560
|
+
if clause != "" {
|
|
561
|
+
query += " WHERE " + clause
|
|
562
|
+
}
|
|
563
|
+
if orderBy != "" {
|
|
564
|
+
query += " " + orderBy
|
|
565
|
+
}
|
|
566
|
+
if c.Dialect == DialectPostgres || c.Dialect == DialectSqlite {
|
|
567
|
+
if take > 0 {
|
|
568
|
+
query += fmt.Sprintf(" LIMIT %d", take)
|
|
569
|
+
}
|
|
570
|
+
if skip > 0 {
|
|
571
|
+
query += fmt.Sprintf(" OFFSET %d", skip)
|
|
572
|
+
}
|
|
573
|
+
} else {
|
|
574
|
+
if skip > 0 {
|
|
575
|
+
query += fmt.Sprintf(" OFFSET %d ROWS", skip)
|
|
576
|
+
if take > 0 {
|
|
577
|
+
query += fmt.Sprintf(" FETCH NEXT %d ROWS ONLY", take)
|
|
578
|
+
}
|
|
579
|
+
} else if take > 0 {
|
|
580
|
+
// rewrite SELECT to SELECT TOP
|
|
581
|
+
query = strings.Replace(query, "SELECT *", fmt.Sprintf("SELECT TOP (%d) *", take), 1)
|
|
582
|
+
query = strings.Replace(query, "SELECT "+strings.Join(func() []string {
|
|
583
|
+
if len(selectCols) == 0 { return []string{"*"} }
|
|
584
|
+
return selectCols
|
|
585
|
+
}(), ", "), fmt.Sprintf("SELECT TOP (%d) *", take), 1)
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
return c.queryAndScan(ctx, query, queryArgs...)
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// FindFirst returns first record matching criteria.
|
|
592
|
+
func (c *TableClient[T]) FindFirst(ctx context.Context, args interface{}) (*T, error) {
|
|
593
|
+
rows, err := c.FindMany(ctx, args)
|
|
594
|
+
if err != nil {
|
|
595
|
+
return nil, err
|
|
596
|
+
}
|
|
597
|
+
if len(rows) == 0 {
|
|
598
|
+
return nil, nil
|
|
599
|
+
}
|
|
600
|
+
return &rows[0], nil
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// FindUnique fetches a single record by primary key.
|
|
604
|
+
// The where input should uniquely identify one record.
|
|
605
|
+
func (c *TableClient[T]) FindUnique(ctx context.Context, args interface{}) (*T, error) {
|
|
606
|
+
\treturn c.FindFirst(ctx, args)
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// Count returns total records matching criteria.
|
|
610
|
+
func (c *TableClient[T]) Count(ctx context.Context, args interface{}) (int64, error) {
|
|
611
|
+
\tclause, _, _, _, _, queryArgs := c.parseArgs(args)
|
|
612
|
+
\tquery := fmt.Sprintf("SELECT COUNT(*) FROM %s", c.quoteTable())
|
|
613
|
+
\tif clause != "" {
|
|
614
|
+
\t\tquery += " WHERE " + clause
|
|
615
|
+
\t}
|
|
616
|
+
\tvar cnt int64
|
|
617
|
+
\terr := c.DB.QueryRowContext(ctx, query, queryArgs...).Scan(&cnt)
|
|
618
|
+
\treturn cnt, err
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// Create inserts a new record and returns it.
|
|
622
|
+
func (c *TableClient[T]) Create(ctx context.Context, entity *T) (*T, error) {
|
|
623
|
+
\tval := reflect.ValueOf(entity).Elem()
|
|
624
|
+
\ttyp := val.Type()
|
|
625
|
+
|
|
626
|
+
\tvar cols []string
|
|
627
|
+
\tvar phs []string
|
|
628
|
+
\tvar args []interface{}
|
|
629
|
+
|
|
630
|
+
\tfor i := 0; i < typ.NumField(); i++ {
|
|
631
|
+
\t\tfield := typ.Field(i)
|
|
632
|
+
\t\tdbTag := field.Tag.Get("db")
|
|
633
|
+
\t\tif dbTag == "" || dbTag == "-" {
|
|
634
|
+
\t\t\tcontinue
|
|
635
|
+
\t\t}
|
|
636
|
+
\t\tfieldVal := val.Field(i)
|
|
637
|
+
\t\tif !fieldVal.IsZero() {
|
|
638
|
+
\t\t\tcols = append(cols, c.quoteName(dbTag))
|
|
639
|
+
\t\t\targs = append(args, fieldVal.Interface())
|
|
640
|
+
\t\t\tphs = append(phs, c.ph(len(args)))
|
|
641
|
+
\t\t}
|
|
642
|
+
\t}
|
|
643
|
+
|
|
644
|
+
\tquery := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", c.quoteTable(), strings.Join(cols, ", "), strings.Join(phs, ", "))
|
|
645
|
+
\t_, err := c.DB.ExecContext(ctx, query, args...)
|
|
646
|
+
\tif err != nil {
|
|
647
|
+
\t\treturn nil, err
|
|
648
|
+
\t}
|
|
649
|
+
\treturn entity, nil
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// CreateMany inserts multiple records and returns count.
|
|
653
|
+
func (c *TableClient[T]) CreateMany(ctx context.Context, entities []*T) (int64, error) {
|
|
654
|
+
\tvar count int64
|
|
655
|
+
\tfor _, e := range entities {
|
|
656
|
+
\t\t_, err := c.Create(ctx, e)
|
|
657
|
+
\t\tif err != nil {
|
|
658
|
+
\t\t\treturn count, err
|
|
659
|
+
\t\t}
|
|
660
|
+
\t\tcount++
|
|
661
|
+
\t}
|
|
662
|
+
\treturn count, nil
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// Update updates an existing record identified by its primary key field (isId tag or "id" column).
|
|
666
|
+
func (c *TableClient[T]) Update(ctx context.Context, entity *T) (*T, error) {
|
|
667
|
+
\tval := reflect.ValueOf(entity).Elem()
|
|
668
|
+
\ttyp := val.Type()
|
|
669
|
+
|
|
670
|
+
\tvar sets []string
|
|
671
|
+
\tvar args []interface{}
|
|
672
|
+
\tvar idVal interface{}
|
|
673
|
+
\tvar idCol string
|
|
674
|
+
|
|
675
|
+
\tfor i := 0; i < typ.NumField(); i++ {
|
|
676
|
+
\t\tfield := typ.Field(i)
|
|
677
|
+
\t\tdbTag := field.Tag.Get("db")
|
|
678
|
+
\t\tif dbTag == "" || dbTag == "-" {
|
|
679
|
+
\t\t\tcontinue
|
|
680
|
+
\t\t}
|
|
681
|
+
\t\tfieldVal := val.Field(i)
|
|
682
|
+
\t\tif strings.EqualFold(dbTag, "id") || field.Tag.Get("pk") == "true" {
|
|
683
|
+
\t\t\tidVal = fieldVal.Interface()
|
|
684
|
+
\t\t\tidCol = dbTag
|
|
685
|
+
\t\t} else if !fieldVal.IsZero() {
|
|
686
|
+
\t\t\targs = append(args, fieldVal.Interface())
|
|
687
|
+
\t\t\tsets = append(sets, c.quoteName(dbTag)+" = "+c.ph(len(args)))
|
|
688
|
+
\t\t}
|
|
689
|
+
\t}
|
|
690
|
+
|
|
691
|
+
\tif idVal == nil {
|
|
692
|
+
\t\treturn nil, fmt.Errorf("cannot update entity without primary key")
|
|
693
|
+
\t}
|
|
694
|
+
|
|
695
|
+
\targs = append(args, idVal)
|
|
696
|
+
\tquery := fmt.Sprintf("UPDATE %s SET %s WHERE %s = %s",
|
|
697
|
+
\t\tc.quoteTable(), strings.Join(sets, ", "), c.quoteName(idCol), c.ph(len(args)))
|
|
698
|
+
\t_, err := c.DB.ExecContext(ctx, query, args...)
|
|
699
|
+
\tif err != nil {
|
|
700
|
+
\t\treturn nil, err
|
|
701
|
+
\t}
|
|
702
|
+
\treturn entity, nil
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// UpdateMany updates multiple records matching where criteria with given data fields.
|
|
706
|
+
func (c *TableClient[T]) UpdateMany(ctx context.Context, whereArgs interface{}, data map[string]interface{}) (int64, error) {
|
|
707
|
+
\tvar sets []string
|
|
708
|
+
\tvar execArgs []interface{}
|
|
709
|
+
|
|
710
|
+
\tfor col, v := range data {
|
|
711
|
+
\t\texecArgs = append(execArgs, v)
|
|
712
|
+
\t\tsets = append(sets, c.quoteName(col)+" = "+c.ph(len(execArgs)))
|
|
713
|
+
\t}
|
|
714
|
+
|
|
715
|
+
\tclause, _, _, _, _, whereQueryArgs := c.parseArgs(whereArgs)
|
|
716
|
+
\texecArgs = append(execArgs, whereQueryArgs...)
|
|
717
|
+
\tquery := fmt.Sprintf("UPDATE %s SET %s", c.quoteTable(), strings.Join(sets, ", "))
|
|
718
|
+
\tif clause != "" {
|
|
719
|
+
\t\tquery += " WHERE " + clause
|
|
720
|
+
\t}
|
|
721
|
+
|
|
722
|
+
\tres, err := c.DB.ExecContext(ctx, query, execArgs...)
|
|
723
|
+
\tif err != nil {
|
|
724
|
+
\t\treturn 0, err
|
|
725
|
+
\t}
|
|
726
|
+
\treturn res.RowsAffected()
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// Delete removes a record by primary key value.
|
|
730
|
+
func (c *TableClient[T]) Delete(ctx context.Context, id interface{}) (bool, error) {
|
|
731
|
+
\tquery := fmt.Sprintf("DELETE FROM %s WHERE %s = %s", c.quoteTable(), c.quoteName("id"), c.ph(1))
|
|
732
|
+
\tres, err := c.DB.ExecContext(ctx, query, id)
|
|
733
|
+
\tif err != nil {
|
|
734
|
+
\t\treturn false, err
|
|
735
|
+
\t}
|
|
736
|
+
\tn, _ := res.RowsAffected()
|
|
737
|
+
\treturn n > 0, nil
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// DeleteMany removes records matching where criteria.
|
|
741
|
+
func (c *TableClient[T]) DeleteMany(ctx context.Context, args interface{}) (int64, error) {
|
|
742
|
+
\tclause, _, _, _, _, queryArgs := c.parseArgs(args)
|
|
743
|
+
\tquery := fmt.Sprintf("DELETE FROM %s", c.quoteTable())
|
|
744
|
+
\tif clause != "" {
|
|
745
|
+
\t\tquery += " WHERE " + clause
|
|
746
|
+
\t}
|
|
747
|
+
\tres, err := c.DB.ExecContext(ctx, query, queryArgs...)
|
|
748
|
+
\tif err != nil {
|
|
749
|
+
\t\treturn 0, err
|
|
750
|
+
\t}
|
|
751
|
+
\treturn res.RowsAffected()
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// Upsert creates or updates entity based on its primary key.
|
|
755
|
+
func (c *TableClient[T]) Upsert(ctx context.Context, entity *T) (*T, error) {
|
|
756
|
+
\tval := reflect.ValueOf(entity).Elem()
|
|
757
|
+
\tidField := findFieldByDbTag(val, "id")
|
|
758
|
+
\tif idField.IsValid() && !idField.IsZero() {
|
|
759
|
+
\t\texisting, err := c.FindUnique(ctx, nil)
|
|
760
|
+
\t\tif err == nil && existing != nil {
|
|
761
|
+
\t\t\treturn c.Update(ctx, entity)
|
|
762
|
+
\t\t}
|
|
763
|
+
\t}
|
|
764
|
+
\treturn c.Create(ctx, entity)
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// QueryRaw executes a raw SQL SELECT and returns rows as typed slice.
|
|
768
|
+
func (c *TableClient[T]) QueryRaw(ctx context.Context, query string, args ...interface{}) ([]T, error) {
|
|
769
|
+
\treturn c.queryAndScan(ctx, query, args...)
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// ExecuteRaw executes a non-SELECT raw SQL and returns affected rows count.
|
|
773
|
+
func (c *TableClient[T]) ExecuteRaw(ctx context.Context, query string, args ...interface{}) (int64, error) {
|
|
774
|
+
\tres, err := c.DB.ExecContext(ctx, query, args...)
|
|
775
|
+
\tif err != nil {
|
|
776
|
+
\t\treturn 0, err
|
|
777
|
+
\t}
|
|
778
|
+
\treturn res.RowsAffected()
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// Transaction executes fn within a database transaction, rolling back on error.
|
|
782
|
+
func (c *TableClient[T]) Transaction(ctx context.Context, fn func(tx *sql.Tx) error) error {
|
|
783
|
+
\ttx, err := c.DB.BeginTx(ctx, nil)
|
|
784
|
+
\tif err != nil {
|
|
785
|
+
\t\treturn err
|
|
786
|
+
\t}
|
|
787
|
+
\tdefer func() {
|
|
788
|
+
\t\tif p := recover(); p != nil {
|
|
789
|
+
\t\t\t_ = tx.Rollback()
|
|
790
|
+
\t\t\tpanic(p)
|
|
791
|
+
\t\t}
|
|
792
|
+
\t}()
|
|
793
|
+
\tif err := fn(tx); err != nil {
|
|
794
|
+
\t\t_ = tx.Rollback()
|
|
795
|
+
\t\treturn err
|
|
796
|
+
\t}
|
|
797
|
+
\treturn tx.Commit()
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// parseArgs is the generic where/orderBy/take/skip extractor.
|
|
801
|
+
// It uses reflection to read WhereClause, OrderBy, Take, Skip, Select from any args struct.
|
|
802
|
+
func (c *TableClient[T]) parseArgs(args interface{}) (whereClause string, orderBy string, take int, skip int, selectCols []string, queryArgs []interface{}) {
|
|
803
|
+
\tif args == nil {
|
|
804
|
+
\t\treturn
|
|
805
|
+
\t}
|
|
806
|
+
\tv := reflect.ValueOf(args)
|
|
807
|
+
\tif v.Kind() == reflect.Ptr {
|
|
808
|
+
\t\tif v.IsNil() {
|
|
809
|
+
\t\t\treturn
|
|
810
|
+
\t\t}
|
|
811
|
+
\t\tv = v.Elem()
|
|
812
|
+
\t}
|
|
813
|
+
\tif v.Kind() != reflect.Struct {
|
|
814
|
+
\t\treturn
|
|
815
|
+
\t}
|
|
816
|
+
|
|
817
|
+
\t// Where
|
|
818
|
+
\twhereField := v.FieldByName("Where")
|
|
819
|
+
\tif whereField.IsValid() && !whereField.IsNil() {
|
|
820
|
+
\t\t// where is a pointer to a model-specific WhereInput struct
|
|
821
|
+
\t\t// Delegate to buildWhereFromStruct
|
|
822
|
+
\t\twc, wa := c.buildWhereFromStruct(whereField.Elem(), 1)
|
|
823
|
+
\t\twhereClause = wc
|
|
824
|
+
\t\tqueryArgs = wa
|
|
825
|
+
\t}
|
|
826
|
+
|
|
827
|
+
\t// OrderBy
|
|
828
|
+
\torderByField := v.FieldByName("OrderBy")
|
|
829
|
+
\tif orderByField.IsValid() && !orderByField.IsNil() {
|
|
830
|
+
\t\tobv := orderByField.Elem()
|
|
831
|
+
\t\ttyp := obv.Type()
|
|
832
|
+
\t\tvar parts []string
|
|
833
|
+
\t\tfor i := 0; i < obv.NumField(); i++ {
|
|
834
|
+
\t\t\tfv := obv.Field(i)
|
|
835
|
+
\t\t\tif fv.IsNil() {
|
|
836
|
+
\t\t\t\tcontinue
|
|
837
|
+
\t\t\t}
|
|
838
|
+
\t\t\tcol := c.quoteName(c.toSnakeCase(typ.Field(i).Name))
|
|
839
|
+
\t\t\tdirection := strings.ToUpper(fv.Elem().String())
|
|
840
|
+
\t\t\tif direction != "DESC" {
|
|
841
|
+
\t\t\t\tdirection = "ASC"
|
|
842
|
+
\t\t\t}
|
|
843
|
+
\t\t\tparts = append(parts, col+" "+direction)
|
|
844
|
+
\t\t}
|
|
845
|
+
\t\tif len(parts) > 0 {
|
|
846
|
+
\t\t\torderBy = "ORDER BY " + strings.Join(parts, ", ")
|
|
847
|
+
\t\t}
|
|
848
|
+
\t}
|
|
849
|
+
|
|
850
|
+
\t// Take
|
|
851
|
+
\ttakeField := v.FieldByName("Take")
|
|
852
|
+
\tif takeField.IsValid() && !takeField.IsNil() {
|
|
853
|
+
\t\ttake = int(takeField.Elem().Int())
|
|
854
|
+
\t}
|
|
855
|
+
|
|
856
|
+
\t// Skip
|
|
857
|
+
\tskipField := v.FieldByName("Skip")
|
|
858
|
+
\tif skipField.IsValid() && !skipField.IsNil() {
|
|
859
|
+
\t\tskip = int(skipField.Elem().Int())
|
|
860
|
+
\t}
|
|
861
|
+
|
|
862
|
+
\t// Select
|
|
863
|
+
\tselectField := v.FieldByName("Select")
|
|
864
|
+
\tif selectField.IsValid() && selectField.Kind() == reflect.Slice && !selectField.IsNil() {
|
|
865
|
+
\t\tfor i := 0; i < selectField.Len(); i++ {
|
|
866
|
+
\t\t\tselectCols = append(selectCols, selectField.Index(i).String())
|
|
867
|
+
\t\t}
|
|
868
|
+
\t}
|
|
869
|
+
|
|
870
|
+
\treturn
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
// buildWhereFromStruct converts a WhereInput struct to SQL clause + args.
|
|
874
|
+
// It processes exported pointer fields using their type to detect StringFilter, NumberFilter, etc.
|
|
875
|
+
func (c *TableClient[T]) buildWhereFromStruct(v reflect.Value, argOffset int) (string, []interface{}) {
|
|
876
|
+
\ttyp := v.Type()
|
|
877
|
+
\tvar parts []string
|
|
878
|
+
\tvar args []interface{}
|
|
879
|
+
|
|
880
|
+
\tpHFunc := func(n int) string { return c.ph(n) }
|
|
881
|
+
|
|
882
|
+
\tfor i := 0; i < v.NumField(); i++ {
|
|
883
|
+
\t\tfield := typ.Field(i)
|
|
884
|
+
\t\tfv := v.Field(i)
|
|
885
|
+
\t\tname := field.Name
|
|
886
|
+
|
|
887
|
+
\t\t// AND / OR / NOT handling
|
|
888
|
+
\t\tif name == "AND" && fv.Kind() == reflect.Slice && !fv.IsNil() {
|
|
889
|
+
\t\t\tvar subParts []string
|
|
890
|
+
\t\t\tfor j := 0; j < fv.Len(); j++ {
|
|
891
|
+
\t\t\t\tsub, subArgs := c.buildWhereFromStruct(fv.Index(j), argOffset+len(args))
|
|
892
|
+
\t\t\t\tif sub != "" { subParts = append(subParts, sub); args = append(args, subArgs...) }
|
|
893
|
+
\t\t\t}
|
|
894
|
+
\t\t\tif len(subParts) > 0 { parts = append(parts, "("+strings.Join(subParts, " AND ")+")") }
|
|
895
|
+
\t\t\tcontinue
|
|
896
|
+
\t\t}
|
|
897
|
+
\t\tif name == "OR" && fv.Kind() == reflect.Slice && !fv.IsNil() {
|
|
898
|
+
\t\t\tvar subParts []string
|
|
899
|
+
\t\t\tfor j := 0; j < fv.Len(); j++ {
|
|
900
|
+
\t\t\t\tsub, subArgs := c.buildWhereFromStruct(fv.Index(j), argOffset+len(args))
|
|
901
|
+
\t\t\t\tif sub != "" { subParts = append(subParts, sub); args = append(args, subArgs...) }
|
|
902
|
+
\t\t\t}
|
|
903
|
+
\t\t\tif len(subParts) > 0 { parts = append(parts, "("+strings.Join(subParts, " OR ")+")") }
|
|
904
|
+
\t\t\tcontinue
|
|
905
|
+
\t\t}
|
|
906
|
+
\t\tif name == "NOT" && fv.Kind() == reflect.Ptr && !fv.IsNil() {
|
|
907
|
+
\t\t\tsub, subArgs := c.buildWhereFromStruct(fv.Elem(), argOffset+len(args))
|
|
908
|
+
\t\t\tif sub != "" { parts = append(parts, "NOT ("+sub+")"); args = append(args, subArgs...) }
|
|
909
|
+
\t\t\tcontinue
|
|
910
|
+
\t\t}
|
|
911
|
+
|
|
912
|
+
\t\tif fv.Kind() != reflect.Ptr || fv.IsNil() {
|
|
913
|
+
\t\t\tcontinue
|
|
914
|
+
\t\t}
|
|
915
|
+
|
|
916
|
+
\t\tcol := c.quoteName(c.toSnakeCase(name))
|
|
917
|
+
\t\telem := fv.Elem()
|
|
918
|
+
\t\ttypeName := field.Type.Elem().Name()
|
|
919
|
+
|
|
920
|
+
\t\tswitch typeName {
|
|
921
|
+
\t\tcase "StringFilter":
|
|
922
|
+
\t\t\tfilter := elem.Interface().(StringFilter)\n\t\t\tclause, newArgs := buildStringFilter(col, &filter, args, pHFunc)\n\t\t\tif clause != "" { parts = append(parts, clause) }\n\t\t\targs = newArgs
|
|
923
|
+
\t\tcase "NumberFilter":
|
|
924
|
+
\t\t\tfilter := elem.Interface().(NumberFilter)\n\t\t\tclause, newArgs := buildNumberFilter(col, &filter, args, pHFunc)\n\t\t\tif clause != "" { parts = append(parts, clause) }\n\t\t\targs = newArgs
|
|
925
|
+
\t\tcase "IntFilter":
|
|
926
|
+
\t\t\tfilter := elem.Interface().(IntFilter)\n\t\t\tclause, newArgs := buildIntFilter(col, &filter, args, pHFunc)\n\t\t\tif clause != "" { parts = append(parts, clause) }\n\t\t\targs = newArgs
|
|
927
|
+
\t\tcase "DateTimeFilter":
|
|
928
|
+
\t\t\tfilter := elem.Interface().(DateTimeFilter)\n\t\t\tclause, newArgs := buildDateTimeFilter(col, &filter, args, pHFunc)\n\t\t\tif clause != "" { parts = append(parts, clause) }\n\t\t\targs = newArgs
|
|
929
|
+
\t\tcase "bool":
|
|
930
|
+
\t\t\targs = append(args, elem.Bool())
|
|
931
|
+
\t\t\tparts = append(parts, col+" = "+c.ph(argOffset+len(args)))
|
|
932
|
+
\t\tcase "string":
|
|
933
|
+
\t\t\targs = append(args, elem.String())
|
|
934
|
+
\t\t\tparts = append(parts, col+" = "+c.ph(argOffset+len(args)))
|
|
935
|
+
\t\tcase "int", "int64":
|
|
936
|
+
\t\t\targs = append(args, elem.Int())
|
|
937
|
+
\t\t\tparts = append(parts, col+" = "+c.ph(argOffset+len(args)))
|
|
938
|
+
\t\tcase "float64":
|
|
939
|
+
\t\t\targs = append(args, elem.Float())
|
|
940
|
+
\t\t\tparts = append(parts, col+" = "+c.ph(argOffset+len(args)))
|
|
941
|
+
\t\t}
|
|
942
|
+
\t}
|
|
943
|
+
|
|
944
|
+
\treturn strings.Join(parts, " AND "), args
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
`;
|
|
948
|
+
}
|
|
949
|
+
// ─── VectorSearch ──────────────────────────────────────────────────────────
|
|
950
|
+
generateVectorSearch() {
|
|
951
|
+
return `// VectorSearchOptions contains options for vector similarity queries.
|
|
952
|
+
type VectorSearchOptions struct {
|
|
953
|
+
\tTake int
|
|
954
|
+
\tWhere interface{}
|
|
955
|
+
\tVectorField string
|
|
956
|
+
\tDistanceMetric string // "cosine" | "euclidean" | "dot"
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// VectorSearch performs native SQL vector similarity search with in-memory fallback.
|
|
960
|
+
// Primary: SQL Server VECTOR_DISTANCE (MSSQL) or pgvector operators (Postgres).
|
|
961
|
+
// Fallback: in-memory cosine/euclidean/dot similarity if DB lacks native extensions.
|
|
962
|
+
func (c *TableClient[T]) VectorSearch(ctx context.Context, vector []float64, opts ...VectorSearchOptions) ([]T, error) {
|
|
963
|
+
\ttake := 10
|
|
964
|
+
\tvectorField := "embedding"
|
|
965
|
+
\tdistanceMetric := "cosine"
|
|
966
|
+
\tvar whereArgs interface{}
|
|
967
|
+
|
|
968
|
+
\tif len(opts) > 0 {
|
|
969
|
+
\t\tif opts[0].Take > 0 { take = opts[0].Take }
|
|
970
|
+
\t\tif opts[0].VectorField != "" { vectorField = opts[0].VectorField }
|
|
971
|
+
\t\tif opts[0].DistanceMetric != "" { distanceMetric = opts[0].DistanceMetric }
|
|
972
|
+
\t\twhereArgs = opts[0].Where
|
|
973
|
+
\t}
|
|
974
|
+
|
|
975
|
+
\twhereCl, _, _, _, _, whereQueryArgs := c.parseArgs(whereArgs)
|
|
976
|
+
\tdim := len(vector)
|
|
977
|
+
\tvecBytes, _ := json.Marshal(vector)
|
|
978
|
+
\tvecStr := string(vecBytes)
|
|
979
|
+
|
|
980
|
+
\t// 1. Primary path: dialect-aware native SQL vector query
|
|
981
|
+
\tvar sqlQuery string
|
|
982
|
+
\tqueryArgs := append([]interface{}{vecStr}, whereQueryArgs...)
|
|
983
|
+
\tif c.Dialect == DialectPostgres {
|
|
984
|
+
\t\top := "<=>"
|
|
985
|
+
\t\tif strings.EqualFold(distanceMetric, "euclidean") { op = "<->" }
|
|
986
|
+
\t\tif strings.EqualFold(distanceMetric, "dot") { op = "<#>" }
|
|
987
|
+
\t\tvcol := c.quoteName(vectorField)
|
|
988
|
+
\t\tsqlQuery = fmt.Sprintf("SELECT *, (%s %s $1::vector) AS distance FROM %s", vcol, op, c.quoteTable())
|
|
989
|
+
\t\tif whereCl != "" {
|
|
990
|
+
\t\t\tsqlQuery += fmt.Sprintf(" WHERE %s IS NOT NULL AND (%s)", vcol, whereCl)
|
|
991
|
+
\t\t} else {
|
|
992
|
+
\t\t\tsqlQuery += fmt.Sprintf(" WHERE %s IS NOT NULL", vcol)
|
|
993
|
+
\t\t}
|
|
994
|
+
\t\tsqlQuery += fmt.Sprintf(" ORDER BY distance ASC LIMIT %d", take)
|
|
995
|
+
\t} else {
|
|
996
|
+
\t\tvcol := c.quoteName(vectorField)
|
|
997
|
+
\t\tsqlQuery = fmt.Sprintf(
|
|
998
|
+
\t\t\t"SELECT TOP (%d) *, VECTOR_DISTANCE('%s', CAST(%s AS VECTOR(%d, float32)), CAST(? AS VECTOR(%d, float32))) AS distance FROM %s WITH (NOLOCK)",
|
|
999
|
+
\t\t\ttake, distanceMetric, vcol, dim, dim, c.quoteTable(),
|
|
1000
|
+
\t\t)
|
|
1001
|
+
\t\tif whereCl != "" {
|
|
1002
|
+
\t\t\tsqlQuery += fmt.Sprintf(" WHERE %s IS NOT NULL AND (%s)", vcol, whereCl)
|
|
1003
|
+
\t\t} else {
|
|
1004
|
+
\t\t\tsqlQuery += fmt.Sprintf(" WHERE %s IS NOT NULL", vcol)
|
|
1005
|
+
\t\t}
|
|
1006
|
+
\t\tsqlQuery += " ORDER BY distance ASC"
|
|
1007
|
+
\t}
|
|
1008
|
+
|
|
1009
|
+
\tnativeRows, nativeErr := c.queryAndScan(ctx, sqlQuery, queryArgs...)
|
|
1010
|
+
\tif nativeErr == nil {
|
|
1011
|
+
\t\treturn nativeRows, nil
|
|
1012
|
+
\t}
|
|
1013
|
+
|
|
1014
|
+
\t// 2. Fallback: in-memory similarity
|
|
1015
|
+
\trows, err := c.FindMany(ctx, whereArgs)
|
|
1016
|
+
\tif err != nil {
|
|
1017
|
+
\t\treturn nil, err
|
|
1018
|
+
\t}
|
|
1019
|
+
|
|
1020
|
+
\ttype scoredItem struct {
|
|
1021
|
+
\t\titem T
|
|
1022
|
+
\t\tdistance float64
|
|
1023
|
+
\t}
|
|
1024
|
+
\tvar scored []scoredItem
|
|
1025
|
+
|
|
1026
|
+
\tfor _, item := range rows {
|
|
1027
|
+
\t\tval := reflect.ValueOf(item)
|
|
1028
|
+
\t\tfieldVal := findFieldByDbTag(val, vectorField)
|
|
1029
|
+
\t\tif !fieldVal.IsValid() || fieldVal.IsZero() {
|
|
1030
|
+
\t\t\tcontinue
|
|
1031
|
+
\t\t}
|
|
1032
|
+
|
|
1033
|
+
\t\tvar rowVec []float64
|
|
1034
|
+
\t\tif fieldVal.Kind() == reflect.String {
|
|
1035
|
+
\t\t\t_ = json.Unmarshal([]byte(fieldVal.String()), &rowVec)
|
|
1036
|
+
\t\t} else if fieldVal.Kind() == reflect.Slice {
|
|
1037
|
+
\t\t\tfor i := 0; i < fieldVal.Len(); i++ {
|
|
1038
|
+
\t\t\t\trowVec = append(rowVec, fieldVal.Index(i).Float())
|
|
1039
|
+
\t\t\t}
|
|
1040
|
+
\t\t}
|
|
1041
|
+
\t\tif len(rowVec) != len(vector) {
|
|
1042
|
+
\t\t\tcontinue
|
|
1043
|
+
\t\t}
|
|
1044
|
+
|
|
1045
|
+
\t\tvar dist float64
|
|
1046
|
+
\t\tswitch strings.ToLower(distanceMetric) {
|
|
1047
|
+
\t\tcase "euclidean":
|
|
1048
|
+
\t\t\tvar sum float64
|
|
1049
|
+
\t\t\tfor i := range vector { d := vector[i] - rowVec[i]; sum += d * d }
|
|
1050
|
+
\t\t\tdist = math.Sqrt(sum)
|
|
1051
|
+
\t\tcase "dot":
|
|
1052
|
+
\t\t\tvar dot float64
|
|
1053
|
+
\t\t\tfor i := range vector { dot += vector[i] * rowVec[i] }
|
|
1054
|
+
\t\t\tdist = -dot
|
|
1055
|
+
\t\tdefault: // cosine
|
|
1056
|
+
\t\t\tvar dot, m1, m2 float64
|
|
1057
|
+
\t\t\tfor i := range vector { dot += vector[i] * rowVec[i]; m1 += vector[i] * vector[i]; m2 += rowVec[i] * rowVec[i] }
|
|
1058
|
+
\t\t\tif m1 > 0 && m2 > 0 { dist = 1.0 - dot/(math.Sqrt(m1)*math.Sqrt(m2)) } else { dist = 1.0 }
|
|
1059
|
+
\t\t}
|
|
1060
|
+
|
|
1061
|
+
\t\tscored = append(scored, scoredItem{item: item, distance: dist})
|
|
1062
|
+
\t}
|
|
1063
|
+
|
|
1064
|
+
\tsort.Slice(scored, func(i, j int) bool { return scored[i].distance < scored[j].distance })
|
|
1065
|
+
|
|
1066
|
+
\tvar result []T
|
|
1067
|
+
\tlimit := take
|
|
1068
|
+
\tif limit > len(scored) { limit = len(scored) }
|
|
1069
|
+
\tfor i := 0; i < limit; i++ {
|
|
1070
|
+
\t\tresult = append(result, scored[i].item)
|
|
1071
|
+
\t}
|
|
1072
|
+
\treturn result, nil
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
`;
|
|
1076
|
+
}
|
|
1077
|
+
// ─── Helpers ───────────────────────────────────────────────────────────────
|
|
1078
|
+
generateHelpers() {
|
|
1079
|
+
return `// findFieldByDbTag looks up a struct field by its "db" tag (case-insensitive).
|
|
1080
|
+
func findFieldByDbTag(val reflect.Value, dbTag string) reflect.Value {
|
|
1081
|
+
\tif val.Kind() == reflect.Ptr {
|
|
1082
|
+
\t\tval = val.Elem()
|
|
1083
|
+
\t}
|
|
1084
|
+
\tif val.Kind() != reflect.Struct {
|
|
1085
|
+
\t\treturn reflect.Value{}
|
|
1086
|
+
\t}
|
|
1087
|
+
\ttyp := val.Type()
|
|
1088
|
+
\tfor i := 0; i < typ.NumField(); i++ {
|
|
1089
|
+
\t\ttag := typ.Field(i).Tag.Get("db")
|
|
1090
|
+
\t\tif strings.EqualFold(tag, dbTag) || strings.EqualFold(typ.Field(i).Name, dbTag) {
|
|
1091
|
+
\t\t\treturn val.Field(i)
|
|
1092
|
+
\t\t}
|
|
1093
|
+
\t}
|
|
1094
|
+
\treturn reflect.Value{}
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// toSnakeCase converts CamelCase to snake_case for column name resolution.
|
|
1098
|
+
func (c *TableClient[T]) toSnakeCase(s string) string {
|
|
1099
|
+
\tvar res []rune
|
|
1100
|
+
\tfor i, r := range s {
|
|
1101
|
+
\t\tif i > 0 && r >= 'A' && r <= 'Z' {
|
|
1102
|
+
\t\t\tres = append(res, '_')
|
|
1103
|
+
\t\t}
|
|
1104
|
+
\t\tres = append(res, []rune(strings.ToLower(string(r)))...)
|
|
1105
|
+
\t}
|
|
1106
|
+
\treturn string(res)
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// Ensure unused imports are referenced
|
|
1110
|
+
var _ = sort.Slice
|
|
1111
|
+
var _ = time.Time{}
|
|
1112
|
+
|
|
1113
|
+
`;
|
|
1114
|
+
}
|
|
1115
|
+
// ─── Per-model ORM types ───────────────────────────────────────────────────
|
|
1116
|
+
generateModelOrmTypes(model) {
|
|
1117
|
+
const name = this.capitalize(model.name);
|
|
1118
|
+
let content = `// ─── ${name} ORM Types ──────────────────────────────────────────────────────────\n\n`;
|
|
1119
|
+
// WhereInput
|
|
1120
|
+
content += `// ${name}WhereInput provides type-safe filtering for ${name} queries.\ntype ${name}WhereInput struct {\n`;
|
|
1121
|
+
content += `\tAND []${name}WhereInput\n`;
|
|
1122
|
+
content += `\tOR []${name}WhereInput\n`;
|
|
1123
|
+
content += `\tNOT *${name}WhereInput\n`;
|
|
1124
|
+
for (const field of model.fields) {
|
|
1125
|
+
const filterType = this.getGoFilterType(field);
|
|
1126
|
+
content += `\t${this.capitalize(field.name)} *${filterType}\n`;
|
|
1127
|
+
}
|
|
1128
|
+
content += `}\n\n`;
|
|
1129
|
+
// OrderByInput
|
|
1130
|
+
content += `// ${name}OrderByInput provides type-safe ordering for ${name} queries.\ntype ${name}OrderByInput struct {\n`;
|
|
1131
|
+
for (const field of model.fields) {
|
|
1132
|
+
content += `\t${this.capitalize(field.name)} *SortOrder\n`;
|
|
1133
|
+
}
|
|
1134
|
+
content += `}\n\n`;
|
|
1135
|
+
// CreateInput
|
|
1136
|
+
content += `// ${name}CreateInput holds data for creating a new ${name} record.\ntype ${name}CreateInput struct {\n`;
|
|
1137
|
+
for (const field of model.fields) {
|
|
1138
|
+
if (!field.isId) {
|
|
1139
|
+
const goType = this.mapGoType(field, field.isOptional || field.hasDefault);
|
|
1140
|
+
content += `\t${this.capitalize(field.name)} ${goType}\n`;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
content += `}\n\n`;
|
|
1144
|
+
// UpdateInput
|
|
1145
|
+
content += `// ${name}UpdateInput holds data for updating an existing ${name} record.\ntype ${name}UpdateInput struct {\n`;
|
|
1146
|
+
for (const field of model.fields) {
|
|
1147
|
+
if (!field.isId) {
|
|
1148
|
+
const goType = this.mapGoType(field, true); // always pointer so we can detect zero
|
|
1149
|
+
content += `\t${this.capitalize(field.name)} ${goType}\n`;
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
content += `}\n\n`;
|
|
1153
|
+
// FindManyArgs
|
|
1154
|
+
content += `// ${name}FindManyArgs provides ORM-style args for FindMany queries on ${name}.\ntype ${name}FindManyArgs struct {\n`;
|
|
1155
|
+
content += `\tWhere *${name}WhereInput\n`;
|
|
1156
|
+
content += `\tOrderBy *${name}OrderByInput\n`;
|
|
1157
|
+
content += `\tTake *int\n`;
|
|
1158
|
+
content += `\tSkip *int\n`;
|
|
1159
|
+
content += `\tSelect []string\n`;
|
|
1160
|
+
content += `}\n\n`;
|
|
1161
|
+
// FindFirstArgs
|
|
1162
|
+
content += `// ${name}FindFirstArgs provides ORM-style args for FindFirst queries on ${name}.\ntype ${name}FindFirstArgs struct {\n`;
|
|
1163
|
+
content += `\tWhere *${name}WhereInput\n`;
|
|
1164
|
+
content += `\tOrderBy *${name}OrderByInput\n`;
|
|
1165
|
+
content += `\tSelect []string\n`;
|
|
1166
|
+
content += `}\n\n`;
|
|
1167
|
+
// FindUniqueArgs
|
|
1168
|
+
content += `// ${name}FindUniqueArgs provides ORM-style args for FindUnique queries on ${name}.\ntype ${name}FindUniqueArgs struct {\n`;
|
|
1169
|
+
content += `\tWhere *${name}WhereInput\n`;
|
|
1170
|
+
content += `}\n\n`;
|
|
1171
|
+
// DeleteManyArgs
|
|
1172
|
+
content += `// ${name}DeleteManyArgs provides ORM-style args for DeleteMany queries on ${name}.\ntype ${name}DeleteManyArgs struct {\n`;
|
|
1173
|
+
content += `\tWhere *${name}WhereInput\n`;
|
|
1174
|
+
content += `}\n\n`;
|
|
1175
|
+
// CountArgs
|
|
1176
|
+
content += `// ${name}CountArgs provides ORM-style args for Count queries on ${name}.\ntype ${name}CountArgs struct {\n`;
|
|
1177
|
+
content += `\tWhere *${name}WhereInput\n`;
|
|
1178
|
+
content += `}\n\n`;
|
|
1179
|
+
return content;
|
|
1180
|
+
}
|
|
1181
|
+
getGoFilterType(field) {
|
|
1182
|
+
// From the declared type, so a DECIMAL column gets the number filter and an INT
|
|
1183
|
+
// column the integer one; both used to arrive as `number` and pick the first.
|
|
1184
|
+
switch ((0, type_kinds_1.fieldKind)(field, this.provider)) {
|
|
1185
|
+
case 'date': return 'DateTimeFilter';
|
|
1186
|
+
case 'bool': return 'BoolFilter';
|
|
1187
|
+
case 'int':
|
|
1188
|
+
case 'bigint': return 'IntFilter';
|
|
1189
|
+
case 'float': return 'NumberFilter';
|
|
1190
|
+
default: return 'StringFilter';
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
// ─── Utilities ─────────────────────────────────────────────────────────────
|
|
1194
|
+
getAllPropertyVariations(modelName) {
|
|
1195
|
+
const variations = new Set();
|
|
1196
|
+
variations.add(modelName);
|
|
1197
|
+
variations.add(this.toCamelCase(modelName));
|
|
1198
|
+
variations.add(modelName + 's');
|
|
1199
|
+
variations.add(this.toCamelCase(modelName) + 's');
|
|
1200
|
+
const acronyms = ['LLM', 'AI', 'MCP', 'IT', 'QC', 'HR', 'MR', 'WH', 'SSIS', 'API', 'URL', 'ID', 'JSON'];
|
|
1201
|
+
for (const acronym of acronyms) {
|
|
1202
|
+
if (modelName.startsWith(acronym)) {
|
|
1203
|
+
variations.add(acronym.toLowerCase() + modelName.slice(acronym.length));
|
|
1204
|
+
variations.add(acronym[0].toLowerCase() + acronym.slice(1) + modelName.slice(acronym.length));
|
|
1205
|
+
variations.add(acronym.toLowerCase() + modelName.slice(acronym.length) + 's');
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
return Array.from(variations);
|
|
1209
|
+
}
|
|
1210
|
+
capitalize(str) {
|
|
1211
|
+
if (!str)
|
|
1212
|
+
return '';
|
|
1213
|
+
return str[0].toUpperCase() + str.slice(1);
|
|
1214
|
+
}
|
|
1215
|
+
toCamelCase(str) {
|
|
1216
|
+
if (!str)
|
|
1217
|
+
return '';
|
|
1218
|
+
return str[0].toLowerCase() + str.slice(1);
|
|
1219
|
+
}
|
|
1220
|
+
toSnakeCase(str) {
|
|
1221
|
+
if (!str)
|
|
1222
|
+
return '';
|
|
1223
|
+
return str
|
|
1224
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
|
|
1225
|
+
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
|
|
1226
|
+
.toLowerCase();
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
exports.GolangGenerator = GolangGenerator;
|