@apso/cli 0.52.0 → 0.53.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 (93) hide show
  1. package/dist/commands/import/supabase.js +31 -6
  2. package/dist/commands/init.d.ts +9 -0
  3. package/dist/commands/init.js +31 -1
  4. package/dist/commands/mcp/serve.js +20 -0
  5. package/dist/lib/apsorc-parser.js +7 -3
  6. package/dist/lib/ddl/catalog.js +5 -2
  7. package/dist/lib/ddl/change.js +13 -2
  8. package/dist/lib/ddl/index.d.ts +62 -3
  9. package/dist/lib/ddl/index.js +211 -40
  10. package/dist/lib/generators/go.js +17 -3
  11. package/dist/lib/generators/python.js +17 -3
  12. package/dist/lib/generators/typescript.js +85 -15
  13. package/dist/lib/import/copy-data.js +4 -0
  14. package/dist/lib/import/introspect.d.ts +40 -0
  15. package/dist/lib/import/introspect.js +137 -49
  16. package/dist/lib/import/pg-to-apsorc.d.ts +62 -0
  17. package/dist/lib/import/pg-to-apsorc.js +248 -37
  18. package/dist/lib/import/types.d.ts +48 -3
  19. package/dist/lib/migrate/sandbox.js +23 -6
  20. package/dist/lib/migrate/snapshot.d.ts +5 -0
  21. package/dist/lib/plan/index.d.ts +4 -1
  22. package/dist/lib/plan/index.js +9 -3
  23. package/dist/lib/templates/entities/entity-col-array.eta +2 -1
  24. package/dist/lib/templates/entities/entity-col-bigint.eta +2 -2
  25. package/dist/lib/templates/entities/entity-col-bigserial.eta +2 -2
  26. package/dist/lib/templates/entities/entity-col-boolean.eta +1 -1
  27. package/dist/lib/templates/entities/entity-col-bytea.eta +2 -2
  28. package/dist/lib/templates/entities/entity-col-char.eta +4 -3
  29. package/dist/lib/templates/entities/entity-col-date.eta +6 -2
  30. package/dist/lib/templates/entities/entity-col-datetime.eta +8 -1
  31. package/dist/lib/templates/entities/entity-col-decimal.eta +2 -2
  32. package/dist/lib/templates/entities/entity-col-double.eta +2 -2
  33. package/dist/lib/templates/entities/entity-col-float.eta +1 -1
  34. package/dist/lib/templates/entities/entity-col-geography.eta +1 -1
  35. package/dist/lib/templates/entities/entity-col-geometry.eta +1 -1
  36. package/dist/lib/templates/entities/entity-col-geometrycollection.eta +1 -1
  37. package/dist/lib/templates/entities/entity-col-inet.eta +2 -2
  38. package/dist/lib/templates/entities/entity-col-int4range.eta +1 -1
  39. package/dist/lib/templates/entities/entity-col-integer.eta +2 -2
  40. package/dist/lib/templates/entities/entity-col-interval.eta +2 -2
  41. package/dist/lib/templates/entities/entity-col-json-plain.eta +1 -1
  42. package/dist/lib/templates/entities/entity-col-json.eta +1 -1
  43. package/dist/lib/templates/entities/entity-col-jsonb.eta +1 -1
  44. package/dist/lib/templates/entities/entity-col-linestring.eta +1 -1
  45. package/dist/lib/templates/entities/entity-col-money.eta +2 -2
  46. package/dist/lib/templates/entities/entity-col-multilinestring.eta +1 -1
  47. package/dist/lib/templates/entities/entity-col-multipoint.eta +1 -1
  48. package/dist/lib/templates/entities/entity-col-multipolygon.eta +1 -1
  49. package/dist/lib/templates/entities/entity-col-numeric.eta +2 -2
  50. package/dist/lib/templates/entities/entity-col-point.eta +1 -1
  51. package/dist/lib/templates/entities/entity-col-polygon.eta +1 -1
  52. package/dist/lib/templates/entities/entity-col-real.eta +2 -2
  53. package/dist/lib/templates/entities/entity-col-serial.eta +2 -2
  54. package/dist/lib/templates/entities/entity-col-smallint.eta +2 -2
  55. package/dist/lib/templates/entities/entity-col-smallserial.eta +2 -2
  56. package/dist/lib/templates/entities/entity-col-string.eta +2 -2
  57. package/dist/lib/templates/entities/entity-col-text.eta +4 -3
  58. package/dist/lib/templates/entities/entity-col-time.eta +2 -2
  59. package/dist/lib/templates/entities/entity-col-timestamp.eta +8 -1
  60. package/dist/lib/templates/entities/entity-col-timestamptz.eta +8 -1
  61. package/dist/lib/templates/entities/entity-col-timetz.eta +2 -2
  62. package/dist/lib/templates/entities/entity-col-tsvector.eta +2 -2
  63. package/dist/lib/templates/entities/entity-col-uuid.eta +5 -2
  64. package/dist/lib/templates/entities/entity-col-varchar.eta +4 -3
  65. package/dist/lib/templates/entities/entity-col-xml.eta +2 -2
  66. package/dist/lib/templates/entities/entity.eta +30 -18
  67. package/dist/lib/templates/go/models/model.eta +3 -3
  68. package/dist/lib/templates/python/models/model.eta +1 -1
  69. package/dist/lib/templates/rest/controller-rest.eta +16 -5
  70. package/dist/lib/templates/rest/dto-rest.eta +2 -2
  71. package/dist/lib/templates/rest/index-module-rest.eta +6 -0
  72. package/dist/lib/templates/rest/schema-extras-module.eta +24 -0
  73. package/dist/lib/types/constraints.d.ts +13 -0
  74. package/dist/lib/types/entity.d.ts +67 -2
  75. package/dist/lib/types/entity.js +39 -1
  76. package/dist/lib/types/field.d.ts +20 -2
  77. package/dist/lib/types/indices.d.ts +21 -0
  78. package/dist/lib/types/relationship.d.ts +33 -0
  79. package/dist/lib/types/relationship.js +13 -0
  80. package/dist/lib/utils/field.d.ts +22 -0
  81. package/dist/lib/utils/field.js +62 -3
  82. package/dist/lib/utils/relationships/index.d.ts +1 -1
  83. package/dist/lib/utils/relationships/index.js +2 -1
  84. package/dist/lib/utils/relationships/parse.d.ts +11 -0
  85. package/dist/lib/utils/relationships/parse.js +44 -1
  86. package/dist/lib/utils/template.d.ts +3 -3
  87. package/dist/lib/utils/template.js +4 -4
  88. package/dist/lib/verify/crud-plan.d.ts +2 -0
  89. package/dist/lib/verify/crud-plan.js +19 -5
  90. package/dist/lib/verify/index.js +32 -3
  91. package/npm-shrinkwrap.json +72 -87
  92. package/oclif.manifest.json +7 -1
  93. package/package.json +3 -2
