@apso/cli 0.47.6 → 0.48.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.
Files changed (74) hide show
  1. package/dist/commands/generate.js +6 -0
  2. package/dist/lib/ddl/change.js +2 -0
  3. package/dist/lib/ddl/index.d.ts +11 -1
  4. package/dist/lib/ddl/index.js +30 -16
  5. package/dist/lib/ddl/sync.d.ts +25 -0
  6. package/dist/lib/ddl/sync.js +78 -0
  7. package/dist/lib/generators/go.d.ts +12 -6
  8. package/dist/lib/generators/go.js +223 -97
  9. package/dist/lib/generators/python.d.ts +6 -0
  10. package/dist/lib/generators/python.js +234 -23
  11. package/dist/lib/templates/entities/entity-col-array.eta +1 -1
  12. package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
  13. package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
  14. package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
  15. package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
  16. package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
  17. package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
  18. package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
  19. package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
  20. package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
  21. package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
  22. package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
  23. package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
  24. package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
  25. package/dist/lib/templates/go/dto/dto.eta +17 -18
  26. package/dist/lib/templates/go/handlers/handler.eta +2 -0
  27. package/dist/lib/templates/go/index-module.eta +3 -1
  28. package/dist/lib/templates/go/middleware/auth.eta +1 -1
  29. package/dist/lib/templates/go/models/model.eta +22 -19
  30. package/dist/lib/templates/go/models/schema.eta +72 -0
  31. package/dist/lib/templates/go/services/service.eta +49 -21
  32. package/dist/lib/templates/go/utils/query.eta +32 -6
  33. package/dist/lib/templates/python/models/init.eta +24 -0
  34. package/dist/lib/templates/python/models/model.eta +24 -56
  35. package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
  36. package/dist/lib/templates/python/schemas/schema.eta +9 -9
  37. package/dist/lib/utils/field.d.ts +12 -0
  38. package/dist/lib/utils/field.js +18 -2
  39. package/npm-shrinkwrap.json +2 -2
  40. package/oclif.manifest.json +1 -1
  41. package/package.json +1 -1
  42. package/dist/lib/templates/go/models/model-col-array.eta +0 -1
  43. package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
  44. package/dist/lib/templates/go/models/model-col-date.eta +0 -1
  45. package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
  46. package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
  47. package/dist/lib/templates/go/models/model-col-float.eta +0 -1
  48. package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
  49. package/dist/lib/templates/go/models/model-col-json.eta +0 -1
  50. package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
  51. package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
  52. package/dist/lib/templates/go/models/model-col-string.eta +0 -1
  53. package/dist/lib/templates/go/models/model-col-text.eta +0 -1
  54. package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
  55. package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
  56. package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
  57. package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
  58. package/dist/lib/templates/python/models/model-col-array.eta +0 -4
  59. package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
  60. package/dist/lib/templates/python/models/model-col-date.eta +0 -4
  61. package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
  62. package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
  63. package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
  64. package/dist/lib/templates/python/models/model-col-float.eta +0 -6
  65. package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
  66. package/dist/lib/templates/python/models/model-col-json.eta +0 -4
  67. package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
  68. package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
  69. package/dist/lib/templates/python/models/model-col-string.eta +0 -6
  70. package/dist/lib/templates/python/models/model-col-text.eta +0 -6
  71. package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
  72. package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
  73. package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
  74. package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
@@ -12,7 +12,116 @@ const casing_1 = require("../utils/casing");
12
12
  const events_1 = require("../events");
13
13
  const guards_1 = require("../guards");
14
14
  const migration_file_1 = require("../ddl/migration-file");
15
+ const ddl_1 = require("../ddl");
16
+ const sync_1 = require("../ddl/sync");
15
17
  const pluralize_1 = tslib_1.__importDefault(require("pluralize"));
