@apso/cli 0.57.0 → 0.58.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.
@@ -1028,6 +1028,9 @@ is tracked separately.
1028
1028
  | deferrable | relationship | \`INITIALLY DEFERRED\` or \`INITIALLY IMMEDIATE\`: the key is DEFERRABLE and checked at commit or per statement. TypeScript only |
1029
1029
  | primary | relationship | The foreign key column is the entity's primary key. No \`id\` is generated. TypeScript only |
1030
1030
  | primaryKeyName | entity | The primary key constraint's name. TypeScript only |
1031
+ | primaryKeyType | entity | \`bigserial\` keeps a bigint id 64 bits wide (read and written as a string). TypeScript only |
1032
+ | primaryKeyDefault | entity | The SQL expression that fills a uuid id, or \`null\` when the column has no default and every create sends the id |
1033
+ | enumName | field | The Postgres enum type's own name instead of \`<table>_<column>_enum\`. Fields may share one. TypeScript only |
1031
1034
  | timestampType | entity | \`timestamp\` (default) or \`timestamptz\` for created_at and updated_at: one value, or \`{ "created_at": ..., "updated_at": ... }\` |
1032
1035
  | timestampNullable | entity | Whether created_at and updated_at accept NULL: one boolean, or one per column |
1033
1036
  | timestampDefault | entity | \`false\` when created_at or updated_at has no \`DEFAULT now()\`: one boolean, or one per column. Migrations honor it |
@@ -27,6 +27,8 @@ export interface AccessEntity {
27
27
  route: string;
28
28
  fields: NonNullable<Entity["fields"]>;
29
29
  payload: Row;
30
+ /** The uuid id has no default: each create body carries a new one. */
31
+ suppliesId?: boolean;
30
32
  /** Required foreign keys: property -> the entity it points to. */
31
33
  parents: {
32
34
  property: string;
@@ -105,6 +105,7 @@ function buildModel(entities, relationships, language, auth) {
105
105
  route: routeOf(language, entity.name),
106
106
  fields: (_c = entity.fields) !== null && _c !== void 0 ? _c : [],
107
107
  payload: planned.payload,
108
+ suppliesId: planned.suppliesId,
108
109
  parents: planned.parents,
109
110
  relations,
110
111
  scope,
@@ -131,6 +132,8 @@ const TEXT = new Set(["text", "string", "varchar"]);
131
132
  /** A create body for the nth row of an entity: text values differ per row so unique fields do not collide. */
132
133
  function payloadFor(entity, n) {
133
134
  const body = { ...entity.payload };
135
+ if (entity.suppliesId)
136
+ body.id = (0, crypto_1.randomUUID)();
134
137
  for (const field of entity.fields) {
135
138
  const value = body[field.name];
136
139
  if (typeof value !== "string")
@@ -217,6 +217,10 @@ function changeDdl(before, after, plan) {
217
217
  if (o.default !== undefined)
218
218
  up.push(`${at} DROP DEFAULT`);
219
219
  up.push(`${at} TYPE ${c.type} USING ${using}`);
220
+ // serial <-> bigserial: the sequence has its own type, and an integer
221
+ // sequence stops at 2147483647 under a bigint column.
222
+ if (o.serial && c.serial)
223
+ up.push(`ALTER SEQUENCE ${(0, _1.q)(`${t.name}_${c.name}_seq`)} AS ${c.type}`);
220
224
  if (c.default !== undefined)
221
225
  setNotNull.push(`${at} SET DEFAULT ${c.default}`);
222
226
  }
@@ -65,6 +65,7 @@ const NO_LITERAL_DEFAULT = new Set(["xml", "tsvector", "int4range"]);
65
65
  const generatedSql = (expression) => ` GENERATED ALWAYS AS (${expression}) STORED`;
66
66
  /** One column as its entity template declares it. */
67
67
  function columnSpec(table, f) {
68
+ var _a;
68
69
  const textLike = (type) => [
69
70
  type,
70
71
  quoted(f),
@@ -86,7 +87,7 @@ function columnSpec(table, f) {
86
87
  [type, def, unique] = textLike(`character(${size || 1})`);
87
88
  break;
88
89
  case "enum":
89
- type = `"public".${(0, exports.q)((0, exports.enumTypeName)(table, f.name))}`;
90
+ type = `"public".${(0, exports.q)((_a = f.enumName) !== null && _a !== void 0 ? _a : (0, exports.enumTypeName)(table, f.name))}`;
90
91
  def = quoted(f);
91
92
  break;
92
93
  case "integer":
@@ -185,7 +186,7 @@ exports.columnSpec = columnSpec;
185
186
  const cols = (c) => c.map((x) => (0, exports.q)(x)).join(", ");
186
187
  const column = (name, type, notNull, def, serial, generated) => ({
187
188
  name,
188
- sql: `${(0, exports.q)(name)} ${serial ? "SERIAL" : type}${generated ? generatedSql(generated) : ""}${notNull ? " NOT NULL" : ""}${def && !serial ? ` DEFAULT ${def}` : ""}`,
189
+ sql: `${(0, exports.q)(name)} ${serial ? (type === "bigint" ? "BIGSERIAL" : "SERIAL") : type}${generated ? generatedSql(generated) : ""}${notNull ? " NOT NULL" : ""}${def && !serial ? ` DEFAULT ${def}` : ""}`,
189
190
  type,
190
191
  notNull,
191
192
  default: def,
@@ -251,6 +252,9 @@ const keyColumn = (target, schema) => {
251
252
  return { sql: "uuid", options: 'type: "uuid"', ts: "string" };
252
253
  if ((target === null || target === void 0 ? void 0 : target.primaryKeyType) === "text")
253
254
  return { sql: "text", options: 'type: "text"', ts: "string" };
255
+ // TypeORM reads a bigint as a string, so no id loses digits in JavaScript.
256
+ if ((target === null || target === void 0 ? void 0 : target.primaryKeyType) === "bigserial")
257
+ return { sql: "bigint", options: 'type: "bigint"', ts: "string" };
254
258
  return { sql: "integer", options: 'type: "integer"', ts: "number" };
255
259
  };
256
260
  exports.keyColumn = keyColumn;
@@ -323,7 +327,7 @@ const joinTableOf = (e, r, target, schema) => {
323
327
  };
324
328
  exports.joinTableOf = joinTableOf;
325
329
  function schemaModel(input) {
326
- var _a, _b, _c, _d, _e, _f, _g, _h;
330
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
327
331
  const { entities, relationshipMap } = input;
328
332
  const byName = new Map(entities.map((e) => [e.name, e]));
329
333
  const model = {
@@ -395,15 +399,27 @@ function schemaModel(input) {
395
399
  const customPk = ((_a = e.fields) !== null && _a !== void 0 ? _a : []).some((f) => f.primary) || relationKeys.length > 0;
396
400
  if (!customPk) {
397
401
  const pkType = e.primaryKeyType || "serial";
398
- if (pkType === "uuid") {
399
- if (!e.primaryKeyDefault)
400
- model.extensions.push(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
401
- t.columns.push(column("id", "uuid", true, e.primaryKeyDefault || "uuid_generate_v4()"));
402
+ const serialId = (type) => column("id", type, true, `nextval('${table}_id_seq'::regclass)`, true);
403
+ switch (pkType) {
404
+ case "uuid":
405
+ // "primaryKeyDefault": null: the caller supplies every id.
406
+ if (e.primaryKeyDefault === null) {
407
+ t.columns.push(column("id", "uuid", true));
408
+ break;
409
+ }
410
+ if (!e.primaryKeyDefault)
411
+ model.extensions.push(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
412
+ t.columns.push(column("id", "uuid", true, e.primaryKeyDefault || "uuid_generate_v4()"));
413
+ break;
414
+ case "text":
415
+ t.columns.push(column("id", "text", true));
416
+ break;
417
+ case "bigserial":
418
+ t.columns.push(serialId("bigint"));
419
+ break;
420
+ default:
421
+ t.columns.push(serialId("integer"));
402
422
  }
403
- else if (pkType === "text")
404
- t.columns.push(column("id", "text", true));
405
- else
406
- t.columns.push(column("id", "integer", true, `nextval('${table}_id_seq'::regclass)`, true));
407
423
  }
408
424
  for (const stamp of ["created_at", "updated_at"])
409
425
  if (e[stamp])
@@ -417,11 +433,15 @@ function schemaModel(input) {
417
433
  continue;
418
434
  if (e.updated_at && f.name === "updated_at")
419
435
  continue;
420
- if (f.type === "enum" && f.values)
421
- model.enums.push({
422
- name: (0, exports.enumTypeName)(table, f.name),
423
- values: [...f.values],
424
- });
436
+ if (f.type === "enum" && f.values) {
437
+ const name = (_c = f.enumName) !== null && _c !== void 0 ? _c : (0, exports.enumTypeName)(table, f.name);
438
+ // Two fields may share one named type; it is created once.
439
+ const shared = model.enums.find((x) => x.name === name);
440
+ if (!shared)
441
+ model.enums.push({ name, values: [...f.values] });
442
+ else if (shared.values.join("\u0000") !== f.values.join("\u0000"))
443
+ throw new Error(`${e.name}.${f.name} uses the enum type "${name}" with values that differ from another field of that type. Fields that share "enumName" must list the same values in the same order.`);
444
+ }
425
445
  const spec = columnSpec(table, f);
426
446
  t.columns.push(column(f.name, spec.type, spec.notNull, spec.default, false, spec.generated));
427
447
  if (spec.unique)
@@ -434,9 +454,9 @@ function schemaModel(input) {
434
454
  const columnByName = (0, exports.relationColumns)(relationships);
435
455
  for (const c of t.columns)
436
456
  columnByName.set(c.name, c.name);
437
- for (const i of (_c = e.indexes) !== null && _c !== void 0 ? _c : [])
457
+ for (const i of (_d = e.indexes) !== null && _d !== void 0 ? _d : [])
438
458
  index(table, i.fields.map((f) => { var _a; return (_a = columnByName.get(f)) !== null && _a !== void 0 ? _a : f; }), i.unique, i.name, i.where);
439
- for (const i of (_d = e.sqlIndexes) !== null && _d !== void 0 ? _d : [])
459
+ for (const i of (_e = e.sqlIndexes) !== null && _e !== void 0 ? _e : [])
440
460
  model.indexes.push({
441
461
  key: `sqlindex:${table}:${i.name}(${i.columns})${i.where ? ` where ${i.where}` : ""}`,
442
462
  name: i.name,
@@ -446,7 +466,7 @@ function schemaModel(input) {
446
466
  unique: Boolean(i.unique),
447
467
  ...(i.where && { where: i.where }),
448
468
  });
449
- for (const c of (_e = e.checks) !== null && _e !== void 0 ? _e : []) {
469
+ for (const c of (_f = e.checks) !== null && _f !== void 0 ? _f : []) {
450
470
  const name = c.name || exports.constraintName.check(table, c.expression);
451
471
  // NOT VALID is allowed only on a constraint added by ALTER TABLE.
452
472
  const late = c.validate === false;
@@ -461,7 +481,7 @@ function schemaModel(input) {
461
481
  ...(late && { late }),
462
482
  });
463
483
  }
464
- for (const u of (_f = e.uniques) !== null && _f !== void 0 ? _f : []) {
484
+ for (const u of (_g = e.uniques) !== null && _g !== void 0 ? _g : []) {
465
485
  const columns = u.fields.map((f) => { var _a; return (_a = columnByName.get(f)) !== null && _a !== void 0 ? _a : f; });
466
486
  unique(table, columns, u.name || exports.constraintName.unique(table, columns));
467
487
  }
@@ -472,7 +492,7 @@ function schemaModel(input) {
472
492
  const targetTable = (0, exports.tableName)(target);
473
493
  // The template gives OneToOne onDelete CASCADE and a nullable join column.
474
494
  const oneToOne = r.type === "OneToOne";
475
- const onDelete = oneToOne ? "CASCADE" : (_g = (0, relationship_1.onDeleteOf)(r)) !== null && _g !== void 0 ? _g : "NO ACTION";
495
+ const onDelete = oneToOne ? "CASCADE" : (_h = (0, relationship_1.onDeleteOf)(r)) !== null && _h !== void 0 ? _h : "NO ACTION";
476
496
  if (r.type === "ManyToOne" || (oneToOne && r.joinTable)) {
477
497
  const col = (0, exports.relationColumn)(r);
478
498
  t.columns.push(column(col, (0, exports.fkType)(target, input), !(r.nullable || oneToOne), r.joinColumnDefault));
@@ -511,7 +531,7 @@ function schemaModel(input) {
511
531
  }
512
532
  const keyColumns = customPk
513
533
  ? [
514
- ...((_h = e.fields) !== null && _h !== void 0 ? _h : []).filter((f) => f.primary).map((f) => f.name),
534
+ ...((_j = e.fields) !== null && _j !== void 0 ? _j : []).filter((f) => f.primary).map((f) => f.name),
515
535
  ...relationKeys,
516
536
  ]
517
537
  : ["id"];
@@ -19,6 +19,10 @@ function checkPkStrategy(ctx) {
19
19
  for (const entity of ctx.entities) {
20
20
  if (entity.primaryKeyType !== "uuid")
21
21
  continue;
22
+ // "primaryKeyDefault" picks the default (or none, when null); the entity
23
+ // then uses @PrimaryColumn on purpose.
24
+ if (entity.primaryKeyDefault !== undefined)
25
+ continue;
22
26
  // Check if any field is explicitly marked as primary (custom PK)
23
27
  const hasCustomPk = (_b = (_a = entity.fields) === null || _a === void 0 ? void 0 : _a.some((f) => f.primary)) !== null && _b !== void 0 ? _b : false;
24
28
  if (hasCustomPk)
@@ -121,7 +121,7 @@ class GoGenerator extends base_1.BaseGenerator {
121
121
  return ".go";
122
122
  }
123
123
  validateConfig(config) {
124
- var _a, _b, _c, _d, _e, _f, _g;
124
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
125
125
  const errors = [];
126
126
  const warnings = [];
127
127
  // Validate that entities are provided
@@ -137,7 +137,16 @@ class GoGenerator extends base_1.BaseGenerator {
137
137
  for (const e of (_d = config.entities) !== null && _d !== void 0 ? _d : [])
138
138
  if ((_e = e.foreignKeys) === null || _e === void 0 ? void 0 : _e.length)
139
139
  errors.push(`${e.name} sets "foreignKeys". The Go generator cannot declare a second foreign key on a column yet; remove it or generate a TypeScript service.`);
140
- for (const e of (_f = config.entities) !== null && _f !== void 0 ? _f : [])
140
+ for (const e of (_f = config.entities) !== null && _f !== void 0 ? _f : []) {
141
+ if (e.primaryKeyType === "bigserial")
142
+ errors.push(`${e.name} sets "primaryKeyType": "bigserial". The Go generator cannot make a bigint id yet; remove it or generate a TypeScript service.`);
143
+ if (e.primaryKeyDefault === null)
144
+ errors.push(`${e.name} sets "primaryKeyDefault": null. The Go generator cannot make a uuid id without a default yet; remove it or generate a TypeScript service.`);
145
+ for (const f of (_g = e.fields) !== null && _g !== void 0 ? _g : [])
146
+ if (f.enumName)
147
+ errors.push(`${e.name}.${f.name} sets "enumName". The Go generator cannot keep an enum type's name yet; remove it or generate a TypeScript service.`);
148
+ }
149
+ for (const e of (_h = config.entities) !== null && _h !== void 0 ? _h : [])
141
150
  if (e.primaryKeyName)
