@apso/cli 0.47.5 → 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.
- package/dist/commands/generate.js +6 -0
- package/dist/lib/apsorc-parser.d.ts +12 -1
- package/dist/lib/apsorc-parser.js +25 -2
- package/dist/lib/ddl/change.js +2 -0
- package/dist/lib/ddl/index.d.ts +11 -1
- package/dist/lib/ddl/index.js +30 -16
- package/dist/lib/ddl/sync.d.ts +25 -0
- package/dist/lib/ddl/sync.js +78 -0
- package/dist/lib/generators/go.d.ts +12 -6
- package/dist/lib/generators/go.js +223 -97
- package/dist/lib/generators/python.d.ts +6 -0
- package/dist/lib/generators/python.js +234 -23
- package/dist/lib/generators/typescript.js +12 -2
- package/dist/lib/templates/entities/entity-col-array.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
- package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
- package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
- package/dist/lib/templates/go/dto/dto.eta +17 -18
- package/dist/lib/templates/go/handlers/handler.eta +2 -0
- package/dist/lib/templates/go/index-module.eta +3 -1
- package/dist/lib/templates/go/middleware/auth.eta +1 -1
- package/dist/lib/templates/go/models/model.eta +22 -19
- package/dist/lib/templates/go/models/schema.eta +72 -0
- package/dist/lib/templates/go/services/service.eta +49 -21
- package/dist/lib/templates/go/utils/query.eta +32 -6
- package/dist/lib/templates/python/models/init.eta +24 -0
- package/dist/lib/templates/python/models/model.eta +24 -56
- package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
- package/dist/lib/templates/python/schemas/schema.eta +9 -9
- package/dist/lib/utils/field.d.ts +12 -0
- package/dist/lib/utils/field.js +18 -2
- package/npm-shrinkwrap.json +6 -6
- package/oclif.manifest.json +1 -1
- package/package.json +2 -2
- package/dist/lib/templates/go/models/model-col-array.eta +0 -1
- package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
- package/dist/lib/templates/go/models/model-col-date.eta +0 -1
- package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
- package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
- package/dist/lib/templates/go/models/model-col-float.eta +0 -1
- package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
- package/dist/lib/templates/go/models/model-col-json.eta +0 -1
- package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
- package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
- package/dist/lib/templates/go/models/model-col-string.eta +0 -1
- package/dist/lib/templates/go/models/model-col-text.eta +0 -1
- package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
- package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
- package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
- package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
- package/dist/lib/templates/python/models/model-col-array.eta +0 -4
- package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
- package/dist/lib/templates/python/models/model-col-date.eta +0 -4
- package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
- package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
- package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
- package/dist/lib/templates/python/models/model-col-float.eta +0 -6
- package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
- package/dist/lib/templates/python/models/model-col-json.eta +0 -4
- package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
- package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
- package/dist/lib/templates/python/models/model-col-string.eta +0 -6
- package/dist/lib/templates/python/models/model-col-text.eta +0 -6
- package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
- package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
- package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
- package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
|
@@ -287,6 +287,12 @@ class Generate extends base_command_1.default {
|
|
|
287
287
|
!fs.readFileSync(main, "utf8").includes("autogen_router"))
|
|
288
288
|
console.warn("[apso] app/main.py does not include autogen_router, so the generated routes are not served. Add: from app.autogen import autogen_router; app.include_router(autogen_router)");
|
|
289
289
|
}
|
|
290
|
+
if (language === "go") {
|
|
291
|
+
const main = path.join(process.cwd(), "cmd", "main.go");
|
|
292
|
+
if (fs.existsSync(main) &&
|
|
293
|
+
fs.readFileSync(main, "utf8").includes("AutoMigrate(models.All()"))
|
|
294
|
+
console.warn("[apso] cmd/main.go runs db.AutoMigrate(models.All()...) for DATABASE_SYNC. gorm can't create the enum types, constraints and names the migrations from apso migrate use, so the two databases would differ. Replace that call with: models.Migrate(db)");
|
|
295
|
+
}
|
|
290
296
|
const totalBuildTime = perf_hooks_1.performance.now() - totalBuildStart;
|
|
291
297
|
console.log(`[apso] Finished building all entities in ${totalBuildTime.toFixed(2)} ms`);
|
|
292
298
|
// Best-effort: install the commit co-author hook so commits that include
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Entity } from "./types/entity";
|
|
2
|
-
import { ApsorcRelationship, RelationshipMap } from "./types/relationship";
|
|
2
|
+
import { ApsorcRelationship, Relationship, RelationshipMap } from "./types/relationship";
|
|
3
3
|
import { AuthConfig } from "./types/auth";
|
|
4
4
|
import { TargetLanguage } from "./types/generator";
|
|
5
5
|
export declare enum ApiType {
|
|
@@ -82,6 +82,17 @@ export declare const assertCodegenSafeNames: (apsorc: Pick<ApsorcType, "entities
|
|
|
82
82
|
* @returns {Entity} The entity, with a filtered copy of its indexes when needed.
|
|
83
83
|
*/
|
|
84
84
|
export declare const dedupeIndexes: (entity: Entity) => Entity;
|
|
85
|
+
/**
|
|
86
|
+
* Drop a "uniques" entry on exactly the foreign key column of a OneToOne the
|
|
87
|
+
* entity owns. The relationship already makes that column UNIQUE (TypeORM's
|
|
88
|
+
* REL_ constraint), so a second constraint would only duplicate it. Composite
|
|
89
|
+
* entries that include the column are kept. `apso schema lint` warns about it.
|
|
90
|
+
*
|
|
91
|
+
* @param {Entity} entity - An entity from .apsorc.
|
|
92
|
+
* @param {Relationship[]} relationships - The entity's parsed relationships.
|
|
93
|
+
* @returns {Entity} The entity, with a filtered copy of its uniques when needed.
|
|
94
|
+
*/
|
|
95
|
+
export declare const dedupeOneToOneUniques: (entity: Entity, relationships?: Relationship[]) => Entity;
|
|
85
96
|
export declare const parseApsorcV2: (apsorc: ApsorcType) => ParsedApsorcData;
|
|
86
97
|
export declare const parseApsorc: () => ParsedApsorc;
|
|
87
98
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.findConfigPath = exports.readApsorcFile = exports.parseApsorc = exports.parseApsorcV2 = exports.dedupeIndexes = exports.assertCodegenSafeNames = exports.ApsorcNamingError = exports.parseApsorcV1 = exports.ApiType = void 0;
|
|
3
|
+
exports.findConfigPath = exports.readApsorcFile = exports.parseApsorc = exports.parseApsorcV2 = exports.dedupeOneToOneUniques = exports.dedupeIndexes = exports.assertCodegenSafeNames = exports.ApsorcNamingError = exports.parseApsorcV1 = exports.ApiType = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
6
6
|
const path = tslib_1.__importStar(require("path"));
|
|
@@ -87,6 +87,29 @@ const dedupeIndexes = (entity) => {
|
|
|
87
87
|
: { ...entity, indexes };
|
|
88
88
|
};
|
|
89
89
|
exports.dedupeIndexes = dedupeIndexes;
|
|
90
|
+
/**
|
|
91
|
+
* Drop a "uniques" entry on exactly the foreign key column of a OneToOne the
|
|
92
|
+
* entity owns. The relationship already makes that column UNIQUE (TypeORM's
|
|
93
|
+
* REL_ constraint), so a second constraint would only duplicate it. Composite
|
|
94
|
+
* entries that include the column are kept. `apso schema lint` warns about it.
|
|
95
|
+
*
|
|
96
|
+
* @param {Entity} entity - An entity from .apsorc.
|
|
97
|
+
* @param {Relationship[]} relationships - The entity's parsed relationships.
|
|
98
|
+
* @returns {Entity} The entity, with a filtered copy of its uniques when needed.
|
|
99
|
+
*/
|
|
100
|
+
const dedupeOneToOneUniques = (entity, relationships = []) => {
|
|
101
|
+
var _a;
|
|
102
|
+
if (!((_a = entity.uniques) === null || _a === void 0 ? void 0 : _a.length))
|
|
103
|
+
return entity;
|
|
104
|
+
const owned = new Set(relationships
|
|
105
|
+
.filter((r) => r.type === "OneToOne" && r.join)
|
|
106
|
+
.map((r) => (0, relationships_1.getRelationshipIdField)(r)));
|
|
107
|
+
const uniques = entity.uniques.filter((u) => !(u.fields.length === 1 && owned.has(u.fields[0])));
|
|
108
|
+
return uniques.length === entity.uniques.length
|
|
109
|
+
? entity
|
|
110
|
+
: { ...entity, uniques };
|
|
111
|
+
};
|
|
112
|
+
exports.dedupeOneToOneUniques = dedupeOneToOneUniques;
|
|
90
113
|
const parseApsorcV2 = (apsorc) => {
|
|
91
114
|
// A raw .apsorc may omit "relationships" (fresh scaffolds do); parseRc
|
|
92
115
|
// defaults it, but migrate and verify read the file directly.
|
|
@@ -94,7 +117,7 @@ const parseApsorcV2 = (apsorc) => {
|
|
|
94
117
|
(0, exports.assertCodegenSafeNames)(apsorc);
|
|
95
118
|
const relationshipMap = (0, relationships_1.parseRelationships)(apsoRelationships);
|
|
96
119
|
return {
|
|
97
|
-
entities: entities.map((entity) => (0, exports.dedupeIndexes)(entity)),
|
|
120
|
+
entities: entities.map((entity) => (0, exports.dedupeOneToOneUniques)((0, exports.dedupeIndexes)(entity), relationshipMap[entity.name])),
|
|
98
121
|
relationshipMap,
|
|
99
122
|
};
|
|
100
123
|
};
|
package/dist/lib/ddl/change.js
CHANGED
|
@@ -112,6 +112,8 @@ function changeDdl(before, after, plan) {
|
|
|
112
112
|
return (0, _1.tableName)(e);
|
|
113
113
|
};
|
|
114
114
|
const up = renames(was, R);
|
|
115
|
+
// A new uuid-keyed table needs uuid-ossp; schemaDdl creates it, so do the same here.
|
|
116
|
+
up.unshift(...A.extensions.filter((x) => !R.extensions.includes(x)));
|
|
115
117
|
const later = [];
|
|
116
118
|
const rTables = new Map(R.tables.map((t) => [t.name, t]));
|
|
117
119
|
const aTables = new Map(A.tables.map((t) => [t.name, t]));
|
package/dist/lib/ddl/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Entity } from "../types/entity";
|
|
2
2
|
import { ComputedField } from "../types/field";
|
|
3
|
-
import { RelationshipMap } from "../types/relationship";
|
|
3
|
+
import { RelationshipForTemplate, RelationshipMap } from "../types/relationship";
|
|
4
4
|
export declare const constraintName: {
|
|
5
5
|
primaryKey: (t: string, cols: string[]) => string;
|
|
6
6
|
unique: (t: string, cols: string[]) => string;
|
|
@@ -71,6 +71,16 @@ export interface Model {
|
|
|
71
71
|
constraints: ModelConstraint[];
|
|
72
72
|
indexes: ModelIndex[];
|
|
73
73
|
}
|
|
74
|
+
export declare const pkColumn: (e: Entity) => string;
|
|
75
|
+
export declare const fkType: (target?: Entity) => string;
|
|
76
|
+
/** The foreign key column of a ManyToOne or an owning OneToOne. */
|
|
77
|
+
export declare const relationColumn: (r: RelationshipForTemplate) => string;
|
|
78
|
+
/** The join table of an owning ManyToMany and its two key columns. */
|
|
79
|
+
export declare const joinTableOf: (e: Entity, r: RelationshipForTemplate, target: Entity) => {
|
|
80
|
+
name: string;
|
|
81
|
+
ownCol: string;
|
|
82
|
+
otherCol: string;
|
|
83
|
+
};
|
|
74
84
|
export declare function schemaModel(input: SchemaInput): Model;
|
|
75
85
|
export declare const createTypeSql: (e: ModelEnum) => string;
|
|
76
86
|
export declare const createIndexSql: (i: ModelIndex) => string;
|
package/dist/lib/ddl/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.schemaDdl = exports.createTableSql = exports.addConstraintSql = exports.createIndexSql = exports.createTypeSql = exports.schemaModel = exports.columnSpec = exports.enumTypeName = exports.tableName = exports.literal = exports.q = exports.constraintName = void 0;
|
|
3
|
+
exports.schemaDdl = exports.createTableSql = exports.addConstraintSql = exports.createIndexSql = exports.createTypeSql = exports.schemaModel = exports.joinTableOf = exports.relationColumn = exports.fkType = exports.pkColumn = exports.columnSpec = exports.enumTypeName = exports.tableName = exports.literal = exports.q = exports.constraintName = void 0;
|
|
4
4
|
/**
|
|
5
5
|
* Apso's own DDL writer: the CREATE statements for a whole .apsorc schema.
|
|
6
6
|
*
|
|
@@ -109,7 +109,7 @@ function columnSpec(table, f) {
|
|
|
109
109
|
break;
|
|
110
110
|
case "array": {
|
|
111
111
|
// entity-col-array.eta: { type: elementType || "text", array: true }, no default.
|
|
112
|
-
const element = f
|
|
112
|
+
const element = (0, field_1.arrayElementType)(f);
|
|
113
113
|
if (!/^[a-z][\w ]*$/i.test(element))
|
|
114
114
|
throw new Error(`Field ${table}.${f.name} has an invalid elementType "${element}".`);
|
|
115
115
|
type = `${element}[]`;
|
|
@@ -144,7 +144,27 @@ const column = (name, type, notNull, def, serial) => ({
|
|
|
144
144
|
serial,
|
|
145
145
|
});
|
|
146
146
|
const pkColumn = (e) => { var _a, _b, _c; return (_c = (_b = ((_a = e.fields) !== null && _a !== void 0 ? _a : []).find((f) => f.primary)) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : "id"; };
|
|
147
|
+
exports.pkColumn = pkColumn;
|
|
147
148
|
const fkType = (target) => (target === null || target === void 0 ? void 0 : target.primaryKeyType) === "uuid" ? "uuid" : "integer";
|
|
149
|
+
exports.fkType = fkType;
|
|
150
|
+
/** The foreign key column of a ManyToOne or an owning OneToOne. */
|
|
151
|
+
const relationColumn = (r) => r.type === "ManyToOne"
|
|
152
|
+
? r.camelCasedId
|
|
153
|
+
: typeormCase.camelCase(`${r.relationshipName}_id`);
|
|
154
|
+
exports.relationColumn = relationColumn;
|
|
155
|
+
/** The join table of an owning ManyToMany and its two key columns. */
|
|
156
|
+
const joinTableOf = (e, r, target) => {
|
|
157
|
+
const table = (0, exports.tableName)(e);
|
|
158
|
+
const targetTable = (0, exports.tableName)(target);
|
|
159
|
+
return {
|
|
160
|
+
name: r.joinTableName ||
|
|
161
|
+
typeormCase.snakeCase(`${table}_${r.pluralizedRelationshipName}_${targetTable}`),
|
|
162
|
+
ownCol: r.joinColumnName || typeormCase.camelCase(`${table}_${(0, exports.pkColumn)(e)}`),
|
|
163
|
+
otherCol: r.inverseJoinColumnName ||
|
|
164
|
+
typeormCase.camelCase(`${targetTable}_${(0, exports.pkColumn)(target)}`),
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
exports.joinTableOf = joinTableOf;
|
|
148
168
|
function schemaModel(input) {
|
|
149
169
|
var _a, _b, _c, _d, _e;
|
|
150
170
|
const { entities, relationshipMap } = input;
|
|
@@ -254,27 +274,21 @@ function schemaModel(input) {
|
|
|
254
274
|
const oneToOne = r.type === "OneToOne";
|
|
255
275
|
const onDelete = r.cascadeDelete || oneToOne ? "CASCADE" : "NO ACTION";
|
|
256
276
|
if (r.type === "ManyToOne" || (oneToOne && r.joinTable)) {
|
|
257
|
-
const col = r
|
|
258
|
-
|
|
259
|
-
: typeormCase.camelCase(`${r.relationshipName}_id`);
|
|
260
|
-
t.columns.push(column(col, fkType(target), !(r.nullable || oneToOne)));
|
|
277
|
+
const col = (0, exports.relationColumn)(r);
|
|
278
|
+
t.columns.push(column(col, (0, exports.fkType)(target), !(r.nullable || oneToOne)));
|
|
261
279
|
if (oneToOne)
|
|
262
280
|
unique(table, [col], exports.constraintName.relation(table, [col]));
|
|
263
281
|
if (r.type === "ManyToOne" && r.index)
|
|
264
282
|
index(table, [col]);
|
|
265
|
-
foreignKey(table, col, targetTable, pkColumn(target), `ON DELETE ${onDelete} ON UPDATE NO ACTION`);
|
|
283
|
+
foreignKey(table, col, targetTable, (0, exports.pkColumn)(target), `ON DELETE ${onDelete} ON UPDATE NO ACTION`);
|
|
266
284
|
}
|
|
267
285
|
if (r.type === "ManyToMany" && r.joinTable) {
|
|
268
|
-
const join =
|
|
269
|
-
typeormCase.snakeCase(`${table}_${r.pluralizedRelationshipName}_${targetTable}`);
|
|
270
|
-
const ownCol = r.joinColumnName || typeormCase.camelCase(`${table}_${pkColumn(e)}`);
|
|
271
|
-
const otherCol = r.inverseJoinColumnName ||
|
|
272
|
-
typeormCase.camelCase(`${targetTable}_${pkColumn(target)}`);
|
|
286
|
+
const { name: join, ownCol, otherCol } = (0, exports.joinTableOf)(e, r, target);
|
|
273
287
|
joinTables.push({
|
|
274
288
|
name: join,
|
|
275
289
|
columns: [
|
|
276
|
-
column(ownCol, fkType(e), true),
|
|
277
|
-
column(otherCol, fkType(target), true),
|
|
290
|
+
column(ownCol, (0, exports.fkType)(e), true),
|
|
291
|
+
column(otherCol, (0, exports.fkType)(target), true),
|
|
278
292
|
],
|
|
279
293
|
});
|
|
280
294
|
primaryKey(join, [ownCol, otherCol]);
|
|
@@ -282,8 +296,8 @@ function schemaModel(input) {
|
|
|
282
296
|
index(join, [otherCol]);
|
|
283
297
|
// TypeORM cascades the inverse key only when no inverse relation exists.
|
|
284
298
|
const inverse = r.biDirectional ? "NO ACTION" : "CASCADE";
|
|
285
|
-
foreignKey(join, ownCol, table, pkColumn(e), "ON DELETE CASCADE ON UPDATE CASCADE");
|
|
286
|
-
foreignKey(join, otherCol, targetTable, pkColumn(target), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
|
|
299
|
+
foreignKey(join, ownCol, table, (0, exports.pkColumn)(e), "ON DELETE CASCADE ON UPDATE CASCADE");
|
|
300
|
+
foreignKey(join, otherCol, targetTable, (0, exports.pkColumn)(target), `ON DELETE ${inverse} ON UPDATE ${inverse}`);
|
|
287
301
|
}
|
|
288
302
|
}
|
|
289
303
|
primaryKey(table, customPk
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DATABASE_SYNC for services whose ORM can't build the DDL on its own (Go):
|
|
3
|
+
* the same objects schemaDdl creates, as statements that create only what is
|
|
4
|
+
* missing. A fresh database ends up exactly as `apso migrate` builds it, and
|
|
5
|
+
* a database built by the migrations is left as it is. Nothing is altered or
|
|
6
|
+
* dropped, like gorm's AutoMigrate.
|
|
7
|
+
*/
|
|
8
|
+
import { SchemaInput } from ".";
|
|
9
|
+
/** Something an older generated service named differently, and the SQL that renames it. */
|
|
10
|
+
export interface LegacyName {
|
|
11
|
+
/** SQL that is true when the database still has the old name. */
|
|
12
|
+
when: string;
|
|
13
|
+
fix: string[];
|
|
14
|
+
}
|
|
15
|
+
export declare const legacyColumn: (table: string, from: string, to: string) => LegacyName;
|
|
16
|
+
export declare const legacyTable: (from: string, to: string, columns?: [string, string][]) => LegacyName;
|
|
17
|
+
export declare const legacyType: (from: string, to: string) => LegacyName;
|
|
18
|
+
/**
|
|
19
|
+
* One statement that fails, naming the renames to run, when the database
|
|
20
|
+
* still has names an older generated service used. Run before anything
|
|
21
|
+
* else, so a sync never adds empty columns beside ones that hold the data.
|
|
22
|
+
*/
|
|
23
|
+
export declare function legacyGuardSql(legacy: LegacyName[]): string | undefined;
|
|
24
|
+
/** Statements that bring a database up to the schema without dropping or altering anything. */
|
|
25
|
+
export declare function syncStatements(input: SchemaInput, legacy?: LegacyName[]): string[];
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.syncStatements = exports.legacyGuardSql = exports.legacyType = exports.legacyTable = exports.legacyColumn = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* DATABASE_SYNC for services whose ORM can't build the DDL on its own (Go):
|
|
6
|
+
* the same objects schemaDdl creates, as statements that create only what is
|
|
7
|
+
* missing. A fresh database ends up exactly as `apso migrate` builds it, and
|
|
8
|
+
* a database built by the migrations is left as it is. Nothing is altered or
|
|
9
|
+
* dropped, like gorm's AutoMigrate.
|
|
10
|
+
*/
|
|
11
|
+
const _1 = require(".");
|
|
12
|
+
const columnExists = (table, column) => `EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ${(0, _1.literal)(table)} AND column_name = ${(0, _1.literal)(column)})`;
|
|
13
|
+
const tableExists = (table) => `to_regclass(${(0, _1.literal)((0, _1.q)(table))}) IS NOT NULL`;
|
|
14
|
+
const typeExists = (name) => `EXISTS (SELECT 1 FROM pg_type WHERE typname = ${(0, _1.literal)(name)} AND typnamespace = 'public'::regnamespace)`;
|
|
15
|
+
const legacyColumn = (table, from, to) => ({
|
|
16
|
+
when: `${columnExists(table, from)} AND NOT ${columnExists(table, to)}`,
|
|
17
|
+
fix: [`ALTER TABLE ${(0, _1.q)(table)} RENAME COLUMN ${(0, _1.q)(from)} TO ${(0, _1.q)(to)}`],
|
|
18
|
+
});
|
|
19
|
+
exports.legacyColumn = legacyColumn;
|
|
20
|
+
const legacyTable = (from, to, columns = []) => ({
|
|
21
|
+
when: `${tableExists(from)} AND NOT ${tableExists(to)}`,
|
|
22
|
+
fix: [
|
|
23
|
+
`ALTER TABLE ${(0, _1.q)(from)} RENAME TO ${(0, _1.q)(to)}`,
|
|
24
|
+
...columns
|
|
25
|
+
.filter(([a, b]) => a !== b)
|
|
26
|
+
.map(([a, b]) => `ALTER TABLE ${(0, _1.q)(to)} RENAME COLUMN ${(0, _1.q)(a)} TO ${(0, _1.q)(b)}`),
|
|
27
|
+
],
|
|
28
|
+
});
|
|
29
|
+
exports.legacyTable = legacyTable;
|
|
30
|
+
const legacyType = (from, to) => ({
|
|
31
|
+
when: `${typeExists(from)} AND NOT ${typeExists(to)}`,
|
|
32
|
+
fix: [`ALTER TYPE "public".${(0, _1.q)(from)} RENAME TO ${(0, _1.q)(to)}`],
|
|
33
|
+
});
|
|
34
|
+
exports.legacyType = legacyType;
|
|
35
|
+
const block = (body) => `DO $apso$ BEGIN ${body} END $apso$`;
|
|
36
|
+
/**
|
|
37
|
+
* One statement that fails, naming the renames to run, when the database
|
|
38
|
+
* still has names an older generated service used. Run before anything
|
|
39
|
+
* else, so a sync never adds empty columns beside ones that hold the data.
|
|
40
|
+
*/
|
|
41
|
+
function legacyGuardSql(legacy) {
|
|
42
|
+
if (legacy.length === 0)
|
|
43
|
+
return undefined;
|
|
44
|
+
const checks = legacy
|
|
45
|
+
.map((l) => `IF ${l.when} THEN fix := fix || ${(0, _1.literal)(l.fix.map((s) => s + ";\n").join(""))}; END IF;`)
|
|
46
|
+
.join(" ");
|
|
47
|
+
return `DO $apso$ DECLARE fix text := ''; BEGIN ${checks} IF fix <> '' THEN RAISE EXCEPTION USING MESSAGE = ${(0, _1.literal)("This database was created by an older Apso-generated service, which named these columns, tables or types differently. Nothing was changed. Run this SQL once to keep the data, then start the service again:\n")} || fix; END IF; END $apso$`;
|
|
48
|
+
}
|
|
49
|
+
exports.legacyGuardSql = legacyGuardSql;
|
|
50
|
+
/** Statements that bring a database up to the schema without dropping or altering anything. */
|
|
51
|
+
function syncStatements(input, legacy = []) {
|
|
52
|
+
const m = (0, _1.schemaModel)(input);
|
|
53
|
+
const guard = legacyGuardSql(legacy);
|
|
54
|
+
return [
|
|
55
|
+
...(guard ? [guard] : []),
|
|
56
|
+
...m.extensions,
|
|
57
|
+
...m.enums.map((e) => block(`IF NOT ${typeExists(e.name)} THEN ${(0, _1.createTypeSql)(e)}; END IF;`)),
|
|
58
|
+
...m.tables.flatMap((t) => {
|
|
59
|
+
const pk = new Set(m.constraints
|
|
60
|
+
.filter((c) => c.kind === "pk" && c.table === t.name)
|
|
61
|
+
.flatMap((c) => c.columns));
|
|
62
|
+
return [
|
|
63
|
+
(0, _1.createTableSql)(t, m.constraints).replace(/^CREATE TABLE /, "CREATE TABLE IF NOT EXISTS "),
|
|
64
|
+
// A table from an older .apsorc gets the columns added since. Key
|
|
65
|
+
// columns are left out: an existing table has them, and ADD COLUMN
|
|
66
|
+
// IF NOT EXISTS with SERIAL makes a sequence even when it skips.
|
|
67
|
+
...t.columns
|
|
68
|
+
.filter((c) => !pk.has(c.name))
|
|
69
|
+
.map((c) => `ALTER TABLE ${(0, _1.q)(t.name)} ADD COLUMN IF NOT EXISTS ${c.sql}`),
|
|
70
|
+
];
|
|
71
|
+
}),
|
|
72
|
+
...m.indexes.map((i) => (0, _1.createIndexSql)(i).replace(/^CREATE (UNIQUE )?INDEX /, "CREATE $1INDEX IF NOT EXISTS ")),
|
|
73
|
+
...m.constraints
|
|
74
|
+
.filter((c) => c.kind !== "pk")
|
|
75
|
+
.map((c) => block(`IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ${(0, _1.literal)(c.name)} AND conrelid = to_regclass(${(0, _1.literal)((0, _1.q)(c.table))})) THEN ALTER TABLE ${(0, _1.q)(c.table)} ADD CONSTRAINT ${(0, _1.q)(c.name)} ${c.body}; END IF;`)),
|
|
76
|
+
];
|
|
77
|
+
}
|
|
78
|
+
exports.syncStatements = syncStatements;
|
|
@@ -9,10 +9,6 @@ export declare class GoGenerator extends BaseGenerator {
|
|
|
9
9
|
getLanguage(): TargetLanguage;
|
|
10
10
|
getFileExtension(): string;
|
|
11
11
|
validateConfig(config: GeneratorConfig): ValidationResult;
|
|
12
|
-
/**
|
|
13
|
-
* Maps .apsorc field types to Go types
|
|
14
|
-
*/
|
|
15
|
-
private mapFieldToGoType;
|
|
16
12
|
/**
|
|
17
13
|
* Gets the Go type for primary keys
|
|
18
14
|
*/
|
|
@@ -21,10 +17,15 @@ export declare class GoGenerator extends BaseGenerator {
|
|
|
21
17
|
* Gets the Swagger type for primary keys
|
|
22
18
|
*/
|
|
23
19
|
private getPrimaryKeySwaggerType;
|
|
20
|
+
private arrayTypes;
|
|
24
21
|
/**
|
|
25
|
-
*
|
|
22
|
+
* Fields for the Go templates. The gorm tag carries the column exactly as
|
|
23
|
+
* the DDL writer creates it (name, type, NOT NULL, default), so the model
|
|
24
|
+
* reads and writes the database `apso migrate` builds.
|
|
26
25
|
*/
|
|
27
26
|
private getGoFieldsForTemplate;
|
|
27
|
+
/** Relationships with what the Go templates need: field names, columns, join tables. */
|
|
28
|
+
private goAssociations;
|
|
28
29
|
generateEntity(options: EntityGenerationOptions): Promise<GeneratedFile[]>;
|
|
29
30
|
generateController(options: ControllerGenerationOptions): Promise<GeneratedFile[]>;
|
|
30
31
|
generateService(options: ServiceGenerationOptions): Promise<GeneratedFile[]>;
|
|
@@ -37,6 +38,11 @@ export declare class GoGenerator extends BaseGenerator {
|
|
|
37
38
|
http?: boolean;
|
|
38
39
|
auth?: AuthConfig;
|
|
39
40
|
}): Promise<GeneratedFile[]>;
|
|
41
|
+
/**
|
|
42
|
+
* DATABASE_SYNC's statements (the DDL writer's, creating only what is
|
|
43
|
+
* missing) and the join table columns gorm must be told about.
|
|
44
|
+
*/
|
|
45
|
+
private schemaData;
|
|
40
46
|
/**
|
|
41
47
|
* Emits a schema-derived manifest of the entities that opted in to
|
|
42
48
|
* domain-event emission (`.apsorc` `emitEvents`), mirroring the TypeScript
|
|
@@ -57,7 +63,7 @@ export declare class GoGenerator extends BaseGenerator {
|
|
|
57
63
|
}): Promise<GeneratedFile[]>;
|
|
58
64
|
/**
|
|
59
65
|
* Scope data for a Go service: each direct scopeBy field's struct field and
|
|
60
|
-
*
|
|
66
|
+
* column (the .apsorc name, as the DDL writer names it). A field declared on the entity is
|
|
61
67
|
* pascalCase; a relation's foreign key (organizationId) is OrganizationID.
|
|
62
68
|
*/
|
|
63
69
|
private goScope;
|