18
+ // Postgres array element type -> [SQLAlchemy column type, Python type]. The
19
+ // column type must give the same Postgres type the DDL writer does.
20
+ const arrayElementTypes = {
21
+ text: ["Text", "str"],
22
+ varchar: ["String", "str"],
23
+ uuid: ["PGUUID(as_uuid=True)", "UUID"],
24
+ integer: ["Integer", "int"],
25
+ int: ["Integer", "int"],
26
+ int4: ["Integer", "int"],
27
+ smallint: ["SmallInteger", "int"],
28
+ bigint: ["BigInteger", "int"],
29
+ numeric: ["Numeric", "Decimal"],
30
+ decimal: ["Numeric", "Decimal"],
31
+ real: ["REAL", "float"],
32
+ float: ["Float", "float"],
33
+ float8: ["Float", "float"],
34
+ "double precision": ["Float", "float"],
35
+ boolean: ["Boolean", "bool"],
36
+ bool: ["Boolean", "bool"],
37
+ date: ["Date", "date"],
38
+ timestamp: ["DateTime", "datetime"],
39
+ timestamptz: ["DateTime(timezone=True)", "datetime"],
40
+ };
41
+ // Field type -> Pydantic schema template, where the type has none of its own.
42
+ const schemaTemplates = {
43
+ char: "varchar",
44
+ bigint: "integer",
45
+ smallint: "integer",
46
+ double: "float",
47
+ "json-plain": "json",
48
+ };
49
+ // DDL column type -> [SQLAlchemy type, Python type]; the SQLAlchemy type
50
+ // creates that same Postgres type.
51
+ const saTypes = {
52
+ text: ["Text", "str"],
53
+ integer: ["Integer", "int"],
54
+ bigint: ["BigInteger", "int"],
55
+ smallint: ["SmallInteger", "int"],
56
+ numeric: ["Numeric()", "Decimal"],
57
+ "double precision": ["DOUBLE_PRECISION", "float"],
58
+ boolean: ["Boolean", "bool"],
59
+ uuid: ["PGUUID(as_uuid=True)", "UUID"],
60
+ date: ["Date", "date"],
61
+ TIMESTAMP: ["DateTime", "datetime"],
62
+ "TIMESTAMP WITH TIME ZONE": ["DateTime(timezone=True)", "datetime"],
63
+ jsonb: ["JSONB", "dict"],
64
+ json: ["JSON", "dict"],
65
+ };
66
+ function saType(type) {
67
+ const sized = type.match(/^(character varying|character|numeric)\((\d+)(?:,(\d+))?\)$/);
68
+ if (sized) {
69
+ const [, kind, a, b] = sized;
70
+ if (kind === "numeric")
71
+ return [`Numeric(${a}, ${b})`, "Decimal"];
72
+ return [`${kind === "character" ? "CHAR" : "String"}(${a})`, "str"];
73
+ }
74
+ if (type.endsWith("[]")) {
75
+ const element = arrayElementTypes[type.slice(0, -2).toLowerCase()];
76
+ if (!element)
77
+ throw new Error(`The Python generator does not support ${type} columns. Use one of: ${Object.keys(arrayElementTypes).join(", ")}.`);
78
+ return [`ARRAY(${element[0]})`, `List[${element[1]}]`];
79
+ }
80
+ const known = saTypes[type];
81
+ if (!known)
82
+ throw new Error(`The Python generator does not support ${type} columns.`);
83
+ return known;
84
+ }
85
+ const withArrayTypes = (columns, entityName) => columns.map((c) => {
86
+ if (c.type !== "array")
87
+ return c;
88
+ const element = (0, field_1.arrayElementType)(c);
89
+ const types = arrayElementTypes[element.toLowerCase()];
90
+ if (!types)
91
+ throw new Error(`Field ${entityName}.${c.name} has elementType "${element}", which the Python generator does not support. Use one of: ${Object.keys(arrayElementTypes).join(", ")}.`);
92
+ return { ...c, arrayColumnType: types[0], arrayItemType: types[1] };
93
+ });
94
+ /** The ForeignKey(...) of a DDL foreign key constraint. */
95
+ const pyForeignKey = (fk) => {
96
+ const [, targetCol, onDelete, onUpdate] = fk.body.match(/REFERENCES "[^"]+"\("([^"]+)"\) ON DELETE (.+) ON UPDATE (.+)$/);
97
+ return `ForeignKey(${(0, migration_file_1.pyString)(`${fk.references}.${targetCol}`)}, name=${(0, migration_file_1.pyString)(fk.name)}, ondelete=${(0, migration_file_1.pyString)(onDelete)}, onupdate=${(0, migration_file_1.pyString)(onUpdate)})`;
98
+ };
99
+ /**
100
+ * A DDL column as a SQLAlchemy Column argument list: type, foreign key,
101
+ * key, NULL and default exactly as the DDL writer creates them.
102
+ */
103
+ function pyColumnArgs(table, c, field, fk, primary) {
104
+ const [type, enumOrPyType] = (field === null || field === void 0 ? void 0 : field.type) === "enum"
105
+ ? [
106
+ `SAEnum(enums.${field.dataType}, name=${(0, migration_file_1.pyString)((0, ddl_1.enumTypeName)(table, field.name))}, values_callable=lambda x: [e.value for e in x])`,
107
+ `enums.${field.dataType}`,
108
+ ]
109
+ : saType(c.type);
110
+ const args = [type];
111
+ if (fk)
112
+ args.push(pyForeignKey(fk));
113
+ if (primary)
114
+ args.push("primary_key=True");
115
+ if (c.serial)
116
+ args.push("autoincrement=True");
117
+ else if (!primary)
118
+ args.push(`nullable=${c.notNull ? "False" : "True"}`);
119
+ if (c.default !== undefined && !c.serial)
120
+ args.push(`server_default=text(${(0, migration_file_1.pyString)(c.default)})`);
121
+ if (c.name === "updated_at")
122
+ args.push("onupdate=func.now()");
123
+ return { args, pyType: c.notNull ? enumOrPyType : `Optional[${enumOrPyType}]` };
124
+ }
16
125
  /**
17
126
  * Python/FastAPI generator that produces SQLAlchemy models, Pydantic schemas,
18
127
  * and FastAPI routers.
@@ -59,7 +168,12 @@ class PythonGenerator extends base_1.BaseGenerator {
59
168
  "text",
60
169
  "varchar",
61
170
  "string",
171
+ "char",
62
172
  "integer",
173
+ "bigint",
174
+ "smallint",
175
+ "double",
176
+ "json-plain",
63
177
  "boolean",
64
178
  "float",
65
179
  "decimal",
@@ -87,31 +201,77 @@ class PythonGenerator extends base_1.BaseGenerator {
87
201
  }
88
202
  async generateEntity(options) {
89
203
  const { entity, relationships, allEntities, apiType } = options;
90
- const { name, fields = [], indexes, uniques } = entity;
91
- const columns = (0, field_1.getFieldForTemplate)(fields, name);
92
- const createPrimaryKey = columns.filter((column) => column.primary === true).length === 0;
93
- const createdAt = entity.created_at;
94
- const updatedAt = entity.updated_at;
95
- const primaryKeyType = entity.primaryKeyType || "serial";
204
+ const { name, fields = [] } = entity;
205
+ // Every table object comes from the DDL writer's model of the schema, so
206
+ // create_all builds what the migrations from `apso migrate` build.
207
+ const model = (0, ddl_1.schemaModel)({
208
+ entities: allEntities,
209
+ relationshipMap: {
210
+ ...this.config.relationshipMap,
211
+ [name]: relationships,
212
+ },
213
+ });
214
+ const table = (0, ddl_1.tableName)(entity);
215
+ const byField = new Map((0, field_1.getFieldForTemplate)(fields, name).map((f) => [f.name, f]));
216
+ const tableArgs = (t) => {
217
+ const pk = model.constraints.find((c) => c.kind === "pk" && c.table === t);
218
+ return {
219
+ pk,
220
+ args: [
221
+ `PrimaryKeyConstraint(${[...pk.columns, `name=${(0, migration_file_1.pyString)(pk.name)}`]
222
+ .map((x) => (x.startsWith("name=") ? x : (0, migration_file_1.pyString)(x)))
223
+ .join(", ")})`,
224
+ ...model.constraints
225
+ .filter((c) => c.kind === "unique" && c.table === t)
226
+ .map((c) => `UniqueConstraint(${c.columns
227
+ .map((x) => (0, migration_file_1.pyString)(x))
228
+ .join(", ")}, name=${(0, migration_file_1.pyString)(c.name)})`),
229
+ ...model.indexes
230
+ .filter((i) => i.table === t)
231
+ .map((i) => `Index(${[i.name, ...i.columns].map((x) => (0, migration_file_1.pyString)(x)).join(", ")}${i.unique ? ", unique=True" : ""})`),
232
+ ],
233
+ };
234
+ };
235
+ const columnsOf = (t, fieldOf) => {
236
+ const { pk, args } = tableArgs(t);
237
+ const columns = model.tables
238
+ .find((x) => x.name === t)
239
+ .columns.map((c) => ({
240
+ name: c.name,
241
+ ...pyColumnArgs(t, c, fieldOf === null || fieldOf === void 0 ? void 0 : fieldOf(c.name), model.constraints.find((k) => k.kind === "fk" && k.table === t && k.columns[0] === c.name), pk.columns.includes(c.name)),
242
+ }));
243
+ return { columns, tableArgs: args };
244
+ };
245
+ const own = columnsOf(table, (c) => byField.get(c));
96
246
  const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(name, relationships, allEntities);
247
+ const byName = new Map(allEntities.map((e) => [e.name, e]));
248
+ const joinTables = relationshipsForTemplate
249
+ .filter((r) => r.type === "ManyToMany" && r.joinTable && byName.get(r.name))
250
+ .map((r) => {
251
+ const j = (0, ddl_1.joinTableOf)(entity, r, byName.get(r.name));
252
+ return { name: j.name, ...columnsOf(j.name) };
253
+ });
254
+ // A non-owning ManyToMany names the join table its owner declares.
255
+ const associations = relationshipsForTemplate.map((r) => {
256
+ var _a;
257
+ if (r.type === "OneToOne" && r.joinTable)
258
+ return { ...r, fkColumn: (0, ddl_1.relationColumn)(r) };
259
+ if (r.type !== "ManyToMany" || !byName.get(r.name))
260
+ return r;
261
+ const target = byName.get(r.name);
262
+ if (r.joinTable)
263
+ return { ...r, secondary: (0, ddl_1.joinTableOf)(entity, r, target).name };
264
+ const owner = (0, relationships_1.getRelationshipForTemplate)(target.name, ((_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {})[target.name] || [], allEntities).find((o) => o.type === "ManyToMany" && o.joinTable && o.name === name);
265
+ return { ...r, secondary: owner && (0, ddl_1.joinTableOf)(target, owner, entity).name };
266
+ });
97
267
  const entitiesToImport = (0, relationships_1.getRelationshipsForImport)(name, relationshipsForTemplate);
98
268
  const data = {
99
269
  name,
100
- indexes: indexes || [],
101
- uniques: uniques || [],
102
- createPrimaryKey,
103
- primaryKeyType,
104
- snakeCasedName: (0, casing_1.snakeCase)(name),
105
- // Honor an explicit per-entity `table` override; otherwise derive from
106
- // the entity name. See apsoai/cli#107 (Python/Go parity with #98).
107
- tableName: entity.table || (0, casing_1.snakeCase)(name),
108
- // Foreign keys name the referenced entity's real table, override included.
109
- tableNames: Object.fromEntries(allEntities.map((e) => [e.name, e.table || (0, casing_1.snakeCase)(e.name)])),
110
- createdAt,
111
- updatedAt,
112
- pluralizedName: (0, casing_1.camelCase)((0, pluralize_1.default)(name)),
113
- columns,
114
- associations: [...new Set(relationshipsForTemplate)],
270
+ tableName: table,
271
+ columns: own.columns,
272
+ tableArgs: own.tableArgs,
273
+ joinTables,
274
+ associations,
115
275
  entitiesToImport,
116
276
  importEnums: (0, field_1.typeExistsInEntity)(entity, "enum") !== -1,
117
277
  apiType,
@@ -168,8 +328,17 @@ class PythonGenerator extends base_1.BaseGenerator {
168
328
  async generateDto(options) {
169
329
  const { entity, relationships, allEntities, apiType } = options;
170
330
  const { name: entityName, fields = [] } = entity;
171
- const columns = (0, field_1.getFieldForTemplate)(fields, entityName);
172
- const relationshipsTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
331
+ const table = (0, ddl_1.tableName)(entity);
332
+ const columns = withArrayTypes((0, field_1.getFieldForTemplate)(fields, entityName), entityName).map((c) => {
333
+ const spec = (0, ddl_1.columnSpec)(table, c);
334
+ return {
335
+ ...c,
336
+ schemaTemplate: schemaTemplates[c.type] || c.type,
337
+ // NOT NULL with no default: the create schema requires it.
338
+ required: spec.notNull && spec.default === undefined,
339
+ };
340
+ });
341
+ const relationshipsTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships, allEntities);
173
342
  // Add foreign key columns for ManyToOne relationships
174
343
  relationshipsTemplate.forEach((rel) => {
175
344
  if (rel.type === "ManyToOne") {
@@ -292,8 +461,50 @@ ${downStatements || " pass"}
292
461
  path: "__init__.py",
293
462
  content,
294
463
  },
464
+ {
465
+ path: "models/__init__.py",
466
+ content: await this.renderTemplate("./models/init", this.modelsInitData(entities)),
467
+ },
295
468
  ];
296
469
  }
470
+ /**
471
+ * What create_all must run first: the extensions the tables use, and a
472
+ * guard that stops when the database still has a join table or enum type
473
+ * under the name older generated models gave it.
474
+ */
475
+ modelsInitData(entities) {
476
+ var _a, _b;
477
+ const relationshipMap = (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {};
478
+ const model = (0, ddl_1.schemaModel)({ entities, relationshipMap });
479
+ const legacy = [];
480
+ for (const entity of entities) {
481
+ const table = (0, ddl_1.tableName)(entity);
482
+ for (const f of (_b = entity.fields) !== null && _b !== void 0 ? _b : [])
483
+ if (f.type === "enum") {
484
+ const old = `${entity.name}_${f.name}_enum`.toLowerCase();
485
+ const now = (0, ddl_1.enumTypeName)(table, f.name);
486
+ if (old !== now)
487
+ legacy.push((0, sync_1.legacyType)(old, now));
488
+ }
489
+ for (const r of (0, relationships_1.getRelationshipForTemplate)(entity.name, relationshipMap[entity.name] || [], entities)) {
490
+ const target = entities.find((e) => e.name === r.name);
491
+ if (r.type !== "ManyToMany" || !r.joinTable || !target)
492
+ continue;
493
+ const j = (0, ddl_1.joinTableOf)(entity, r, target);
494
+ const old = r.joinTableName || `${table}_${r.name.toLowerCase()}`;
495
+ if (old !== j.name)
496
+ legacy.push((0, sync_1.legacyTable)(old, j.name, [
497
+ [r.joinColumnName || `${table}_id`, j.ownCol],
498
+ [r.inverseJoinColumnName || `${r.name.toLowerCase()}_id`, j.otherCol],
499
+ ]));
500
+ }
501
+ }
502
+ const guard = (0, sync_1.legacyGuardSql)(legacy);
503
+ return {
504
+ modules: entities.map((e) => [e.name.toLowerCase(), e.name]),
505
+ statements: [...model.extensions, ...(guard ? [guard] : [])].map((x) => (0, migration_file_1.pyString)(x)),
506
+ };
507
+ }
297
508
  /**
298
509
  * Emits a schema-derived manifest of the entities that opted in to
299
510
  * domain-event emission (`.apsorc` `emitEvents`), mirroring the TypeScript
@@ -9,4 +9,4 @@
9
9
  @Index()
10
10
  <% } %>
11
11
 
12
- <%= field.name %>: <%= field.elementType === 'int' || field.elementType === 'smallint' || field.elementType === 'decimal' || field.elementType === 'numeric' || field.elementType === 'real' || field.elementType === 'float8' ? 'number' : 'string' %>[];
12
+ <%= field.name %>: <%= field.dataType %>;
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> []<%= it.column.arrayItemGoType || 'string' %> `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> []<%= it.column.arrayItemGoType || 'string' %> `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
4
+ <%= it.column.pascalName %> []<%= it.column.arrayItemGoType || 'string' %> `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
5
5
  <% } else { %>
6
- <%= it.column.pascalName %> []<%= it.column.arrayItemGoType || 'string' %> `json:"<%= it.column.name %>,omitempty"`
6
+ <%= it.column.pascalName %> *[]<%= it.column.arrayItemGoType || 'string' %> `json:"<%= it.column.name %>,omitempty"`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *time.Time `json:"<%= it.column.name %>,omitempty"`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *float64 `json:"<%= it.column.name %>,omitempty"`
7
7
  <% } %>
@@ -2,7 +2,7 @@
2
2
  <% if (it.mode === 'response') { %>
3
3
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>enums.<%= enumTypeName %> `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
4
4
  <% } else if (it.mode === 'create') { %>
5
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>enums.<%= enumTypeName %> `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
5
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>enums.<%= enumTypeName %> `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
6
6
  <% } else { %>
7
7
  <%= it.column.pascalName %> *enums.<%= enumTypeName %> `json:"<%= it.column.name %>,omitempty"`
8
8
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *float64 `json:"<%= it.column.name %>,omitempty"`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>int `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
2
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %><%= it.column.goType %> `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>int `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %><%= it.column.goType %> `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
5
5
  <% } else { %>
6
- <%= it.column.pascalName %> *int `json:"<%= it.column.name %>,omitempty"`
6
+ <%= it.column.pascalName %> *<%= it.column.goType %> `json:"<%= it.column.name %>,omitempty"`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *float64 `json:"<%= it.column.name %>,omitempty"`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required<% if (it.column.length) { %>,max=<%= it.column.length %><% } %>"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required<% if (it.column.length) { %>,max=<%= it.column.length %><% } %>"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *string `json:"<%= it.column.name %>,omitempty"<% if (it.column.length) { %> validate:"omitempty,max=<%= it.column.length %>"<% } %>`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *string `json:"<%= it.column.name %>,omitempty"`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *time.Time `json:"<%= it.column.name %>,omitempty"`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *time.Time `json:"<%= it.column.name %>,omitempty"`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required,uuid"<% } else { %> validate:"omitempty,uuid"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required,uuid"<% } else { %> validate:"omitempty,uuid"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *string `json:"<%= it.column.name %>,omitempty" validate:"omitempty,uuid"`
7
7
  <% } %>
@@ -1,7 +1,7 @@
1
1
  <% if (it.mode === 'response') { %>
2
2
  <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
3
3
  <% } else if (it.mode === 'create') { %>
4
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.required) { %> validate:"required<% if (it.column.length) { %>,max=<%= it.column.length %><% } %>"<% } %>`
4
+ <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"<% if (it.column.mustSend) { %> validate:"required<% if (it.column.length) { %>,max=<%= it.column.length %><% } %>"<% } %>`
5
5
  <% } else { %>
6
6
  <%= it.column.pascalName %> *string `json:"<%= it.column.name %>,omitempty"<% if (it.column.length) { %> validate:"omitempty,max=<%= it.column.length %>"<% } %>`
7
7
  <% } %>
@@ -2,12 +2,16 @@
2
2
 
3
3
  package dto
4
4
 
5
+ <% if (it.importTime || it.importEnums) { %>
5
6
  import (
7
+ <% if (it.importTime) { %>
6
8
  "time"
9
+ <% } %>
7
10
  <% if (it.importEnums) { %>
8
11
  "app/autogen/models/enums"
9
12
  <% } %>
10
13
  )
14
+ <% } %>
11
15
 
12
16
  // <%= it.entityName %>Response represents the response DTO for <%= it.entityName %>
13
17
  type <%= it.entityName %>Response struct {
@@ -19,7 +23,7 @@ type <%= it.entityName %>Response struct {
19
23
  <% } -%>
20
24
  <% } -%>
21
25
  <% it.columns.forEach((column) => { -%>
22
- <%~ includeFile('./dto-col-' + column.type + '.eta', { column, mode: 'response' }) %>
26
+ <%~ includeFile('./dto-col-' + column.dtoTemplate + '.eta', { column, mode: 'response' }) %>
23
27
  <% }); -%>
24
28
  <% if (it.createdAt) { -%>
25
29
  CreatedAt time.Time `json:"createdAt"`
@@ -28,18 +32,13 @@ type <%= it.entityName %>Response struct {
28
32
  UpdatedAt time.Time `json:"updatedAt"`
29
33
  <% } -%>
30
34
  <% it.associations.forEach((assoc) => { -%>
31
- <% if (assoc.type === 'OneToMany') { -%>
32
- <%= assoc.pluralName %> []<%= assoc.name %>Response `json:"<%= assoc.camelPluralName %>,omitempty"`
33
- <% } else if (assoc.type === 'ManyToOne') { -%>
34
- <%= assoc.referenceName || assoc.name %>ID <%= assoc.primaryKeyGoType || 'uint' %> `json:"<%= assoc.camelReferenceName || assoc.camelName %>Id"`
35
- <%= assoc.referenceName || assoc.name %> *<%= assoc.name %>Response `json:"<%= assoc.camelReferenceName || assoc.camelName %>,omitempty"`
35
+ <% if (assoc.owns) { -%>
36
+ <%= assoc.fkField %> <%= assoc.fkGoType %> `json:"<%= assoc.camelReferenceName %>Id"`
37
+ <%= assoc.fieldName %> *<%= assoc.name %>Response `json:"<%= assoc.jsonName %>,omitempty"`
36
38
  <% } else if (assoc.type === 'OneToOne') { -%>
37
- <% if (assoc.isOwner) { -%>
38
- <%= assoc.referenceName || assoc.name %>ID <%= assoc.primaryKeyGoType || 'uint' %> `json:"<%= assoc.camelReferenceName || assoc.camelName %>Id"`
39
- <% } -%>
40
- <%= assoc.referenceName || assoc.name %> *<%= assoc.name %>Response `json:"<%= assoc.camelReferenceName || assoc.camelName %>,omitempty"`
41
- <% } else if (assoc.type === 'ManyToMany') { -%>
42
- <%= assoc.pluralName %> []<%= assoc.name %>Response `json:"<%= assoc.camelPluralName %>,omitempty"`
39
+ <%= assoc.fieldName %> *<%= assoc.name %>Response `json:"<%= assoc.jsonName %>,omitempty"`
40
+ <% } else if (assoc.type === 'OneToMany' || (assoc.type === 'ManyToMany' && assoc.join)) { -%>
41
+ <%= assoc.fieldName %> []<%= assoc.name %>Response `json:"<%= assoc.jsonName %>,omitempty"`
43
42
  <% } -%>
44
43
  <% }) -%>
45
44
  }
@@ -47,11 +46,11 @@ type <%= it.entityName %>Response struct {
47
46
  // <%= it.entityName %>Create represents the create DTO for <%= it.entityName %>
48
47
  type <%= it.entityName %>Create struct {
49
48
  <% it.columns.forEach((column) => { -%>
50
- <%~ includeFile('./dto-col-' + column.type + '.eta', { column, mode: 'create' }) %>
49
+ <%~ includeFile('./dto-col-' + column.dtoTemplate + '.eta', { column, mode: 'create' }) %>
51
50
  <% }); -%>
52
51
  <% it.associations.forEach((assoc) => { -%>
53
- <% if (assoc.type === 'ManyToOne' || (assoc.type === 'OneToOne' && assoc.isOwner)) { -%>
54
- <%= assoc.referenceName || assoc.name %>ID <%= assoc.primaryKeyGoType || 'uint' %> `json:"<%= assoc.camelReferenceName || assoc.camelName %>Id"<% if (!assoc.scoped) { %> validate:"required"<% } %>`
52
+ <% if (assoc.owns) { -%>
53
+ <%= assoc.fkField %> <%= assoc.fkGoType %> `json:"<%= assoc.camelReferenceName %>Id<% if (assoc.fkNullable) { %>,omitempty<% } %>"<% if (!assoc.scoped && !assoc.fkNullable) { %> validate:"required"<% } %>`
55
54
  <% } -%>
56
55
  <% }) -%>
57
56
  }
@@ -59,11 +58,11 @@ type <%= it.entityName %>Create struct {
59
58
  // <%= it.entityName %>Update represents the update DTO for <%= it.entityName %>
60
59
  type <%= it.entityName %>Update struct {
61
60
  <% it.columns.forEach((column) => { -%>
62
- <%~ includeFile('./dto-col-' + column.type + '.eta', { column, mode: 'update' }) %>
61
+ <%~ includeFile('./dto-col-' + column.dtoTemplate + '.eta', { column, mode: 'update' }) %>
63
62
  <% }); -%>
64
63
  <% it.associations.forEach((assoc) => { -%>
65
- <% if (assoc.type === 'ManyToOne' || (assoc.type === 'OneToOne' && assoc.isOwner)) { -%>
66
- <%= assoc.referenceName || assoc.name %>ID *<%= assoc.primaryKeyGoType || 'uint' %> `json:"<%= assoc.camelReferenceName || assoc.camelName %>Id,omitempty"`
64
+ <% if (assoc.owns) { -%>
65
+ <%= assoc.fkField %> *<%= assoc.primaryKeyGoType %> `json:"<%= assoc.camelReferenceName %>Id,omitempty"`
67
66
  <% } -%>
68
67
  <% }) -%>
69
68
  }
@@ -4,7 +4,9 @@ package handlers
4
4
 
5
5
  import (
6
6
  "net/http"
7
+ <% if (it.primaryKeyType !== 'uuid') { %>
7
8
  "strconv"
9
+ <% } %>
8
10
 
9
11
  "app/autogen/dto"
10
12
  "app/autogen/services"
@@ -5,13 +5,15 @@ package routes
5
5
  import (
6
6
  <% if (httpEntities.length > 0) { %> "app/autogen/handlers"
7
7
  <% } %><% if (it.hasAuth) { %> "app/autogen/middleware"
8
- <% } %> "app/autogen/services"
8
+ <% } %> "app/autogen/models"
9
+ "app/autogen/services"
9
10
  "github.com/gin-gonic/gin"
10
11
  "gorm.io/gorm"
11
12
  )
12
13
 
13
14
  // RegisterAllRoutes registers all entity routes
14
15
  func RegisterAllRoutes(r *gin.RouterGroup, db *gorm.DB) {
16
+ models.UseNames(db)
15
17
  <% if (it.hasAuth) { %>
16
18
  // Every route in this group requires authentication (.apsorc auth).
17
19
  r.Use(middleware.AuthMiddleware(db))
@@ -316,7 +316,7 @@ func AuthMiddleware(db *gorm.DB) gin.HandlerFunc {
316
316
  sum := sha256.Sum256([]byte(key))
317
317
  row := map[string]interface{}{}
318
318
  err := db.Model(&models.<%= it.apiKey.goModel %>{}).
319
- Where(<%~ JSON.stringify(it.apiKey.keyColumn + ' = ?') %>, hex.EncodeToString(sum[:])).
319
+ Where(<%~ JSON.stringify('"' + it.apiKey.keyColumn + '" = ?') %>, hex.EncodeToString(sum[:])).
320
320
  Take(&row).Error
321
321
  if err != nil {
322
322
  unauthorized(c, "Invalid API key")