@apso/cli 0.51.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 (98) hide show
  1. package/dist/commands/generate.js +3 -2
  2. package/dist/commands/import/supabase.js +31 -6
  3. package/dist/commands/init.d.ts +9 -0
  4. package/dist/commands/init.js +31 -1
  5. package/dist/commands/mcp/serve.js +23 -2
  6. package/dist/lib/apsorc-parser.d.ts +13 -1
  7. package/dist/lib/apsorc-parser.js +47 -4
  8. package/dist/lib/ddl/catalog.js +5 -2
  9. package/dist/lib/ddl/change.js +13 -2
  10. package/dist/lib/ddl/index.d.ts +62 -3
  11. package/dist/lib/ddl/index.js +211 -40
  12. package/dist/lib/generators/go.js +17 -3
  13. package/dist/lib/generators/python.js +17 -3
  14. package/dist/lib/generators/typescript.d.ts +2 -1
  15. package/dist/lib/generators/typescript.js +87 -13
  16. package/dist/lib/import/copy-data.js +4 -0
  17. package/dist/lib/import/introspect.d.ts +40 -0
  18. package/dist/lib/import/introspect.js +137 -49
  19. package/dist/lib/import/pg-to-apsorc.d.ts +62 -0
  20. package/dist/lib/import/pg-to-apsorc.js +248 -37
  21. package/dist/lib/import/types.d.ts +48 -3
  22. package/dist/lib/migrate/sandbox.js +23 -6
  23. package/dist/lib/migrate/snapshot.d.ts +5 -0
  24. package/dist/lib/plan/index.d.ts +4 -1
  25. package/dist/lib/plan/index.js +9 -3
  26. package/dist/lib/templates/entities/entity-col-array.eta +2 -1
  27. package/dist/lib/templates/entities/entity-col-bigint.eta +2 -2
  28. package/dist/lib/templates/entities/entity-col-bigserial.eta +2 -2
  29. package/dist/lib/templates/entities/entity-col-boolean.eta +1 -1
  30. package/dist/lib/templates/entities/entity-col-bytea.eta +2 -2
  31. package/dist/lib/templates/entities/entity-col-char.eta +4 -3
  32. package/dist/lib/templates/entities/entity-col-date.eta +6 -2
  33. package/dist/lib/templates/entities/entity-col-datetime.eta +8 -1
  34. package/dist/lib/templates/entities/entity-col-decimal.eta +2 -2
  35. package/dist/lib/templates/entities/entity-col-double.eta +2 -2
  36. package/dist/lib/templates/entities/entity-col-float.eta +1 -1
  37. package/dist/lib/templates/entities/entity-col-geography.eta +1 -1
  38. package/dist/lib/templates/entities/entity-col-geometry.eta +1 -1
  39. package/dist/lib/templates/entities/entity-col-geometrycollection.eta +1 -1
  40. package/dist/lib/templates/entities/entity-col-inet.eta +2 -2
  41. package/dist/lib/templates/entities/entity-col-int4range.eta +1 -1
  42. package/dist/lib/templates/entities/entity-col-integer.eta +2 -2
  43. package/dist/lib/templates/entities/entity-col-interval.eta +2 -2
  44. package/dist/lib/templates/entities/entity-col-json-plain.eta +1 -1
  45. package/dist/lib/templates/entities/entity-col-json.eta +1 -1
  46. package/dist/lib/templates/entities/entity-col-jsonb.eta +1 -1
  47. package/dist/lib/templates/entities/entity-col-linestring.eta +1 -1
  48. package/dist/lib/templates/entities/entity-col-money.eta +2 -2
  49. package/dist/lib/templates/entities/entity-col-multilinestring.eta +1 -1
  50. package/dist/lib/templates/entities/entity-col-multipoint.eta +1 -1
  51. package/dist/lib/templates/entities/entity-col-multipolygon.eta +1 -1
  52. package/dist/lib/templates/entities/entity-col-numeric.eta +2 -2
  53. package/dist/lib/templates/entities/entity-col-point.eta +1 -1
  54. package/dist/lib/templates/entities/entity-col-polygon.eta +1 -1
  55. package/dist/lib/templates/entities/entity-col-real.eta +2 -2
  56. package/dist/lib/templates/entities/entity-col-serial.eta +2 -2
  57. package/dist/lib/templates/entities/entity-col-smallint.eta +2 -2
  58. package/dist/lib/templates/entities/entity-col-smallserial.eta +2 -2
  59. package/dist/lib/templates/entities/entity-col-string.eta +2 -2
  60. package/dist/lib/templates/entities/entity-col-text.eta +4 -3
  61. package/dist/lib/templates/entities/entity-col-time.eta +2 -2
  62. package/dist/lib/templates/entities/entity-col-timestamp.eta +8 -1
  63. package/dist/lib/templates/entities/entity-col-timestamptz.eta +8 -1
  64. package/dist/lib/templates/entities/entity-col-timetz.eta +2 -2
  65. package/dist/lib/templates/entities/entity-col-tsvector.eta +2 -2
  66. package/dist/lib/templates/entities/entity-col-uuid.eta +5 -2
  67. package/dist/lib/templates/entities/entity-col-varchar.eta +4 -3
  68. package/dist/lib/templates/entities/entity-col-xml.eta +2 -2
  69. package/dist/lib/templates/entities/entity.eta +30 -18
  70. package/dist/lib/templates/go/models/model.eta +3 -3
  71. package/dist/lib/templates/python/models/model.eta +1 -1
  72. package/dist/lib/templates/rest/controller-rest.eta +25 -7
  73. package/dist/lib/templates/rest/dto-rest.eta +2 -2
  74. package/dist/lib/templates/rest/index-module-rest.eta +10 -0
  75. package/dist/lib/templates/rest/schema-extras-module.eta +24 -0
  76. package/dist/lib/types/constraints.d.ts +13 -0
  77. package/dist/lib/types/entity.d.ts +67 -2
  78. package/dist/lib/types/entity.js +39 -1
  79. package/dist/lib/types/field.d.ts +20 -2
  80. package/dist/lib/types/generator.d.ts +16 -0
  81. package/dist/lib/types/index.d.ts +1 -1
  82. package/dist/lib/types/indices.d.ts +21 -0
  83. package/dist/lib/types/relationship.d.ts +33 -0
  84. package/dist/lib/types/relationship.js +13 -0
  85. package/dist/lib/utils/field.d.ts +22 -0
  86. package/dist/lib/utils/field.js +62 -3
  87. package/dist/lib/utils/relationships/index.d.ts +1 -1
  88. package/dist/lib/utils/relationships/index.js +2 -1
  89. package/dist/lib/utils/relationships/parse.d.ts +11 -0
  90. package/dist/lib/utils/relationships/parse.js +44 -1
  91. package/dist/lib/utils/template.d.ts +3 -3
  92. package/dist/lib/utils/template.js +4 -4
  93. package/dist/lib/verify/crud-plan.d.ts +2 -0
  94. package/dist/lib/verify/crud-plan.js +19 -5
  95. package/dist/lib/verify/index.js +32 -3
  96. package/npm-shrinkwrap.json +72 -87
  97. package/oclif.manifest.json +7 -1
  98. 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.