@@ -6,6 +6,13 @@ created_at: Date;
6
6
  @UpdateDateColumn()
7
7
  updated_at: Date;
8
8
  <% } else { %>
9
- @Column({ type: 'timestamp', nullable: <%= Boolean(field.nullable) %> })
9
+ <% if (field.primary) { %>
10
+ @PrimaryColumn({ type: 'timestamp'<% if (field.primaryKeyName) { %>, primaryKeyConstraintName: '<%= field.primaryKeyName %>'<% } %> })
11
+ <% } else { %>
12
+ <% if (field.index) { %>
13
+ @Index()
14
+ <% } %>
15
+ @Column({ type: 'timestamp', nullable: <%= Boolean(field.nullable) %><% if (field.unique) { %>, unique: true<% } %><% if (field.defaultSql) { %>, default: () => <%~ JSON.stringify(field.defaultSql) %><% } %> })
16
+ <% } %>
10
17
  <%= field.name %>: Date;
11
18
  <% } %>
@@ -6,6 +6,13 @@ created_at: Date;
6
6
  @UpdateDateColumn()
7
7
  updated_at: Date;
8
8
  <% } else { %>
9
- @Column({ type: 'timestamptz', nullable: <%= Boolean(field.nullable) %> })
9
+ <% if (field.primary) { %>
10
+ @PrimaryColumn({ type: 'timestamptz'<% if (field.primaryKeyName) { %>, primaryKeyConstraintName: '<%= field.primaryKeyName %>'<% } %> })
11
+ <% } else { %>
12
+ <% if (field.index) { %>
13
+ @Index()
14
+ <% } %>
15
+ @Column({ type: 'timestamptz', nullable: <%= Boolean(field.nullable) %><% if (field.unique) { %>, unique: true<% } %><% if (field.defaultSql) { %>, default: () => <%~ JSON.stringify(field.defaultSql) %><% } %> })
16
+ <% } %>
10
17
  <%= field.name %>: Date;
11
18
  <% } %>
@@ -1,11 +1,11 @@
1
1
  <% const {field} = it; %>
2
2
 
3
- @Column({ "type": "timetz", nullable: <%= Boolean(field.nullable) %><% if (field.default !== null) {%>, default: <%= field.default %><% } %> })
3
+ @Column({ "type": "timetz", nullable: <%= Boolean(field.nullable) %><% if (field.default !== null) {%>, default: <%= field.default %><% } %><% if (field.defaultSql) { %>, default: () => <%~ JSON.stringify(field.defaultSql) %><% } %> })
4
4
  <% if (field.index ) {%>
5
5
  @Index()
6
6
  <% } %>
7
7
  <% if (field.primary ) {%>
8
- @PrimaryColumn()
8
+ @PrimaryColumn(<% if (field.primaryKeyName) { %>{ primaryKeyConstraintName: '<%= field.primaryKeyName %>' }<% } %>)
9
9
  <% } %>
10
10
 
11
11
  <%= field.name %>: string;
@@ -1,11 +1,11 @@
1
1
  <% const {field} = it; %>
2
2
 
3
- @Column({ "type": "tsvector"<% if (field.nullable) {%>, nullable: true<% } %> })
3
+ @Column({ "type": "tsvector"<% if (field.nullable) {%>, nullable: true<% } %><% if (field.defaultSql) { %>, default: () => <%~ JSON.stringify(field.defaultSql) %><% } %> })
4
4
  <% if (field.index ) {%>
5
5
  @Index()
6
6
  <% } %>
7
7
  <% if (field.primary ) {%>
8
- @PrimaryColumn()
8
+ @PrimaryColumn(<% if (field.primaryKeyName) { %>{ primaryKeyConstraintName: '<%= field.primaryKeyName %>' }<% } %>)
9
9
  <% } %>
10
10
 
11
11
  <%= field.name %>: string;
@@ -1,9 +1,12 @@
1
1
  <% const {field} = it; %>
2
2
 