142
151
  errors.push(`${e.name} sets "primaryKeyName": "${e.primaryKeyName}". The Go generator cannot keep a custom primary key constraint name yet; remove it or generate a TypeScript service.`);
143
152
  // Validate each entity
@@ -146,7 +155,7 @@ class GoGenerator extends base_1.BaseGenerator {
146
155
  errors.push("Entity missing required 'name' property");
147
156
  }
148
157
  // Validate field types
149
- for (const field of (_g = entity.fields) !== null && _g !== void 0 ? _g : []) {
158
+ for (const field of (_j = entity.fields) !== null && _j !== void 0 ? _j : []) {
150
159
  if (!field.name) {
151
160
  errors.push(`Entity '${entity.name}' has a field without a name`);
152
161
  }
@@ -143,7 +143,7 @@ class PythonGenerator extends base_1.BaseGenerator {
143
143
  return ".py";
144
144
  }
145
145
  validateConfig(config) {
146
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
146
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
147
147
  const errors = [];
148
148
  const warnings = [];
149
149
  // Validate that entities are provided
@@ -162,7 +162,16 @@ class PythonGenerator extends base_1.BaseGenerator {
162
162
  for (const e of (_f = config.entities) !== null && _f !== void 0 ? _f : [])
163
163
  if ((_g = e.foreignKeys) === null || _g === void 0 ? void 0 : _g.length)
164
164
  errors.push(`${e.name} sets "foreignKeys". The Python generator cannot declare a second foreign key on a column yet; remove it or generate a TypeScript service.`);
165
- for (const e of (_h = config.entities) !== null && _h !== void 0 ? _h : [])
165
+ for (const e of (_h = config.entities) !== null && _h !== void 0 ? _h : []) {
166
+ if (e.primaryKeyType === "bigserial")
167
+ errors.push(`${e.name} sets "primaryKeyType": "bigserial". The Python generator cannot make a bigint id yet; remove it or generate a TypeScript service.`);
168
+ if (e.primaryKeyDefault === null)
169
+ errors.push(`${e.name} sets "primaryKeyDefault": null. The Python generator cannot make a uuid id without a default yet; remove it or generate a TypeScript service.`);
170
+ for (const f of (_j = e.fields) !== null && _j !== void 0 ? _j : [])
171
+ if (f.enumName)
172
+ errors.push(`${e.name}.${f.name} sets "enumName". The Python generator cannot keep an enum type's name yet; remove it or generate a TypeScript service.`);
173
+ }
174
+ for (const e of (_k = config.entities) !== null && _k !== void 0 ? _k : [])
166
175
  if (e.primaryKeyName)
167
176
  errors.push(`${e.name} sets "primaryKeyName": "${e.primaryKeyName}". The Python generator cannot keep a custom primary key constraint name yet; remove it or generate a TypeScript service.`);
168
177
  // Validate each entity
@@ -171,7 +180,7 @@ class PythonGenerator extends base_1.BaseGenerator {
171
180
  errors.push("Entity missing required 'name' property");
172
181
  }
173
182
  // Validate field types
174
- for (const field of (_j = entity.fields) !== null && _j !== void 0 ? _j : []) {
183
+ for (const field of (_l = entity.fields) !== null && _l !== void 0 ? _l : []) {
175
184
  if (!field.name) {
176
185
  errors.push(`Entity '${entity.name}' has a field without a name`);
177
186
  }
@@ -11,6 +11,11 @@
11
11
  * - target table name = snakeCase(entity name) = snakeCase(source table name)
12
12
  * - single-column FK = renamed to the platform's camelCase `<ref>Id`
13
13
  * - every other column = copied under its original name
14
+ *
15
+ * Values travel as the text Postgres prints for them and are parsed again by
16
+ * the target column, so an array, a timestamp's microseconds, an interval or a
17
+ * bytea arrive as they left. Reading them into JavaScript values first lost
18
+ * the microseconds and broke every array column.
14
19
  */
15
20
  import { IntrospectedSchema, IntrospectedTable } from "./types";
16
21
  export interface ColumnMapping {
@@ -24,6 +29,8 @@ export interface TableCopyPlan {
24
29
  sourceColumns: string[];
25
30
  /** Target column names, parallel to sourceColumns. */
26
31
  targetColumns: string[];
32
+ /** The SQL that reads each source column as text, parallel to sourceColumns. */
33
+ sourceExpressions?: string[];
27
34
  /** Source PK column used to order paged reads (null when there is no PK). */
28
35
  orderBy: string | null;
29
36
  /** Target PK column whose sequence to reset after copy (null if not serial). */
@@ -60,9 +67,18 @@ export declare function topoSortTables(tables: IntrospectedTable[]): {
60
67
  * column is missing are dropped (and reported); source tables with no target
61
68
  * table are skipped entirely.
62
69
  */
63
- export declare function planCopy(source: IntrospectedSchema, targetColumnsByTable: Map<string, Set<string>>, tableFilter?: string[]): CopyPlan;
64
- /** Coerce a value read from pg into something safe to bind on insert. */
70
+ export declare function planCopy(source: IntrospectedSchema, targetColumnsByTable: Map<string, Set<string> | Map<string, string>>, tableFilter?: string[]): CopyPlan;
71
+ /**
72
+ * Coerce a value into something safe to bind on insert. The copy reads every
73
+ * column as text, so it sees strings and nulls; the other branches serve a
74
+ * reader that returns JavaScript values.
75
+ */
65
76
  export declare function coerceValue(value: unknown): unknown;
77
+ /**
78
+ * Build the paged SELECT that reads a batch of source rows. Each column comes
79
+ * back under its own name; `expressions` says how to read it.
80
+ */
81
+ export declare function buildSelectSql(table: string, columns: string[], orderBy: string | null, schema?: string, expressions?: string[]): string;
66
82
  /** Build a parameterized multi-row INSERT statement for a batch. */
67
83
  export declare function buildInsertSql(table: string, columns: string[], rows: unknown[][], schema?: string): {
68
84
  text: string;
@@ -70,7 +86,9 @@ export declare function buildInsertSql(table: string, columns: string[], rows: u
70
86
  };
71
87
  export interface SourceReader {
72
88
  totalRows(table: string): Promise<number>;
73
- readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number): Promise<unknown[][]>;
89
+ readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number,
90
+ /** The SQL that reads each column, parallel to columns. Defaults to the column itself. */
91
+ expressions?: string[]): Promise<unknown[][]>;
74
92
  }
75
93
  export interface TargetWriter {
76
94
  rowCount(table: string): Promise<number>;
@@ -102,5 +120,5 @@ export interface ExecuteOptions {
102
120
  * on the target, so a failure rolls everything back.
103
121
  */
104
122
  export declare function executeCopy(plan: CopyPlan, source: SourceReader, target: TargetWriter, options?: ExecuteOptions): Promise<CopyResult>;
105
- /** Build the target column lookup used by planCopy from an introspected target. */
106
- export declare function targetColumnsFromSchema(target: IntrospectedSchema): Map<string, Set<string>>;
123
+ /** Build the target lookup used by planCopy from an introspected target: each table's columns and their types. */
124
+ export declare function targetColumnsFromSchema(target: IntrospectedSchema): Map<string, Map<string, string>>;
@@ -12,9 +12,14 @@
12
12
  * - target table name = snakeCase(entity name) = snakeCase(source table name)
13
13
  * - single-column FK = renamed to the platform's camelCase `<ref>Id`
14
14
  * - every other column = copied under its original name
15
+ *
16
+ * Values travel as the text Postgres prints for them and are parsed again by
17
+ * the target column, so an array, a timestamp's microseconds, an interval or a
18
+ * bytea arrive as they left. Reading them into JavaScript values first lost
19
+ * the microseconds and broke every array column.
15
20
  */
16
21
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.targetColumnsFromSchema = exports.executeCopy = exports.buildInsertSql = exports.coerceValue = exports.planCopy = exports.topoSortTables = exports.buildColumnMapping = exports.targetTableName = void 0;
22
+ exports.targetColumnsFromSchema = exports.executeCopy = exports.buildInsertSql = exports.buildSelectSql = exports.coerceValue = exports.planCopy = exports.topoSortTables = exports.buildColumnMapping = exports.targetTableName = void 0;
18
23
  const casing_1 = require("../utils/casing");
19
24
  const relationships_1 = require("../utils/relationships");
20
25
  const pg_to_apsorc_1 = require("./pg-to-apsorc");
@@ -98,7 +103,7 @@ exports.topoSortTables = topoSortTables;
98
103
  * table are skipped entirely.
99
104
  */
100
105
  function planCopy(source, targetColumnsByTable, tableFilter) {
101
- var _a;
106
+ var _a, _b;
102
107
  const filter = tableFilter && tableFilter.length > 0 ? new Set(tableFilter) : null;
103
108
  const consideredTables = source.tables.filter((t) => !filter || filter.has(t.name));
104
109
  const { order, cyclic } = topoSortTables(consideredTables);
@@ -117,6 +122,8 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
117
122
  const mapping = buildColumnMapping(table);
118
123
  const keptSource = [];
119
124
  const keptTarget = [];
125
+ const expressions = [];
126
+ const sourceTypes = new Map(table.columns.map((c) => [c.name, c.udtName]));
120
127
  for (const m of mapping) {
121
128
  // An import keeps foreign key column names ("joinColumnName"); a project
122
129
  // imported by an older CLI has the generated camelCase name instead.
@@ -125,6 +132,14 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
125
132
  if (targetColumns.has(m.targetColumn)) {
126
133
  keptSource.push(m.sourceColumn);
127
134
  keptTarget.push(m.targetColumn);
135
+ // An array whose target column is json (the field was changed to
136
+ // jsonb after the import) is sent as a JSON array.
137
+ const targetType = targetColumns instanceof Map ? targetColumns.get(m.targetColumn) : "";
138
+ const arrayToJson = ((_a = sourceTypes.get(m.sourceColumn)) === null || _a === void 0 ? void 0 : _a.startsWith("_")) &&
139
+ (targetType === "json" || targetType === "jsonb");
140
+ expressions.push(arrayToJson
141
+ ? `to_jsonb("${m.sourceColumn}")::text`
142
+ : `"${m.sourceColumn}"::text`);
128
143
  }
129
144
  else {
130
145
  skippedColumns.push({
@@ -141,7 +156,7 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
141
156
  const pkCol = table.primaryKey[0];
142
157
  orderBy = pkCol;
143
158
  const pk = table.columns.find((c) => c.name === pkCol);
144
- const targetPk = (_a = mapping.find((m) => m.sourceColumn === pkCol)) === null || _a === void 0 ? void 0 : _a.targetColumn;
159
+ const targetPk = (_b = mapping.find((m) => m.sourceColumn === pkCol)) === null || _b === void 0 ? void 0 : _b.targetColumn;
145
160
  if (pk && targetPk && INTEGER_PK_UDTS.has(pk.udtName)) {
146
161
  serialPkColumn = targetPk;
147
162
  }
@@ -151,6 +166,7 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
151
166
  targetTable,
152
167
  sourceColumns: keptSource,
153
168
  targetColumns: keptTarget,
169
+ sourceExpressions: expressions,
154
170
  orderBy,
155
171
  serialPkColumn,
156
172
  });
@@ -158,7 +174,11 @@ function planCopy(source, targetColumnsByTable, tableFilter) {
158
174
  return { tables, skippedColumns, missingTargetTables, cyclicTables: cyclic };
159
175
  }
160
176
  exports.planCopy = planCopy;
161
- /** Coerce a value read from pg into something safe to bind on insert. */
177
+ /**
178
+ * Coerce a value into something safe to bind on insert. The copy reads every
179
+ * column as text, so it sees strings and nulls; the other branches serve a
180
+ * reader that returns JavaScript values.
181
+ */
162
182
  function coerceValue(value) {
163
183
  if (value === null || value === undefined)
164
184
  return null;
@@ -171,6 +191,21 @@ function coerceValue(value) {
171
191
  return value;
172
192
  }
173
193
  exports.coerceValue = coerceValue;
194
+ /**
195
+ * Build the paged SELECT that reads a batch of source rows. Each column comes
196
+ * back under its own name; `expressions` says how to read it.
197
+ */
198
+ function buildSelectSql(table, columns, orderBy, schema, expressions) {
199
+ const tableRef = schema ? `"${schema}"."${table}"` : `"${table}"`;
200
+ const cols = columns
201
+ .map((c, i) => { var _a; return `${(_a = expressions === null || expressions === void 0 ? void 0 : expressions[i]) !== null && _a !== void 0 ? _a : `"${c}"`} AS "${c}"`; })
202
+ .join(", ");
203
+ // Qualified, so the order is the column's own (and its index is used), not
204
+ // the text alias of the same name: as text, id 10 sorts before id 9.
205
+ const order = orderBy ? ` ORDER BY ${tableRef}."${orderBy}"` : "";
206
+ return `SELECT ${cols} FROM ${tableRef}${order} OFFSET $1 LIMIT $2`;
207
+ }
208
+ exports.buildSelectSql = buildSelectSql;
174
209
  /** Build a parameterized multi-row INSERT statement for a batch. */
175
210
  function buildInsertSql(table, columns, rows, schema) {
176
211
  const tableRef = schema ? `"${schema}"."${table}"` : `"${table}"`;
@@ -233,7 +268,7 @@ async function executeCopy(plan, source, target, options = {}) {
233
268
  // eslint-disable-next-line no-constant-condition
234
269
  while (true) {
235
270
  // eslint-disable-next-line no-await-in-loop
236
- const rows = await source.readBatch(t.sourceTable, t.sourceColumns, t.orderBy, offset, batchSize);
271
+ const rows = await source.readBatch(t.sourceTable, t.sourceColumns, t.orderBy, offset, batchSize, t.sourceExpressions);
237
272
  if (rows.length === 0)
238
273
  break;
239
274
  // eslint-disable-next-line no-await-in-loop
@@ -265,8 +300,11 @@ async function executeCopy(plan, source, target, options = {}) {
265
300
  };
266
301
  }
267
302
  exports.executeCopy = executeCopy;
268
- /** Build the target column lookup used by planCopy from an introspected target. */
303
+ /** Build the target lookup used by planCopy from an introspected target: each table's columns and their types. */
269
304
  function targetColumnsFromSchema(target) {
270
- return new Map(target.tables.map((t) => [t.name, new Set(t.columns.map((c) => c.name))]));
305
+ return new Map(target.tables.map((t) => [
306
+ t.name,
307
+ new Map(t.columns.map((c) => [c.name, c.udtName])),
308
+ ]));
271
309
  }
272
310
  exports.targetColumnsFromSchema = targetColumnsFromSchema;
@@ -2,6 +2,6 @@ export * from "./types";
2
2
  export { pgToApsorc, findUnknownEmittedTypes } from "./pg-to-apsorc";
3
3
  export type { ApsorcImportOutput, ApsorcImportEntityOutput, ApsorcImportFieldOutput, ApsorcImportRelationshipOutput, } from "./pg-to-apsorc";
4
4
  export { PgIntrospector, redactConnectionString, buildSchema, SYSTEM_SCHEMAS } from "./introspect";
5
- export { planCopy, executeCopy, buildColumnMapping, topoSortTables, targetTableName, targetColumnsFromSchema, buildInsertSql, coerceValue, } from "./copy-data";
5
+ export { planCopy, executeCopy, buildColumnMapping, topoSortTables, targetTableName, targetColumnsFromSchema, buildInsertSql, buildSelectSql, coerceValue, } from "./copy-data";
6
6
  export type { CopyPlan, CopyResult, TableCopyPlan, ColumnMapping, SourceReader, TargetWriter, ExecuteOptions, } from "./copy-data";
7
7
  export { PgSourceReader, PgTargetWriter } from "./pg-data";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PgTargetWriter = exports.PgSourceReader = exports.coerceValue = exports.buildInsertSql = exports.targetColumnsFromSchema = exports.targetTableName = exports.topoSortTables = exports.buildColumnMapping = exports.executeCopy = exports.planCopy = exports.SYSTEM_SCHEMAS = exports.buildSchema = exports.redactConnectionString = exports.PgIntrospector = exports.findUnknownEmittedTypes = exports.pgToApsorc = void 0;
3
+ exports.PgTargetWriter = exports.PgSourceReader = exports.coerceValue = exports.buildSelectSql = exports.buildInsertSql = exports.targetColumnsFromSchema = exports.targetTableName = exports.topoSortTables = exports.buildColumnMapping = exports.executeCopy = exports.planCopy = exports.SYSTEM_SCHEMAS = exports.buildSchema = exports.redactConnectionString = exports.PgIntrospector = exports.findUnknownEmittedTypes = exports.pgToApsorc = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  tslib_1.__exportStar(require("./types"), exports);
6
6
  var pg_to_apsorc_1 = require("./pg-to-apsorc");
@@ -19,6 +19,7 @@ Object.defineProperty(exports, "topoSortTables", { enumerable: true, get: functi
19
19
  Object.defineProperty(exports, "targetTableName", { enumerable: true, get: function () { return copy_data_1.targetTableName; } });
20
20
  Object.defineProperty(exports, "targetColumnsFromSchema", { enumerable: true, get: function () { return copy_data_1.targetColumnsFromSchema; } });
21
21
  Object.defineProperty(exports, "buildInsertSql", { enumerable: true, get: function () { return copy_data_1.buildInsertSql; } });
22
+ Object.defineProperty(exports, "buildSelectSql", { enumerable: true, get: function () { return copy_data_1.buildSelectSql; } });
22
23
  Object.defineProperty(exports, "coerceValue", { enumerable: true, get: function () { return copy_data_1.coerceValue; } });
23
24
  var pg_data_1 = require("./pg-data");
24
25
  Object.defineProperty(exports, "PgSourceReader", { enumerable: true, get: function () { return pg_data_1.PgSourceReader; } });
@@ -14,7 +14,7 @@ export declare class PgSourceReader implements SourceReader {
14
14
  private constructor();
15
15
  static connect(connectionString: string, schema: string): Promise<PgSourceReader>;
16
16
  totalRows(table: string): Promise<number>;
17
- readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number): Promise<unknown[][]>;
17
+ readBatch(table: string, columns: string[], orderBy: string | null, offset: number, limit: number, expressions?: string[]): Promise<unknown[][]>;
18
18
  close(): Promise<void>;
19
19
  }
20
20
  /** Writes rows into the target database within a single transaction. */
@@ -53,16 +53,21 @@ class PgSourceReader {
53
53
  this.schema = schema;
54
54
  }
55
55
  static async connect(connectionString, schema) {
56
- return new PgSourceReader(await createClient(connectionString), schema);
56
+ const client = await createClient(connectionString);
57
+ // Values are read as text, so the text must mean the same on the target:
58
+ // ISO dates whatever the source's DateStyle (with "SQL, DMY" the day and
59
+ // month would swap), and every digit of a float.
60
+ await client.query("SET datestyle = 'ISO'");
61
+ await client.query("SET extra_float_digits = 3");
62
+ return new PgSourceReader(client, schema);
57
63
  }
58
64
  async totalRows(table) {
59
65
  const res = await this.client.query(`SELECT count(*)::int AS n FROM ${qualified(this.schema, table)}`);
60
66
  return res.rows[0].n;
61
67
  }
62
- async readBatch(table, columns, orderBy, offset, limit) {
63
- const cols = columns.map((c) => `"${c}"`).join(", ");
64
- const order = orderBy ? ` ORDER BY "${orderBy}"` : "";
65
- const res = await this.client.query(`SELECT ${cols} FROM ${qualified(this.schema, table)}${order} OFFSET $1 LIMIT $2`, [offset, limit]);
68
+ async readBatch(table, columns, orderBy, offset, limit, expressions) {
69
+ const { buildSelectSql } = await Promise.resolve().then(() => __importStar(require("./copy-data")));
70
+ const res = await this.client.query(buildSelectSql(table, columns, orderBy, this.schema, expressions), [offset, limit]);
66
71
  return res.rows.map((row) => columns.map((c) => row[c]));
67
72
  }
68
73
  async close() {
@@ -24,6 +24,7 @@ export interface ApsorcImportFieldOutput {
24
24
  generated?: string;
25
25
  index?: boolean;
26
26
  values?: string[];
27
+ enumName?: string;
27
28
  length?: number;
28
29
  precision?: number;
29
30
  scale?: number;
@@ -32,9 +33,9 @@ export interface ApsorcImportFieldOutput {
32
33
  }
33
34
  export interface ApsorcImportEntityOutput {
34
35
  name: string;
35
- primaryKeyType?: "serial" | "uuid" | "text";
36
+ primaryKeyType?: "serial" | "bigserial" | "uuid" | "text";
36
37
  primaryKeyName?: string;
37
- primaryKeyDefault?: string;
38
+ primaryKeyDefault?: string | null;
38
39
  created_at?: boolean;
39
40
  updated_at?: boolean;
40
41
  timestampType?: Entity["timestampType"];
@@ -324,12 +324,18 @@ function pgToApsorc(schema) {
324
324
  const t = pgTypeToApsorcType(pkCol).type;
325
325
  // A varchar(n) or char(n) id is kept as a primary field, so its
326
326
  // length and the columns that reference it keep theirs.
327
- // integer/bigint/smallint id => default serial, omit primaryKeyType.
327
+ // integer/smallint id => default serial, omit primaryKeyType. A
328
+ // bigint id stays 64 bits wide.
328
329
  if (t === "uuid" || t === "text")
329
330
  entity.primaryKeyType = t;
330
- // The generated uuid id uses uuid_generate_v4(); keep another function.
331
+ else if (t === "bigint")
332
+ entity.primaryKeyType = "bigserial";
333
+ // The generated uuid id uses uuid_generate_v4(); keep another
334
+ // function, and keep "no default" (the caller supplies the id).
331
335
  const idDefault = (_a = pkCol.default) === null || _a === void 0 ? void 0 : _a.trim();
332
- if (t === "uuid" && idDefault && idDefault !== "uuid_generate_v4()")
336
+ if (t === "uuid" && !idDefault)
337
+ entity.primaryKeyDefault = null;
338
+ else if (t === "uuid" && idDefault !== "uuid_generate_v4()")
333
339
  entity.primaryKeyDefault = idDefault;
334
340
  else
335
341
  pkAsField = t === "varchar" || t === "char";
@@ -492,15 +498,22 @@ function pgToApsorc(schema) {
492
498
  : undefined;
493
499
  if (labels)
494
500
  field.values = labels;
501
+ // Always stated: the name TypeORM derives folds the column's case,
502
+ // and two columns may share one type.
503
+ if (col.enumTypeName && field_1.ENUM_NAME.test(col.enumTypeName))
504
+ field.enumName = col.enumTypeName;
495
505
  }
496
506
  // Defaults (skip for PK columns — those are implicit/sequence-driven).
497
507
  if (!(pkSet.has(col.name) && !pkAsField) && !col.generated) {
498
508
  const parsed = parseDefault(col.default, resolved.type);
499
509
  const literal = "value" in parsed && LITERAL_DEFAULT_TYPES.has(resolved.type);
500
510
  if (col.default === null) {
501
- // A boolean field gets DEFAULT false unless it says otherwise.
511
+ // A boolean field gets DEFAULT false unless it says otherwise, and
512
+ // an enum field its first value unless its default is null.
502
513
  if (resolved.type === "boolean")
503
514
  field.noDefault = true;
515
+ else if (resolved.type === "enum")
516
+ field.default = null;
504
517
  }
505
518
  else if (col.default.trim().toLowerCase().startsWith("nextval(")) {
506
519
  // A sequence .apsorc does not create.
@@ -78,14 +78,18 @@ function buildEntityClasses(entities, relationshipMap = {}) {
78
78
  const hasCustomPk = (_b = (_a = entityDef.fields) === null || _a === void 0 ? void 0 : _a.some((f) => f.primary)) !== null && _b !== void 0 ? _b : false;
79
79
  const pkType = entityDef.primaryKeyType || "serial";
80
80
  if (!hasCustomPk) {
81
- if (pkType === "uuid") {
82
- typeorm.PrimaryColumn({ type: "uuid" })(EntityClass.prototype, "id");
83
- }
84
- else if (pkType === "text") {
85
- typeorm.PrimaryColumn({ type: "text" })(EntityClass.prototype, "id");
86
- }
87
- else {
88
- typeorm.PrimaryGeneratedColumn()(EntityClass.prototype, "id");
81
+ switch (pkType) {
82
+ case "uuid":
83
+ typeorm.PrimaryColumn({ type: "uuid" })(EntityClass.prototype, "id");
84
+ break;
85
+ case "text":
86
+ typeorm.PrimaryColumn({ type: "text" })(EntityClass.prototype, "id");
87
+ break;
88
+ case "bigserial":
89
+ typeorm.PrimaryGeneratedColumn({ type: "bigint" })(EntityClass.prototype, "id");
90
+ break;
91
+ default:
92
+ typeorm.PrimaryGeneratedColumn()(EntityClass.prototype, "id");
89
93
  }
90
94
  }
91
95
  if (entityDef.created_at) {
@@ -121,6 +125,8 @@ function buildEntityClasses(entities, relationshipMap = {}) {
121
125
  }
122
126
  if (field.type === "enum" && field.values) {
123
127
  colOpts.enum = field.values;
128
+ if (field.enumName)
129
+ colOpts.enumName = field.enumName;
124
130
  }
125
131
  if (((_c = field.length) !== null && _c !== void 0 ? _c : 0) > 0)
126
132
  colOpts.length = field.length;
@@ -171,7 +171,7 @@ function planMigration(before, after, previous) {
171
171
  }
172
172
  if (old.nullable &&
173
173
  !cur.nullable &&
174
- cur.default === undefined &&
174
+ (cur.default === undefined || cur.default === null) &&
175
175
  !cur.generated) {
176
176
  questions.push({
177
177
  id: `backfill:${now.name}.${old.name}`,
@@ -226,7 +226,7 @@ function planMigration(before, after, previous) {
226
226
  for (const f of fieldsOf(now)) {
227
227
  if (byName(fieldsOf(was), f.name) ||
228
228
  f.nullable ||
229
- f.default !== undefined ||
229
+ (f.default !== undefined && f.default !== null) ||
230
230
  // Postgres computes a generated column for the existing rows.
231
231
  f.generated)
232
232
  continue;
@@ -3,7 +3,8 @@
3
3
  @Column({
4
4
  type: 'enum',
5
5
  nullable: <%= Boolean(field.nullable) %>,
6
- enum: enums.<%= field.dataType%><% if (field.default !== null) { %>,
6
+ enum: enums.<%= field.dataType%><% if (field.enumName) { %>,
7
+ enumName: <%~ JSON.stringify(field.enumName) %><% } %><% if (field.default !== null) { %>,
7
8
  default: enums.<%= field.dataType%>.<%= field.default.toLowerCase().replace(/[^a-z0-9]/g, '_').replace(/^(\d)/, '_$1').replace(/_+/g, '_').replace(/_$/, '') %><% } %>
8
9
  })
9
10
  <% if (field.index ) {%>
@@ -70,7 +70,13 @@ const { CREATE, UPDATE } = CrudValidationGroups;
70
70
  export class <%= it.name %> {
71
71
  <% if (it.createPrimaryKey) { %>
72
72
  // Fields
73
- <% if (it.primaryKeyType === 'uuid') { %>
73
+ <% if (it.primaryKeyType === 'uuid' && it.primaryKeyDefault === null) { %>
74
+ @PrimaryColumn({ type: 'uuid'<% if (it.primaryKeyName) { %>, primaryKeyConstraintName: '<%= it.primaryKeyName %>'<% } %> })
75
+ id: string;
76
+ <% } else if (it.primaryKeyType === 'bigserial') { %>
77
+ @PrimaryGeneratedColumn({ type: 'bigint'<% if (it.primaryKeyName) { %>, primaryKeyConstraintName: '<%= it.primaryKeyName %>'<% } %> })
78
+ id!: string;
79
+ <% } else if (it.primaryKeyType === 'uuid') { %>
74
80
  <% if (it.primaryKeyDefault) { %>
75
81
  @PrimaryColumn({ type: 'uuid', default: () => <%~ JSON.stringify(it.primaryKeyDefault) %><% if (it.primaryKeyName) { %>, primaryKeyConstraintName: '<%= it.primaryKeyName %>'<% } %> })
76
82
  <% if (it.primaryKeyGenerated) { %>
@@ -177,7 +177,7 @@ export class <%= it.entityName %>Update {
177
177
  export class <%= it.entityName %> {
178
178
  <% if (it.addDefaultPKProperty) { %>
179
179
  @ApiProperty()
180
- id: <%= (it.primaryKeyType === 'uuid' || it.primaryKeyType === 'text') ? 'string' : 'number' %>;
180
+ id: <%= (it.primaryKeyType === 'uuid' || it.primaryKeyType === 'text' || it.primaryKeyType === 'bigserial') ? 'string' : 'number' %>;
181
181
 
182
182
  <% } -%>
183
183
  <% it.columns.forEach((field) => { -%>
@@ -80,7 +80,12 @@ export interface Entity {
80
80
  * column has none.
81
81
  */
82
82
  timestampDefault?: boolean | Partial<Record<TimestampColumn, boolean>>;
83
- primaryKeyType?: "serial" | "uuid";
83
+ /**
84
+ * Type of the generated id: "serial" (integer with a sequence, the default),
85
+ * "bigserial" (bigint with a sequence), "uuid" or "text". `apso import`
86
+ * writes "bigserial" for a bigint id so no id is narrowed to 32 bits.
87
+ */
88
+ primaryKeyType?: "serial" | "bigserial" | "uuid" | "text";
84
89
  /**
85
90
  * Name of the primary key constraint. Defaults to the name TypeORM derives.
86
91
  * `apso import` sets it so an existing database keeps its constraint names.
@@ -90,7 +95,7 @@ export interface Entity {
90
95
  * SQL expression that fills a uuid "id", for example "gen_random_uuid()".
91
96
  * Defaults to uuid_generate_v4() from the uuid-ossp extension.
92
97
  */
93
- primaryKeyDefault?: string;
98
+ primaryKeyDefault?: string | null;
94
99
  fields?: Field[];
95
100
  indexes?: Index[];
96
101
  /** Indexes on an expression or a descending column. */
@@ -27,6 +27,12 @@ export interface Field {
27
27
  scale?: number;
28
28
  /** Postgres element type of an "array" field; text when unset. */
29
29
  elementType?: string;
30
+ /**
31
+ * Name of the Postgres enum type of an "enum" field. Defaults to
32
+ * `<table>_<column>_enum`. `apso import` sets it so an existing database
33
+ * keeps its type name; two fields may share one type. TypeScript only.
34
+ */
35
+ enumName?: string;
30
36
  is_email?: boolean;
31
37
  }
32
38
  export interface ComputedField extends Omit<Field, "default"> {
@@ -47,6 +47,8 @@ export declare const isUuidGenerator: (sql?: string | null) => boolean;
47
47
  */
48
48
  export declare const typeormDefault: (sql: string) => string;
49
49
  export declare const getDefaultValueForField: (field: Field) => string | null;
50
+ /** An enum type name Apso can write unquoted-safe in every statement. */
51
+ export declare const ENUM_NAME: RegExp;
50
52
  export declare const getFieldForTemplate: (fields: Field[], entityName: string) => ComputedField[];
51
53
  export declare const fieldToEnumType: (fieldName: string, entityName: string) => string;
52
54
  export declare const typeExistsInEntity: (entity: Entity, type: string) => number;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateDecimalField = exports.typeExistsInEntity = exports.fieldToEnumType = exports.getFieldForTemplate = exports.getDefaultValueForField = exports.typeormDefault = exports.isUuidGenerator = exports.defaultSqlOf = exports.arrayElementType = exports.getJsTypeFromFieldType = exports.normalizeFieldType = exports.fieldTypeToColumnType = void 0;
3
+ exports.validateDecimalField = exports.typeExistsInEntity = exports.fieldToEnumType = exports.getFieldForTemplate = exports.ENUM_NAME = exports.getDefaultValueForField = exports.typeormDefault = exports.isUuidGenerator = exports.defaultSqlOf = exports.arrayElementType = exports.getJsTypeFromFieldType = exports.normalizeFieldType = exports.fieldTypeToColumnType = void 0;
4
4
  const casing_1 = require("./casing");
5
5
  /**
6
6
  * Canonical mapping from .apsorc field types to Postgres column types.
@@ -218,6 +218,8 @@ const literalDefault = (field) => {
218
218
  return null;
219
219
  }
220
220
  };
221
+ /** An enum type name Apso can write unquoted-safe in every statement. */
222
+ exports.ENUM_NAME = /^[A-Z_a-z]\w*$/;
221
223
  const getFieldForTemplate = (fields, entityName) => fields.map((field) => {
222
224
  // Validate decimal/numeric fields
223
225
  (0, exports.validateDecimalField)(field);
@@ -227,6 +229,8 @@ const getFieldForTemplate = (fields, entityName) => fields.map((field) => {
227
229
  if (clash)
228
230
  throw new Error(`${entityName}.${field.name} sets "generated" and "${clash}". Postgres computes a generated column, so it cannot have a default or be the primary key.`);
229
231
  }
232
+ if (field.enumName !== undefined && !exports.ENUM_NAME.test(field.enumName))
233
+ throw new Error(`${entityName}.${field.name} sets "enumName": ${JSON.stringify(field.enumName)}. An enum type's name is letters, digits and underscores, and does not start with a digit.`);
230
234
  // Normalize field type for template lookup (e.g., "double precision" -> "double")
231
235
  const normalizedType = (0, exports.normalizeFieldType)(field.type);
232
236
  return {
@@ -17,6 +17,8 @@ export interface PlannedEntity {
17
17
  property: string;
18
18
  entity: string;
19
19
  }[];
20
+ /** The uuid id has no default ("primaryKeyDefault": null): each create sends one. */
21
+ suppliesId?: boolean;
20
22
  }
21
23
  export interface CrudPlan {
22
24
  /** Parents before children. */
@@ -85,6 +85,9 @@ function planCrud(entities, relationships) {
85
85
  key: keys.length === 1 ? keys[0] : "id",
86
86
  payload,
87
87
  parents,
88
+ ...(keys.length === 0 &&
89
+ entity.primaryKeyType === "uuid" &&
90
+ entity.primaryKeyDefault === null && { suppliesId: true }),
88
91
  });
89
92
  }
90
93
  // Topological order: take entities whose required parents are all planned.
@@ -551,6 +551,8 @@ async function checkEndpoints(base, language, entities, relationships, done) {
551
551
  continue;
552
552
  }
553
553
  const body = { ...p.payload };
554
+ if (p.suppliesId)
555
+ body.id = (0, crypto_1.randomUUID)();
554
556
  for (const parent of p.parents)
555
557
  body[parent.property] = ids.get(parent.entity);
556
558
  const created = await request("POST", base + r, body);
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.57.0",
3
+ "version": "0.58.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@apso/cli",
9
- "version": "0.57.0",
9
+ "version": "0.58.0",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@apso/schema-tools": "^0.2.3",
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.57.0",
2
+ "version": "0.58.0",
3
3
  "commands": {
4
4
  "config": {
5
5
  "id": "config",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.57.0",
3
+ "version": "0.58.0",
4
4
  "mcpName": "io.github.apsoai/apso",
5
5
  "description": "Apso CLI",
6
6
  "author": "Apso by Mavric - @mavric",