@@ -49,12 +60,16 @@ const skipScope = (req: any) => {
49
60
  replace: <%= it.entityName %>Update,
50
61
  },
51
62
  validation: false,
63
+ <% if (it.dialects.length === 1 && it.dialects[0] === 'postgrest') { %>
52
64
  // List queries are PostgREST syntax only (?status=eq.open&select=id,name&order=id.desc).
53
65
  // A nestjsx parameter (filter, join, sort, s, fields, page, per_page, cache) gets a 400.
54
- dialects: ['postgrest'],
66
+ <% } else { %>
67
+ // Query syntaxes accepted, from .apsorc "query.dialects".
68
+ <% } %>
69
+ dialects: [<%~ it.dialectList %>],
55
70
  params: {
56
71
  id: {
57
- field: 'id',
72
+ field: '<%= it.keyField %>',
58
73
  type: 'string',
59
74
  primary: true,
60
75
  },
@@ -63,7 +78,10 @@ const skipScope = (req: any) => {
63
78
  // The default page: a list with no limit returns at most this many
64
79
  // rows. When more exist the answer is a 206 and its Content-Range
65
80
  // header has the total (0-24/42). The largest limit is 100.
66
- limit: 25,
81
+ limit: <%= it.limit %>,
82
+ <% if (it.alwaysPaginate) { %>
83
+ alwaysPaginate: true,
84
+ <% } %>
67
85
  <% if (it.associations.length) { %>
68
86
  join: {
69
87
  <% it.associations.forEach((assoc) => { %>
@@ -198,7 +216,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
198
216
  @ParsedRequest() req: CrudRequest,
199
217
  @Body() dto: <%= it.entityName %>Create,
200
218
  ) {
201
- return this.base.createOneBase(req, dto as unknown as <%= it.entityName %>);
219
+ return this.base.createOneBase(req, <%= writable('dto') %> as unknown as <%= it.entityName %>);
202
220
  }
203
221
 
204
222
  @Override('createManyBase')
@@ -207,7 +225,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
207
225
  @ParsedRequest() req: CrudRequest,
208
226
  @Body() dto: CreateManyDto<<%= it.entityName %>Create>
209
227
  ) {
210
- 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 %>>);
211
229
  }
212
230
 
213
231
  @Override('updateOneBase')
@@ -219,7 +237,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
219
237
  @ParsedRequest() req: CrudRequest,
220
238
  @Body() dto: <%= it.entityName %>Update,
221
239
  ) {
222
- return this.base.updateOneBase(req, dto as unknown as <%= it.entityName %>);
240
+ return this.base.updateOneBase(req, <%= writable('dto') %> as unknown as <%= it.entityName %>);
223
241
  }
224
242
 
225
243
  @Override('replaceOneBase')
@@ -228,7 +246,7 @@ export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
228
246
  @ParsedRequest() req: CrudRequest,
229
247
  @Body() dto: <%= it.entityName %>Update,
230
248
  ) {
231
- return this.base.replaceOneBase(req, dto as unknown as <%= it.entityName %>);
249
+ return this.base.replaceOneBase(req, <%= writable('dto') %> as unknown as <%= it.entityName %>);
232
250
  }
233
251
 
234
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")) { -%>
@@ -3,11 +3,21 @@
3
3
  <% it.entities.forEach((entity) => { %>
4
4
  import {<%= entity.name %>Module} from './<%= entity.name %>/<%= entity.name %>.module'
5
5
  <%}) %>
6
+ <% if (it.guards) { %>
6
7
  import { GuardsModule } from './guards/guards.module'
8
+ <% } %>
9
+ <% if (it.schemaExtras) { %>
10
+ import { SchemaExtrasModule } from './schema-extras.module'
11
+ <% } %>
7
12
 
8
13
  export default [
9
14
  <% it.entities.forEach((entity) => { %>
10
15
  <%= entity.name %>Module,
11
16
  <%}) %>
17
+ <% if (it.guards) { %>
12
18
  GuardsModule,
19
+ <% } %>
20
+ <% if (it.schemaExtras) { %>
21
+ SchemaExtrasModule,
22
+ <% } %>
13
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,6 +1,19 @@
1
1
  import { Entity } from "./entity";
2
2
  import { AuthConfig } from "./auth";
3
3
  import { RelationshipMap, Relationship } from "./relationship";
4
+ /**
5
+ * .apsorc `query` (TypeScript REST only): how the generated list routes read a
6
+ * request. Leave it out for the defaults. An app whose clients already send
7
+ * nestjsx queries keeps them working with `"dialects": ["nestjsx", "postgrest"]`.
8
+ */
9
+ export interface QueryConfig {
10
+ /** Query syntaxes the list routes accept. Default `["postgrest"]`. */
11
+ dialects?: Array<"postgrest" | "nestjsx">;
12
+ /** Rows a list returns when the request names no limit. Default 25. */
13
+ limit?: number;
14
+ /** Answer every list with a page object instead of an array. Default false. */
15
+ alwaysPaginate?: boolean;
16
+ }
4
17
  /**
5
18
  * Supported target languages for code generation
6
19
  */
@@ -158,6 +171,8 @@ export interface ControllerGenerationOptions extends EntityGenerationOptions {
158
171
  * caller's tenant
159
172
  */
160
173
  auth?: AuthConfig;
174
+ /** The .apsorc `query` settings for list routes */
175
+ query?: QueryConfig;
161
176
  }
162
177
  /**
163
178
  * Options for generating services
@@ -260,6 +275,7 @@ export interface LanguageGenerator {
260
275
  emitEvents?: boolean;
261
276
  http?: boolean;
262
277
  auth?: AuthConfig;
278
+ guards?: boolean;
263
279
  }): Promise<GeneratedFile[]>;
264
280
  /**
265
281
  * Generate guard files (auth, scope, etc.)
@@ -4,4 +4,4 @@ export { Index } from "./indices";
4
4
  export { JSONValue } from "./json";
5
5
  export { RelationshipType, Association, ApsorcRelationship, Relationship, RelationshipForTemplate, RelationshipMap, } from "./relationship";
6
6
  export { AuthProviderType, BaseAuthConfig, DbSessionAuthConfig, JwtConfig, JwtClaimsMapping, JwtAuthConfig, AuthConfig, AuthProviderConfig, AuthContext, DB_SESSION_AUTH_DEFAULTS, JWT_AUTH_DEFAULTS, isDbSessionAuth, BetterAuthConfig, assertSignInProvider, ResolvedJwtAuth, resolveJwtAuth, authProviders, resolveJwtProviders, } from "./auth";
7
- export { TargetLanguage, GeneratedFile, ValidationResult, PythonLanguageConfig, GoLanguageConfig, TypeScriptLanguageConfig, LanguageConfig, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, LanguageGenerator, GeneratorFactory, GeneratorRegistry, } from "./generator";
7
+ export { TargetLanguage, QueryConfig, GeneratedFile, ValidationResult, PythonLanguageConfig, GoLanguageConfig, TypeScriptLanguageConfig, LanguageConfig, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, LanguageGenerator, GeneratorFactory, GeneratorRegistry, } from "./generator";