3
3
  <% if (field.primary ) {%>
4
- @PrimaryGeneratedColumn('uuid')
4
+ @PrimaryGeneratedColumn('uuid'<% if (field.primaryKeyName) { %>, { primaryKeyConstraintName: '<%= field.primaryKeyName %>' }<% } %>)
5
5
  <% } else { %>
6
- @Column({ "type": "uuid", nullable: <%= Boolean(field.nullable) %><% if (field.default !== null) {%>, default: <%= field.default %><% } %> })
6
+ @Column({ "type": "uuid", nullable: <%= Boolean(field.nullable) %><% if (field.unique) { %>, unique: true<% } %><% if (field.default !== null) {%>, default: <%= field.default %><% } %><% if (field.defaultSql) { %>, default: () => <%~ JSON.stringify(field.defaultSql) %><% } %> })
7
+ <% if (/^(gen_random_uuid|uuid_generate_v\d)\(\)$/.test(field.defaultSql || field.default || '')) { %>
8
+ @Generated('uuid')
9
+ <% } %>
7
10
  <% if (field.index ) {%>
8
11
  @Index()
9
12
  <% } %>
@@ -10,9 +10,10 @@
10
10
  <% if (field.index ) {%>
11
11
  @Index()
12
12
  <% } %>
13
- @Column({ type: "varchar", length: <%= field.length || 255 %>, nullable: <%= Boolean(field.nullable) %><% if (field.unique) {%>, unique: true <% } %><% if (field.default !== null) {%>, default: '<%= field.default %>'<% } %> })
14
- <% if (field.primary ) {%>
15
- @PrimaryColumn()
13
+ <% if (field.primary) { %>
14
+ @PrimaryColumn({ type: "varchar", length: <%= field.length || 255 %><% if (field.primaryKeyName) { %>, primaryKeyConstraintName: '<%= field.primaryKeyName %>'<% } %> })
15
+ <% } else { %>
16
+ @Column({ type: "varchar", length: <%= field.length || 255 %>, nullable: <%= Boolean(field.nullable) %><% if (field.unique) {%>, unique: true <% } %><% if (field.default !== null) {%>, default: '<%= field.default %>'<% } %><% if (field.defaultSql) { %>, default: () => <%~ JSON.stringify(field.defaultSql) %><% } %> })
16
17
  <% } %>
17
18
 
18
19
  <%= field.name %>: string;
@@ -1,11 +1,11 @@
1
1
  <% const {field} = it; %>
2
2
 
3
- @Column({ "type": "xml"<% if (field.nullable) {%>, nullable: true<% } %> })
3
+ @Column({ "type": "xml"<% if (field.nullable) {%>, nullable: true<% } %><% if (field.defaultSql) { %>, default: () => <%~ JSON.stringify(field.defaultSql) %><% } %> })
4
4
  <% if (field.index ) {%>
5
5
  @Index()
6
6
  <% } %>
7
7
  <% if (field.primary ) {%>
8
- @PrimaryColumn()
8
+ @PrimaryColumn(<% if (field.primaryKeyName) { %>{ primaryKeyConstraintName: '<%= field.primaryKeyName %>' }<% } %>)
9
9
  <% } %>
10
10
 
11
11
  <%= field.name %>: string;
@@ -22,6 +22,7 @@ import {
22
22
  JoinTable,
23
23
  Index,
24
24
  Unique,
25
+ Check,
25
26
  PrimaryColumn
26
27
  } from "typeorm";
27
28
  import {
@@ -49,7 +50,13 @@ const { CREATE, UPDATE } = CrudValidationGroups;
49
50
 
50
51
  @Entity('<%= it.tableName %>')
51
52
  <% it.indexes.forEach((index) => { %>
52
- @Index([<%~ index.fields.map((field) => `"${field}"`).join(', ') %>]<% if (index.unique) { %>, { unique: true } <% } %>)
53
+ @Index(<% if (index.name) { %><%~ JSON.stringify(index.name) %>, <% } %>[<%~ index.fields.map((field) => `"${field}"`).join(', ') %>]<% if (index.unique || index.where) { %>, { <%~ [index.unique ? 'unique: true' : '', index.where ? 'where: ' + JSON.stringify(index.where) : ''].filter(Boolean).join(', ') %> } <% } %>)
54
+ <% }) %>
55
+ <% it.sqlIndexes.forEach((index) => { %>
56
+ @Index(<%~ JSON.stringify(index.name) %>, { synchronize: false })
57
+ <% }) %>
58
+ <% it.checks.forEach((check) => { %>
59
+ @Check(<% if (check.name) { %><%~ JSON.stringify(check.name) %>, <% } %><%~ JSON.stringify(check.expression) %>)
53
60
  <% }) %>
54
61
  <% it.uniques.forEach((unique) => { %>
55
62
  @Unique(<% if (unique.name) {%> "<%= unique.name %>", <%} %>[<%~ unique.fields.map((field) => `"${field}"`).join(', ') %>])
@@ -58,25 +65,31 @@ export class <%= it.name %> {
58
65
  <% if (it.createPrimaryKey) { %>
59
66
  // Fields
60
67
  <% if (it.primaryKeyType === 'uuid') { %>
61
- @PrimaryGeneratedColumn('uuid')
68
+ <% if (it.primaryKeyDefault) { %>
69
+ @PrimaryColumn({ type: 'uuid', default: () => <%~ JSON.stringify(it.primaryKeyDefault) %><% if (it.primaryKeyName) { %>, primaryKeyConstraintName: '<%= it.primaryKeyName %>'<% } %> })
70
+ <% if (it.primaryKeyGenerated) { %>
71
+ @Generated('uuid')
72
+ <% } %>
73
+ <% } else { %>
74
+ @PrimaryGeneratedColumn('uuid'<% if (it.primaryKeyName) { %>, { primaryKeyConstraintName: '<%= it.primaryKeyName %>' }<% } %>)
75
+ <% } %>
62
76
  id: string;
63
77
  <% } else if (it.primaryKeyType === 'text') { %>
64
- @Column({ type: 'text' })
65
- @PrimaryColumn()
78
+ @PrimaryColumn({ type: 'text'<% if (it.primaryKeyName) { %>, primaryKeyConstraintName: '<%= it.primaryKeyName %>'<% } %> })
66
79
  id: string;
67
80
  <% } else { %>
68
- @PrimaryGeneratedColumn()
81
+ @PrimaryGeneratedColumn(<% if (it.primaryKeyName) { %>{ primaryKeyConstraintName: '<%= it.primaryKeyName %>' }<% } %>)
69
82
  id!: number;
70
83
  <% } %>
71
84
  <% } %>
72
85
 
73
86
  <% if (it.createdAt) { %>
74
- @CreateDateColumn()
87
+ @CreateDateColumn(<%~ it.createdAtArgs %>)
75
88
  created_at: Date;
76
89
  <% } %>
77
90
 
78
91
  <% if (it.updatedAt) { %>
79
- @UpdateDateColumn()
92
+ @UpdateDateColumn(<%~ it.updatedAtArgs %>)
80
93
  updated_at: Date;
81
94
  <% } %>
82
95
 
@@ -90,7 +103,11 @@ const columnsToProcess = it.columns.filter(c => {
90
103
  });
91
104
  columnsToProcess.forEach((field) => { %>
92
105
 
93
- <%~ includeFile(`./entities/entity-col-${field.type}`, { field }) %>
106
+ <%
107
+ // A generated column: Postgres computes it, so TypeORM never writes it.
108
+ const columnCode = includeFile(`./entities/entity-col-${field.type}`, { field });
109
+ %>
110
+ <%~ field.generated ? columnCode.replace(/@Column\(('\w+', )?\{/, (open) => `${open} generatedType: 'STORED', asExpression: ${JSON.stringify(field.generated)}, insert: false, update: false,`) : columnCode %>
94
111
 
95
112
  <% }); %>
96
113
 
@@ -113,17 +130,12 @@ columnsToProcess.forEach((field) => { %>
113
130
  <% if (assoc.index) { %>
114
131
  @Index()
115
132
  <% } %>
116
- @ManyToOne(() => <%= assoc.name %><% if (assoc.biDirectional) { %>, <%= assoc.camelCasedName %> => <%= assoc.camelCasedName %>.<%= assoc.inverseSidePropertyName %><% } %><% if (assoc.cascadeDelete) { %>, { onDelete: "CASCADE" }<% } %>)
117
- @JoinColumn({ name: '<%= assoc.camelCasedId %>' })
133
+ @ManyToOne(() => <%= assoc.name %><% if (assoc.biDirectional) { %>, <%= assoc.camelCasedName %> => <%= assoc.camelCasedName %>.<%= assoc.inverseSidePropertyName %><% } %><% if (assoc.onDeleteRule) { %>, { onDelete: "<%= assoc.onDeleteRule %>" }<% } %>)
134
+ @JoinColumn({ name: '<%= assoc.joinColumnName || assoc.camelCasedId %>'<% if (assoc.foreignKeyName) { %>, foreignKeyConstraintName: '<%= assoc.foreignKeyName %>'<% } %> })
118
135
  <%= assoc.relationshipName %>: <%= assoc.name %>;
119
136
 
120
- <% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>
121
- @Column({ type: "uuid", <% if (assoc.nullable) { %> nullable: true <% } %>})
122
- <%= assoc.camelCasedId %>: string;
123
- <% } else { %>
124
- @Column({ type: "integer", <% if (assoc.nullable) { %> nullable: true <% } %>})
125
- <%= assoc.camelCasedId %>: number;
126
- <% } %>
137
+ @<%= assoc.primary ? 'PrimaryColumn' : 'Column' %>({ <% if (assoc.joinColumnName) { %>name: '<%= assoc.joinColumnName %>', <% } %><%~ assoc.fkColumnOptions %>, <% if (assoc.primary && it.primaryKeyName) { %>primaryKeyConstraintName: '<%= it.primaryKeyName %>', <% } %><% if (assoc.nullable) { %> nullable: true <% } %>})
138
+ <%= assoc.camelCasedId %>: <%= assoc.fkTsType %>;
127
139
 
128
140
  <% } else if (assoc.type === 'ManyToMany') { %>
129
141
 
@@ -150,7 +162,7 @@ columnsToProcess.forEach((field) => { %>
150
162
  onDelete: "CASCADE",
151
163
  cascade: ["insert", "update"],
152
164
  })
153
- <% if (assoc.joinTable) { %>@JoinColumn()<% } %>
165
+ <% if (assoc.joinTable) { %>@JoinColumn(<% if (assoc.joinColumnName) { %>{ name: '<%= assoc.joinColumnName %>' }<% } %>)<% } %>
154
166
  <%= assoc.relationshipName %>: <%= assoc.name %>;
155
167
 
156
168
  <% } %>
@@ -30,15 +30,15 @@ type <%= it.name %> struct {
30
30
  <%= column.pascalName %> <%~ column.modelGoType %> `gorm:"<%~ column.gormTag %>" json:"<%= column.name %>,omitempty"`
31
31
  <% }) %>
32
32
  <% if (it.createdAt) { %>
33
- CreatedAt time.Time `gorm:"column:created_at;type:timestamp;not null;default:now();autoCreateTime" json:"createdAt"`
33
+ CreatedAt time.Time `gorm:"column:created_at;type:<%= it.createdAtType %>;<%= it.createdAtNotNull %>default:now();autoCreateTime" json:"createdAt"`
34
34
  <% } %>
35
35
  <% if (it.updatedAt) { %>
36
- UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:now();autoUpdateTime" json:"updatedAt"`
36
+ UpdatedAt time.Time `gorm:"column:updated_at;type:<%= it.updatedAtType %>;<%= it.updatedAtNotNull %>default:now();autoUpdateTime" json:"updatedAt"`
37
37
  <% } %>
38
38
  <% it.associations.forEach((assoc) => { %>
39
39
  <% if (assoc.owns) { %>
40
40
  <%= assoc.fkField %> <%= assoc.fkGoType %> `gorm:"<%~ assoc.fkTag %>" json:"<%= assoc.camelReferenceName %>Id"`
41
- <%= assoc.fieldName %> *<%= assoc.name %> `gorm:"foreignKey:<%= assoc.fkField %><% if (assoc.onDeleteCascade) { %>;constraint:OnDelete:CASCADE<% } %>" json:"<%= assoc.jsonName %>,omitempty"`
41
+ <%= assoc.fieldName %> *<%= assoc.name %> `gorm:"foreignKey:<%= assoc.fkField %><% if (assoc.onDelete) { %>;constraint:OnDelete:<%= assoc.onDelete %><% } %>" json:"<%= assoc.jsonName %>,omitempty"`
42
42
  <% } else if (assoc.type === 'OneToMany') { %>
43
43
  <%= assoc.fieldName %> []<%= assoc.name %> `gorm:"foreignKey:<%= assoc.foreignKey %>" json:"<%= assoc.jsonName %>,omitempty"`
44
44
  <% } else if (assoc.type === 'OneToOne') { %>
@@ -6,7 +6,7 @@ from datetime import datetime, date
6
6
  from decimal import Decimal
7
7
  from uuid import UUID
8
8
 
9
- from sqlalchemy import CHAR, Column, Integer, SmallInteger, BigInteger, String, Text, Boolean, Float, Numeric, Date, DateTime, JSON, Enum as SAEnum, ForeignKey, Index, PrimaryKeyConstraint, UniqueConstraint, Table, text
9
+ from sqlalchemy import CHAR, CheckConstraint, Column, Integer, SmallInteger, BigInteger, String, Text, Boolean, Float, Numeric, Date, DateTime, JSON, Enum as SAEnum, ForeignKey, Index, PrimaryKeyConstraint, UniqueConstraint, Table, text
10
10
  from sqlalchemy.dialects.postgresql import UUID as PGUUID, JSONB, ARRAY, DOUBLE_PRECISION, REAL
11
11
  from sqlalchemy.orm import relationship, Mapped, mapped_column
12
12
  from sqlalchemy.sql import func
@@ -15,6 +15,17 @@ import {<%= it.svcName %>} from './<%= it.entityName %>.service';
15
15
  import { RelationAccess, RelationRoot } from '../guards/relations.interceptor';
16
16
  <% } %>
17
17
 
18
+ <%
19
+ // Postgres computes a generated column, so a value sent for one is dropped
20
+ // before it can come back in the response as if it had been stored.
21
+ const writable = (dto) => it.generatedFields.length ? `writable(${dto})` : dto;
22
+ %>
23
+ <% if (it.generatedFields.length) { %>
24
+ const GENERATED = <%~ JSON.stringify(it.generatedFields) %>;
25
+ const writable = <T>(dto: T): T =>
26
+ Object.fromEntries(Object.entries(dto as object).filter(([key]) => !GENERATED.includes(key))) as T;
27
+
28
+ <% } %>
18
29
  <% if (it.crudAuthNested.length) { %>
19
30
  // A nested scopeBy path (task.workspaceId) limits rows to the parents ScopeGuard
20
31
  // found in the caller's tenant (req.apsoScope). An empty list matches no rows.
@@ -58,7 +69,7 @@ const skipScope = (req: any) => {
58
69
  dialects: [<%~ it.dialectList %>],
59
70
  params: {
60
71
  id: {
61
- field: 'id',
72
+ field: '<%= it.keyField %>',
62
73
  type: 'string',
63
74
  primary: true,
64
75
  },
@@ -205,7 +216,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
205
216
  @ParsedRequest() req: CrudRequest,
206
217
  @Body() dto: <%= it.entityName %>Create,
207
218
  ) {
208
- return this.base.createOneBase(req, dto as unknown as <%= it.entityName %>);
219
+ return this.base.createOneBase(req, <%= writable('dto') %> as unknown as <%= it.entityName %>);
209
220
  }
210
221
 
211
222
  @Override('createManyBase')
@@ -214,7 +225,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
214
225
  @ParsedRequest() req: CrudRequest,
215
226
  @Body() dto: CreateManyDto<<%= it.entityName %>Create>
216
227
  ) {
217
- return this.base.createManyBase(req, dto as unknown as CreateManyDto<<%= it.entityName %>>);
228
+ return this.base.createManyBase(req, <%~ it.generatedFields.length ? '{ ...dto, bulk: dto.bulk.map((row) => writable(row)) }' : 'dto' %> as unknown as CreateManyDto<<%= it.entityName %>>);
218
229
  }
219
230
 
220
231
  @Override('updateOneBase')
@@ -226,7 +237,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
226
237
  @ParsedRequest() req: CrudRequest,
227
238
  @Body() dto: <%= it.entityName %>Update,
228
239
  ) {
229
- return this.base.updateOneBase(req, dto as unknown as <%= it.entityName %>);
240
+ return this.base.updateOneBase(req, <%= writable('dto') %> as unknown as <%= it.entityName %>);
230
241
  }
231
242
 
232
243
  @Override('replaceOneBase')
@@ -235,7 +246,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
235
246
  @ParsedRequest() req: CrudRequest,
236
247
  @Body() dto: <%= it.entityName %>Update,
237
248
  ) {
238
- return this.base.replaceOneBase(req, dto as unknown as <%= it.entityName %>);
249
+ return this.base.replaceOneBase(req, <%= writable('dto') %> as unknown as <%= it.entityName %>);
239
250
  }
240
251
 
241
252
  @Override('deleteOneBase')
@@ -28,7 +28,7 @@ export class <%= it.entityName %>Create {
28
28
  id?: string;
29
29
 
30
30
  <% } -%>
31
- <% it.columns.forEach((field) => { -%>
31
+ <% it.columns.filter((field) => !field.generated).forEach((field) => { -%>
32
32
  <% if (!field.required) { -%>
33
33
  @ApiPropertyOptional()
34
34
  @IsOptional()
@@ -98,7 +98,7 @@ export class <%= it.entityName %>Create {
98
98
  }
99
99
 
100
100
  export class <%= it.entityName %>Update {
101
- <% it.columns.forEach((field) => { -%>
101
+ <% it.columns.filter((field) => !field.generated).forEach((field) => { -%>
102
102
  @ApiPropertyOptional()
103
103
  @IsOptional()
104
104
  <% if (field.dataType.includes("Enum")) { -%>
@@ -6,6 +6,9 @@ import {<%= entity.name %>Module} from './<%= entity.name %>/<%= entity.name %>.
6
6
  <% if (it.guards) { %>
7
7
  import { GuardsModule } from './guards/guards.module'
8
8
  <% } %>
9
+ <% if (it.schemaExtras) { %>
10
+ import { SchemaExtrasModule } from './schema-extras.module'
11
+ <% } %>
9
12
 
10
13
  export default [
11
14
  <% it.entities.forEach((entity) => { %>
@@ -14,4 +17,7 @@ export default [
14
17
  <% if (it.guards) { %>
15
18
  GuardsModule,
16
19
  <% } %>
20
+ <% if (it.schemaExtras) { %>
21
+ SchemaExtrasModule,
22
+ <% } %>
17
23
  ]
@@ -0,0 +1,24 @@
1
+ <%~ includeFile('./header.eta') %>
2
+
3
+ import { Module, OnApplicationBootstrap } from '@nestjs/common';
4
+ import { InjectDataSource } from '@nestjs/typeorm';
5
+ import { DataSource } from 'typeorm';
6
+
7
+ // Indexes TypeORM cannot declare: an expression, or a column sorted DESC.
8
+ // Migrations create them. TypeORM's own schema sync (apso dev, tests) does
9
+ // not, so this creates them after it, and the database has the same guards.
10
+ export const SCHEMA_EXTRAS: string[] = [
11
+ <% it.statements.forEach((statement) => { %>
12
+ <%~ JSON.stringify(statement) %>,
13
+ <% }) %>
14
+ ];
15
+
16
+ @Module({})
17
+ export class SchemaExtrasModule implements OnApplicationBootstrap {
18
+ constructor(@InjectDataSource() private readonly dataSource: DataSource) {}
19
+
20
+ async onApplicationBootstrap(): Promise<void> {
21
+ if (!this.dataSource.options.synchronize) return;
22
+ for (const statement of SCHEMA_EXTRAS) await this.dataSource.query(statement);
23
+ }
24
+ }
@@ -2,3 +2,16 @@ export interface Unique {
2
2
  fields: string[];
3
3
  name?: string;
4
4
  }
5
+ /** A CHECK constraint: a rule every row must satisfy, whatever writes it. */
6
+ export interface Check {
7
+ /** The constraint's name. Defaults to the name TypeORM derives. */
8
+ name?: string;
9
+ /** The SQL condition, written against column names. */
10
+ expression: string;
11
+ /**
12
+ * False keeps the constraint NOT VALID in migrations: new and changed rows
13
+ * are checked, rows already there are not. TypeORM's own schema sync
14
+ * creates it validated, which only differs on a database that has rows.
15
+ */
16
+ validate?: boolean;
17
+ }
@@ -1,6 +1,6 @@
1
- import { Unique } from "./constraints";
1
+ import { Unique, Check } from "./constraints";
2
2
  import { Field } from "./field";
3
- import { Index } from "./indices";
3
+ import { Index, SqlIndex } from "./indices";
4
4
  import { Association } from "./relationship";
5
5
  /**
6
6
  * Operations that can have scope enforcement applied
@@ -19,6 +19,38 @@ export interface ScopeOptions {
19
19
  export declare const PERMISSION_OPERATIONS: readonly ["read", "create", "update", "delete"];
20
20
  export type PermissionOperation = typeof PERMISSION_OPERATIONS[number];
21
21
  export type EntityPermissions = Partial<Record<PermissionOperation, string[]>>;
22
+ export type TimestampType = "timestamp" | "timestamptz";
23
+ export type TimestampColumn = "created_at" | "updated_at";
24
+ /**
25
+ * The type of an entity's created_at or updated_at column.
26
+ *
27
+ * @param {object} entity - Anything carrying an entity's "timestampType".
28
+ * @param {TimestampColumn} column - Which of the two columns.
29
+ * @returns {TimestampType} "timestamptz" when the entity asks for it, else "timestamp".
30
+ */
31
+ export declare const timestampTypeOf: (entity: {
32
+ timestampType?: Entity["timestampType"];
33
+ }, column: TimestampColumn) => TimestampType;
34
+ /**
35
+ * Whether an entity's created_at or updated_at column accepts NULL.
36
+ *
37
+ * @param {object} entity - Anything carrying an entity's "timestampNullable".
38
+ * @param {TimestampColumn} column - Which of the two columns.
39
+ * @returns {boolean} True only when the entity asks for a nullable column.
40
+ */
41
+ export declare const timestampNullableOf: (entity: {
42
+ timestampNullable?: Entity["timestampNullable"];
43
+ }, column: TimestampColumn) => boolean;
44
+ /**
45
+ * Whether an entity's created_at or updated_at column has DEFAULT now().
46
+ *
47
+ * @param {object} entity - Anything carrying an entity's "timestampDefault".
48
+ * @param {TimestampColumn} column - Which of the two columns.
49
+ * @returns {boolean} False only when the entity turns the default off.
50
+ */
51
+ export declare const timestampDefaultOf: (entity: {
52
+ timestampDefault?: Entity["timestampDefault"];
53
+ }, column: TimestampColumn) => boolean;
22
54
  export interface Entity {
23
55
  name: string;
24
56
  /**
@@ -29,10 +61,43 @@ export interface Entity {
29
61
  table?: string;
30
62
  created_at?: boolean;
31
63
  updated_at?: boolean;
64
+ /**
65
+ * Column type of created_at and updated_at. Defaults to "timestamp" (no time
66
+ * zone). `apso import` sets "timestamptz" when the source columns have one,
67
+ * or one type per column when the two differ.
68
+ */
69
+ timestampType?: TimestampType | Partial<Record<TimestampColumn, TimestampType>>;
70
+ /**
71
+ * Whether created_at and updated_at accept NULL: one value for both, or one
72
+ * per column. Defaults to false (NOT NULL). `apso import` sets it when the
73
+ * source columns are nullable.
74
+ */
75
+ timestampNullable?: boolean | Partial<Record<TimestampColumn, boolean>>;
76
+ /**
77
+ * Whether created_at and updated_at have DEFAULT now(): one boolean, or one
78
+ * per column. Defaults to true. Migrations honor false; TypeORM's own schema
79
+ * sync always writes the default. `apso import` sets it when a source
80
+ * column has none.
81
+ */
82
+ timestampDefault?: boolean | Partial<Record<TimestampColumn, boolean>>;
32
83
  primaryKeyType?: "serial" | "uuid";
84
+ /**
85
+ * Name of the primary key constraint. Defaults to the name TypeORM derives.
86
+ * `apso import` sets it so an existing database keeps its constraint names.
87
+ */
88
+ primaryKeyName?: string;
89
+ /**
90
+ * SQL expression that fills a uuid "id", for example "gen_random_uuid()".
91
+ * Defaults to uuid_generate_v4() from the uuid-ossp extension.
92
+ */
93
+ primaryKeyDefault?: string;
33
94
  fields?: Field[];
34
95
  indexes?: Index[];
96
+ /** Indexes on an expression or a descending column. */
97
+ sqlIndexes?: SqlIndex[];
35
98
  uniques?: Unique[];
99
+ /** CHECK constraints, for example "end_date >= start_date". */
100
+ checks?: Check[];
36
101
  /**
37
102
  * Fields or paths that define the authorization scope for this entity.
38
103
  * Can be a single field name (e.g., 'workspaceId') or an array of fields/paths
@@ -1,5 +1,43 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PERMISSION_OPERATIONS = void 0;
3
+ exports.timestampDefaultOf = exports.timestampNullableOf = exports.timestampTypeOf = exports.PERMISSION_OPERATIONS = void 0;
4
4
  /** Operations a role list can guard (read covers list and get by id). */
5
5
  exports.PERMISSION_OPERATIONS = ["read", "create", "update", "delete"];
6
+ /**
7
+ * The type of an entity's created_at or updated_at column.
8
+ *
9
+ * @param {object} entity - Anything carrying an entity's "timestampType".
10
+ * @param {TimestampColumn} column - Which of the two columns.
11
+ * @returns {TimestampType} "timestamptz" when the entity asks for it, else "timestamp".
12
+ */
13
+ const timestampTypeOf = (entity, column) => {
14
+ const t = entity.timestampType;
15
+ return (typeof t === "string" ? t : t === null || t === void 0 ? void 0 : t[column]) === "timestamptz"
16
+ ? "timestamptz"
17
+ : "timestamp";
18
+ };
19
+ exports.timestampTypeOf = timestampTypeOf;
20
+ /**
21
+ * Whether an entity's created_at or updated_at column accepts NULL.
22
+ *
23
+ * @param {object} entity - Anything carrying an entity's "timestampNullable".
24
+ * @param {TimestampColumn} column - Which of the two columns.
25
+ * @returns {boolean} True only when the entity asks for a nullable column.
26
+ */
27
+ const timestampNullableOf = (entity, column) => {
28
+ const n = entity.timestampNullable;
29
+ return (typeof n === "object" ? n === null || n === void 0 ? void 0 : n[column] : n) === true;
30
+ };
31
+ exports.timestampNullableOf = timestampNullableOf;
32
+ /**
33
+ * Whether an entity's created_at or updated_at column has DEFAULT now().
34
+ *
35
+ * @param {object} entity - Anything carrying an entity's "timestampDefault".
36
+ * @param {TimestampColumn} column - Which of the two columns.
37
+ * @returns {boolean} False only when the entity turns the default off.
38
+ */
39
+ const timestampDefaultOf = (entity, column) => {
40
+ const d = entity.timestampDefault;
41
+ return (typeof d === "object" ? d === null || d === void 0 ? void 0 : d[column] : d) !== false;
42
+ };
43
+ exports.timestampDefaultOf = timestampDefaultOf;
@@ -7,7 +7,21 @@ export interface Field {
7
7
  index?: boolean;
8
8
  primary?: boolean;
9
9
  unique?: boolean;
10
- default?: string | null;
10
+ /**
11
+ * The column default: a literal, or { "sql": "<expression>" } for a SQL
12
+ * expression such as now() or gen_random_uuid(). A json, jsonb or array
13
+ * field also takes an object or array literal.
14
+ */
15
+ default?: string | null | {
16
+ sql: string;
17
+ } | Record<string, unknown> | unknown[];
18
+ /** The column has no database default (a boolean otherwise defaults to false). */
19
+ noDefault?: boolean;
20
+ /**
21
+ * The SQL expression of a stored generated column: Postgres computes the
22
+ * value, so the API never accepts one for it.
23
+ */
24
+ generated?: string;
11
25
  length?: number;
12
26
  precision?: number;
13
27
  scale?: number;
@@ -15,6 +29,10 @@ export interface Field {
15
29
  elementType?: string;
16
30
  is_email?: boolean;
17
31
  }
18
- export interface ComputedField extends Field {
32
+ export interface ComputedField extends Omit<Field, "default"> {
33
+ /** The literal default, null when there is none or it is a SQL expression. */
34
+ default?: string | null;
35
+ /** The default as SQL, when it is an expression or a JSON literal. */
36
+ defaultSql?: string;
19
37
  dataType: string;
20
38
  }
@@ -1,4 +1,25 @@
1
1
  export interface Index {
2
2
  fields: string[];
3
3
  unique?: boolean;
4
+ /** The index's name. Defaults to the name TypeORM derives. */
5
+ name?: string;
6
+ /**
7
+ * A partial index: the SQL condition after WHERE, written against column
8
+ * names, for example "deleted_at IS NULL". Postgres only.
9
+ */
10
+ where?: string;
11
+ }
12
+ /**
13
+ * An index whose column list TypeORM cannot declare: an expression such as
14
+ * lower(email), or a column sorted DESC. Apso's own DDL creates it, in
15
+ * migrations and after a schema sync, and TypeORM is told to leave it alone.
16
+ */
17
+ export interface SqlIndex {
18
+ /** Required: TypeORM is told about the index by name. */
19
+ name: string;
20
+ /** The column list as SQL, for example "user_id, created_at DESC". */
21
+ columns: string;
22
+ unique?: boolean;
23
+ /** The condition of a partial index. */
24
+ where?: string;
4
25
  }
@@ -1,4 +1,17 @@
1
1
  export type RelationshipType = "OneToMany" | "ManyToOne" | "ManyToMany" | "OneToOne";
2
+ /** A foreign key's ON DELETE rule. "cascadeDelete": true is "CASCADE". */
3
+ export type OnDelete = "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION";
4
+ /**
5
+ * The ON DELETE rule of a ManyToOne's foreign key, undefined for the
6
+ * database default (NO ACTION).
7
+ *
8
+ * @param {object} r - A relationship's "onDelete" and "cascadeDelete".
9
+ * @returns {OnDelete | undefined} The rule to write, if any.
10
+ */
11
+ export declare const onDeleteOf: (r: {
12
+ onDelete?: OnDelete;
13
+ cascadeDelete?: boolean;
14
+ }) => OnDelete | undefined;
2
15
  export interface ApsorcRelationship {
3
16
  from: string;
4
17
  to: string;
@@ -7,6 +20,16 @@ export interface ApsorcRelationship {
7
20
  nullable?: boolean;
8
21
  bi_directional?: boolean;
9
22
  cascadeDelete?: boolean;
23
+ onDelete?: OnDelete;
24
+ /** Name of the foreign key constraint; defaults to the name TypeORM derives. */
25
+ foreignKeyName?: string;
26
+ /** The foreign key column is (part of) the entity's primary key. */
27
+ primary?: boolean;
28
+ /**
29
+ * false keeps a foreign key NOT VALID: enforced for new rows, never checked
30
+ * against the rows already there. Only migrations can create it that way.
31
+ */
32
+ validate?: boolean;
10
33
  index?: boolean;
11
34
  joinTableName?: string;
12
35
  joinColumnName?: string;
@@ -20,6 +43,16 @@ export interface Relationship {
20
43
  join?: boolean;
21
44
  biDirectional?: boolean;
22
45
  cascadeDelete?: boolean;
46
+ onDelete?: OnDelete;
47
+ /** Name of the foreign key constraint; defaults to the name TypeORM derives. */
48
+ foreignKeyName?: string;
49
+ /** The foreign key column is (part of) the entity's primary key. */
50
+ primary?: boolean;
51
+ /**
52
+ * false keeps a foreign key NOT VALID: enforced for new rows, never checked
53
+ * against the rows already there. Only migrations can create it that way.
54
+ */
55
+ validate?: boolean;
23
56
  index?: boolean;
24
57
  joinTableName?: string;
25
58
  joinColumnName?: string;