@apso/cli 0.47.6 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/generate.js +6 -0
- 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/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 +2 -2
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- 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
|
@@ -1,47 +1,50 @@
|
|
|
1
1
|
<%~ includeFile('../../header.eta', it) %>
|
|
2
2
|
|
|
3
3
|
package models
|
|
4
|
+
<% if (it.importTime || it.importEnums || it.importPq) { %>
|
|
4
5
|
|
|
5
6
|
import (
|
|
7
|
+
<% if (it.importTime) { %>
|
|
6
8
|
"time"
|
|
9
|
+
<% } %>
|
|
7
10
|
<% if (it.importEnums) { %>
|
|
8
11
|
"app/autogen/models/enums"
|
|
9
12
|
<% } %>
|
|
13
|
+
<% if (it.importPq) { %>
|
|
14
|
+
"github.com/lib/pq"
|
|
15
|
+
<% } %>
|
|
10
16
|
)
|
|
17
|
+
<% } %>
|
|
11
18
|
|
|
12
|
-
// <%= it.name %> represents the <%= it.tableName %> table
|
|
19
|
+
// <%= it.name %> represents the <%= it.tableName %> table. Each gorm tag
|
|
20
|
+
// matches the column the migrations from `apso migrate` create.
|
|
13
21
|
type <%= it.name %> struct {
|
|
14
22
|
<% if (it.createPrimaryKey) { %>
|
|
15
23
|
<% if (it.primaryKeyType === 'uuid') { %>
|
|
16
|
-
ID
|
|
24
|
+
ID string `gorm:"column:id;type:uuid;primaryKey;default:uuid_generate_v4()" json:"id"`
|
|
17
25
|
<% } else { %>
|
|
18
|
-
ID
|
|
26
|
+
ID uint `gorm:"column:id;type:integer;primaryKey;autoIncrement" json:"id"`
|
|
19
27
|
<% } %>
|
|
20
28
|
<% } %>
|
|
21
29
|
<% it.columns.forEach((column) => { %>
|
|
22
|
-
|
|
30
|
+
<%= column.pascalName %> <%~ column.modelGoType %> `gorm:"<%~ column.gormTag %>" json:"<%= column.name %>,omitempty"`
|
|
23
31
|
<% }) %>
|
|
24
32
|
<% if (it.createdAt) { %>
|
|
25
|
-
CreatedAt time.Time
|
|
33
|
+
CreatedAt time.Time `gorm:"column:created_at;type:timestamp;not null;default:now();autoCreateTime" json:"createdAt"`
|
|
26
34
|
<% } %>
|
|
27
35
|
<% if (it.updatedAt) { %>
|
|
28
|
-
UpdatedAt time.Time
|
|
36
|
+
UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:now();autoUpdateTime" json:"updatedAt"`
|
|
29
37
|
<% } %>
|
|
30
38
|
<% it.associations.forEach((assoc) => { %>
|
|
31
|
-
<% if (assoc.
|
|
32
|
-
<%= assoc.
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
<%= assoc.
|
|
39
|
+
<% if (assoc.owns) { %>
|
|
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"`
|
|
42
|
+
<% } else if (assoc.type === 'OneToMany') { %>
|
|
43
|
+
<%= assoc.fieldName %> []<%= assoc.name %> `gorm:"foreignKey:<%= assoc.foreignKey %>" json:"<%= assoc.jsonName %>,omitempty"`
|
|
36
44
|
<% } else if (assoc.type === 'OneToOne') { %>
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
<%= assoc.
|
|
40
|
-
<% } else { %>
|
|
41
|
-
<%= assoc.referenceName || assoc.name %> *<%= assoc.name %> `json:"<%= assoc.camelReferenceName || assoc.camelName %>,omitempty"`
|
|
42
|
-
<% } %>
|
|
43
|
-
<% } else if (assoc.type === 'ManyToMany') { %>
|
|
44
|
-
<%= assoc.pluralName %> []<%= assoc.name %> `gorm:"many2many:<%= assoc.joinTable %>;" json:"<%= assoc.camelPluralName %>,omitempty"`
|
|
45
|
+
<%= assoc.fieldName %> *<%= assoc.name %> `gorm:"foreignKey:<%= assoc.foreignKey %>;constraint:OnDelete:CASCADE" json:"<%= assoc.jsonName %>,omitempty"`
|
|
46
|
+
<% } else if (assoc.type === 'ManyToMany' && assoc.join) { %>
|
|
47
|
+
<%= assoc.fieldName %> []<%= assoc.name %> `gorm:"many2many:<%= assoc.join.name %>;joinForeignKey:<%= assoc.join.ownCol %>;joinReferences:<%= assoc.join.otherCol %>" json:"<%= assoc.jsonName %>,omitempty"`
|
|
45
48
|
<% } %>
|
|
46
49
|
<% }) %>
|
|
47
50
|
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
<%~ includeFile('../../header.eta', it) %>
|
|
2
|
+
|
|
3
|
+
package models
|
|
4
|
+
|
|
5
|
+
import (
|
|
6
|
+
"gorm.io/gorm"
|
|
7
|
+
"gorm.io/gorm/schema"
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
// Migrate brings the database to the .apsorc schema exactly as the migrations
|
|
11
|
+
// from `apso migrate` build it: it creates the tables, columns, indexes and
|
|
12
|
+
// constraints that are missing, and never alters or drops anything. Call it
|
|
13
|
+
// instead of db.AutoMigrate when DATABASE_SYNC=true; AutoMigrate can't create
|
|
14
|
+
// the enum types, unique constraints and names those migrations use.
|
|
15
|
+
//
|
|
16
|
+
// It refuses, and prints the SQL to rename them, when the database still has
|
|
17
|
+
// the snake_case columns older generated models made, rather than adding
|
|
18
|
+
// empty columns beside them.
|
|
19
|
+
func Migrate(db *gorm.DB) error {
|
|
20
|
+
UseNames(db)
|
|
21
|
+
sqlDB, err := db.DB()
|
|
22
|
+
if err != nil {
|
|
23
|
+
return err
|
|
24
|
+
}
|
|
25
|
+
tx, err := sqlDB.Begin()
|
|
26
|
+
if err != nil {
|
|
27
|
+
return err
|
|
28
|
+
}
|
|
29
|
+
defer tx.Rollback()
|
|
30
|
+
for _, statement := range schemaStatements {
|
|
31
|
+
if _, err := tx.Exec(statement); err != nil {
|
|
32
|
+
return err
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return tx.Commit()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
var schemaStatements = []string{
|
|
39
|
+
<% it.statements.forEach((s) => { %>
|
|
40
|
+
<%~ s %>,
|
|
41
|
+
<% }) %>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// joinColumns maps a join table column, as gorm titles it, to its name in the
|
|
45
|
+
// database (gorm would otherwise snake_case "PostId" to "post_id").
|
|
46
|
+
var joinColumns = map[string]string{
|
|
47
|
+
<% it.joinColumns.forEach(([k, v]) => { %>
|
|
48
|
+
<%~ k %>: <%~ v %>,
|
|
49
|
+
<% }) %>
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type namer struct{ schema.Namer }
|
|
53
|
+
|
|
54
|
+
func (n namer) ColumnName(table, column string) string {
|
|
55
|
+
if c, ok := joinColumns[column]; ok {
|
|
56
|
+
return c
|
|
57
|
+
}
|
|
58
|
+
return n.Namer.ColumnName(table, column)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// JoinTableName keeps the join table names from the many2many tags as written.
|
|
62
|
+
func (n namer) JoinTableName(name string) string {
|
|
63
|
+
return name
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// UseNames makes gorm use the join table column names the migrations create.
|
|
67
|
+
// RegisterAllRoutes and Migrate call it before any model is read.
|
|
68
|
+
func UseNames(db *gorm.DB) {
|
|
69
|
+
if _, ok := db.NamingStrategy.(namer); !ok {
|
|
70
|
+
db.NamingStrategy = namer{db.NamingStrategy}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -4,6 +4,9 @@ package services
|
|
|
4
4
|
|
|
5
5
|
import (
|
|
6
6
|
"context"
|
|
7
|
+
<% if (it.columns.some(c => c.gormTag.includes('serializer:json'))) { %>
|
|
8
|
+
"encoding/json"
|
|
9
|
+
<% } %>
|
|
7
10
|
"errors"
|
|
8
11
|
|
|
9
12
|
"app/autogen/dto"
|
|
@@ -12,6 +15,9 @@ import (
|
|
|
12
15
|
<% } %>
|
|
13
16
|
"app/autogen/models"
|
|
14
17
|
"app/autogen/utils"
|
|
18
|
+
<% if (it.columns.some(c => c.type === 'array')) { %>
|
|
19
|
+
"github.com/lib/pq"
|
|
20
|
+
<% } %>
|
|
15
21
|
"gorm.io/gorm"
|
|
16
22
|
)
|
|
17
23
|
|
|
@@ -20,7 +26,7 @@ import (
|
|
|
20
26
|
var AllowedFields<%= it.entityName %> = map[string]bool{
|
|
21
27
|
"id": true,
|
|
22
28
|
<% it.columns.forEach((column) => { %>
|
|
23
|
-
"<%= column.
|
|
29
|
+
"<%= column.name %>": true,
|
|
24
30
|
<% }) %>
|
|
25
31
|
<% if (it.createdAt) { %>
|
|
26
32
|
"created_at": true,
|
|
@@ -28,8 +34,8 @@ var AllowedFields<%= it.entityName %> = map[string]bool{
|
|
|
28
34
|
<% if (it.updatedAt) { %>
|
|
29
35
|
"updated_at": true,
|
|
30
36
|
<% } %>
|
|
31
|
-
<% it.associations.filter(a => a.
|
|
32
|
-
"<%= assoc.
|
|
37
|
+
<% it.associations.filter(a => a.owns).forEach((assoc) => { %>
|
|
38
|
+
"<%= assoc.fkColumn %>": true,
|
|
33
39
|
<% }) %>
|
|
34
40
|
}
|
|
35
41
|
|
|
@@ -71,7 +77,7 @@ func (s *<%= it.entityName %>Service) scoped(ctx context.Context, q *gorm.DB, op
|
|
|
71
77
|
return nil, nil, ErrForbidden
|
|
72
78
|
}
|
|
73
79
|
// Compared as text: token claims are strings, the column may be a number or uuid.
|
|
74
|
-
q = q.Where(
|
|
80
|
+
q = q.Where(`CAST("`+table+`"."`+col+`" AS TEXT) = ?`, v)
|
|
75
81
|
}
|
|
76
82
|
return q, values, nil
|
|
77
83
|
}
|
|
@@ -84,7 +90,7 @@ func (s *<%= it.entityName %>Service) FindAll(ctx context.Context, opts utils.Qu
|
|
|
84
90
|
|
|
85
91
|
query := s.db.WithContext(ctx).Model(&models.<%= it.entityName %>{})
|
|
86
92
|
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
87
|
-
query = query.Preload("<%= assoc.
|
|
93
|
+
query = query.Preload("<%= assoc.fieldName %>")
|
|
88
94
|
<% }) %>
|
|
89
95
|
<% if (it.scope) { %>
|
|
90
96
|
query, _, scopeErr := s.scoped(ctx, query, "find")
|
|
@@ -125,7 +131,7 @@ func (s *<%= it.entityName %>Service) FindAllBare(ctx context.Context, opts util
|
|
|
125
131
|
|
|
126
132
|
query := s.db.WithContext(ctx).Model(&models.<%= it.entityName %>{})
|
|
127
133
|
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
128
|
-
query = query.Preload("<%= assoc.
|
|
134
|
+
query = query.Preload("<%= assoc.fieldName %>")
|
|
129
135
|
<% }) %>
|
|
130
136
|
<% if (it.scope) { %>
|
|
131
137
|
query, _, scopeErr := s.scoped(ctx, query, "find")
|
|
@@ -156,7 +162,7 @@ func (s *<%= it.entityName %>Service) FindOne(ctx context.Context, id string) (*
|
|
|
156
162
|
|
|
157
163
|
query := s.db.WithContext(ctx)
|
|
158
164
|
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
159
|
-
query = query.Preload("<%= assoc.
|
|
165
|
+
query = query.Preload("<%= assoc.fieldName %>")
|
|
160
166
|
<% }) %>
|
|
161
167
|
<% if (it.scope) { %>
|
|
162
168
|
query, _, scopeErr := s.scoped(ctx, query, "get")
|
|
@@ -184,14 +190,10 @@ func (s *<%= it.entityName %>Service) FindOne(ctx context.Context, id string) (*
|
|
|
184
190
|
func (s *<%= it.entityName %>Service) Create(ctx context.Context, input *dto.<%= it.entityName %>Create) (*dto.<%= it.entityName %>Response, error) {
|
|
185
191
|
item := models.<%= it.entityName %>{
|
|
186
192
|
<% it.columns.filter(c => !c.generated && !c.primary).forEach((column) => { %>
|
|
187
|
-
<% if (column.required) { %>
|
|
188
|
-
<%= column.pascalName %>: input.<%= column.pascalName %>,
|
|
189
|
-
<% } else { %>
|
|
190
193
|
<%= column.pascalName %>: input.<%= column.pascalName %>,
|
|
191
|
-
<% } %>
|
|
192
194
|
<% }) %>
|
|
193
|
-
<% it.associations.filter(a => a.
|
|
194
|
-
<%= assoc.
|
|
195
|
+
<% it.associations.filter(a => a.owns).forEach((assoc) => { %>
|
|
196
|
+
<%= assoc.fkField %>: input.<%= assoc.fkField %>,
|
|
195
197
|
<% }) %>
|
|
196
198
|
}
|
|
197
199
|
<% if (it.scope && it.scope.injectOnCreate) { %>
|
|
@@ -243,12 +245,24 @@ func (s *<%= it.entityName %>Service) Update(ctx context.Context, id string, inp
|
|
|
243
245
|
updates := make(map[string]interface{})
|
|
244
246
|
<% it.columns.filter(c => !c.generated && !c.primary).forEach((column) => { %>
|
|
245
247
|
if input.<%= column.pascalName %> != nil {
|
|
246
|
-
|
|
248
|
+
<% if (column.gormTag.includes('serializer:json')) { %>
|
|
249
|
+
// A map in an update map skips the model's JSON serializer.
|
|
250
|
+
encoded, err := json.Marshal(input.<%= column.pascalName %>)
|
|
251
|
+
if err != nil {
|
|
252
|
+
return nil, err
|
|
253
|
+
}
|
|
254
|
+
updates["<%= column.name %>"] = string(encoded)
|
|
255
|
+
<% } else if (column.type === 'array') { %>
|
|
256
|
+
// A plain slice would be sent as a record; the pq type sends an array.
|
|
257
|
+
updates["<%= column.name %>"] = <%= column.arrayGoType %>(*input.<%= column.pascalName %>)
|
|
258
|
+
<% } else { %>
|
|
259
|
+
updates["<%= column.name %>"] = *input.<%= column.pascalName %>
|
|
260
|
+
<% } %>
|
|
247
261
|
}
|
|
248
262
|
<% }) %>
|
|
249
|
-
<% it.associations.filter(a => a.
|
|
250
|
-
if input.<%= assoc.
|
|
251
|
-
updates["<%= assoc.
|
|
263
|
+
<% it.associations.filter(a => a.owns).forEach((assoc) => { %>
|
|
264
|
+
if input.<%= assoc.fkField %> != nil {
|
|
265
|
+
updates["<%= assoc.fkColumn %>"] = *input.<%= assoc.fkField %>
|
|
252
266
|
}
|
|
253
267
|
<% }) %>
|
|
254
268
|
<% if (it.scope) { %>
|
|
@@ -267,7 +281,7 @@ func (s *<%= it.entityName %>Service) Update(ctx context.Context, id string, inp
|
|
|
267
281
|
// Reload with associations
|
|
268
282
|
query := s.db.WithContext(ctx)
|
|
269
283
|
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
270
|
-
query = query.Preload("<%= assoc.
|
|
284
|
+
query = query.Preload("<%= assoc.fieldName %>")
|
|
271
285
|
<% }) %>
|
|
272
286
|
<% if (it.primaryKeyType === 'uuid') { %>
|
|
273
287
|
if err := query.Where("id = ?", id).First(&item).Error; err != nil {
|
|
@@ -306,7 +320,7 @@ func (s *<%= it.entityName %>Service) Delete(ctx context.Context, id string) err
|
|
|
306
320
|
|
|
307
321
|
// toResponse converts a model to a response DTO
|
|
308
322
|
func (s *<%= it.entityName %>Service) toResponse(item *models.<%= it.entityName %>) dto.<%= it.entityName %>Response {
|
|
309
|
-
|
|
323
|
+
response := dto.<%= it.entityName %>Response{
|
|
310
324
|
ID: item.ID,
|
|
311
325
|
<% it.columns.forEach((column) => { %>
|
|
312
326
|
<%= column.pascalName %>: item.<%= column.pascalName %>,
|
|
@@ -317,8 +331,22 @@ func (s *<%= it.entityName %>Service) toResponse(item *models.<%= it.entityName
|
|
|
317
331
|
<% if (it.updatedAt) { %>
|
|
318
332
|
UpdatedAt: item.UpdatedAt,
|
|
319
333
|
<% } %>
|
|
320
|
-
<% it.associations.filter(a => a.
|
|
321
|
-
<%= assoc.
|
|
334
|
+
<% it.associations.filter(a => a.owns).forEach((assoc) => { %>
|
|
335
|
+
<%= assoc.fkField %>: item.<%= assoc.fkField %>,
|
|
322
336
|
<% }) %>
|
|
323
337
|
}
|
|
338
|
+
// Relations loaded by ?join= or eager loading.
|
|
339
|
+
<% it.associations.forEach((assoc) => { %>
|
|
340
|
+
<% if (assoc.type === 'ManyToOne' || assoc.type === 'OneToOne') { %>
|
|
341
|
+
if item.<%= assoc.fieldName %> != nil {
|
|
342
|
+
related := (&<%= assoc.name %>Service{}).toResponse(item.<%= assoc.fieldName %>)
|
|
343
|
+
response.<%= assoc.fieldName %> = &related
|
|
344
|
+
}
|
|
345
|
+
<% } else if (assoc.type === 'OneToMany' || (assoc.type === 'ManyToMany' && assoc.join)) { %>
|
|
346
|
+
for i := range item.<%= assoc.fieldName %> {
|
|
347
|
+
response.<%= assoc.fieldName %> = append(response.<%= assoc.fieldName %>, (&<%= assoc.name %>Service{}).toResponse(&item.<%= assoc.fieldName %>[i]))
|
|
348
|
+
}
|
|
349
|
+
<% } %>
|
|
350
|
+
<% }) %>
|
|
351
|
+
return response
|
|
324
352
|
}
|
|
@@ -710,7 +710,7 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
710
710
|
if strings.EqualFold(s.Direction, "DESC") {
|
|
711
711
|
dir = "DESC"
|
|
712
712
|
}
|
|
713
|
-
clause := fmt.Sprintf("%s %s", s.Field, dir)
|
|
713
|
+
clause := fmt.Sprintf("%s %s", quoteColumn(s.Field), dir)
|
|
714
714
|
if s.Nulls != "" {
|
|
715
715
|
clause = fmt.Sprintf("%s %s", clause, s.Nulls)
|
|
716
716
|
}
|
|
@@ -723,11 +723,16 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
723
723
|
var safe []string
|
|
724
724
|
for _, f := range opts.Fields {
|
|
725
725
|
col := f
|
|
726
|
+
alias := ""
|
|
726
727
|
if i := strings.Index(strings.ToUpper(f), " AS "); i != -1 {
|
|
727
728
|
col = strings.TrimSpace(f[:i])
|
|
729
|
+
alias = strings.TrimSpace(f[i+4:])
|
|
728
730
|
}
|
|
729
|
-
if allowedFields[col] {
|
|
730
|
-
safe = append(safe,
|
|
731
|
+
if allowedFields[col] && alias != "" {
|
|
732
|
+
safe = append(safe, quoteColumn(col)+" AS "+quoteColumn(alias))
|
|
733
|
+
} else if allowedFields[col] {
|
|
734
|
+
// gorm quotes a bare column name itself.
|
|
735
|
+
safe = append(safe, col)
|
|
731
736
|
} else if postgrest {
|
|
732
737
|
return query, 0, 1, queryErr("Unknown column '%s' in select", col)
|
|
733
738
|
}
|
|
@@ -739,7 +744,7 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
739
744
|
|
|
740
745
|
// Joins (Preloads)
|
|
741
746
|
for _, j := range opts.Joins {
|
|
742
|
-
query = query.Preload(j.Relation)
|
|
747
|
+
query = query.Preload(preloadName(j.Relation))
|
|
743
748
|
}
|
|
744
749
|
|
|
745
750
|
// Pagination
|
|
@@ -763,6 +768,25 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
763
768
|
return query, total, pageCount, nil
|
|
764
769
|
}
|
|
765
770
|
|
|
771
|
+
// quoteColumn quotes an allowlisted column name: the columns keep their
|
|
772
|
+
// .apsorc names, so seenAt must not fold to seenat.
|
|
773
|
+
func quoteColumn(c string) string {
|
|
774
|
+
return `"` + strings.ReplaceAll(c, `"`, `""`) + `"`
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// preloadName turns a relation as the .apsorc names it (author, posts,
|
|
778
|
+
// author.profile) into the Go field path gorm preloads (Author, Posts,
|
|
779
|
+
// Author.Profile), so ?join= takes the same names as TypeScript and Python.
|
|
780
|
+
func preloadName(relation string) string {
|
|
781
|
+
parts := strings.Split(relation, ".")
|
|
782
|
+
for i, p := range parts {
|
|
783
|
+
if p != "" {
|
|
784
|
+
parts[i] = strings.ToUpper(p[:1]) + p[1:]
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
return strings.Join(parts, ".")
|
|
788
|
+
}
|
|
789
|
+
|
|
766
790
|
// buildGroupExpr turns a PostgREST FilterGroup into a nested GORM expression
|
|
767
791
|
// (a *gorm.DB usable as a Where argument). Unknown columns are a client error
|
|
768
792
|
// (400). Returns nil when the group produced no applicable condition.
|
|
@@ -861,6 +885,7 @@ func parseJoinParam(raw string) ParsedJoin {
|
|
|
861
885
|
// ---------------------------------------------------------------------------
|
|
862
886
|
|
|
863
887
|
func applyOperator(query *gorm.DB, field, op, value string, useOr bool) *gorm.DB {
|
|
888
|
+
field = quoteColumn(field)
|
|
864
889
|
where := query.Where
|
|
865
890
|
if useOr {
|
|
866
891
|
where = query.Or
|
|
@@ -960,9 +985,10 @@ func splitValue(value string) []string {
|
|
|
960
985
|
// Booleans and numbers are converted so the database driver sends the
|
|
961
986
|
// correct wire type instead of a raw string.
|
|
962
987
|
func coerceValue(value string) interface{} {
|
|
988
|
+
// "1" and "0" stay numbers: an id or count filter of 1 is not a boolean.
|
|
963
989
|
low := strings.ToLower(value)
|
|
964
|
-
if low == "true" || low == "false" || low == "yes" || low == "no"
|
|
965
|
-
return low == "true" || low == "yes"
|
|
990
|
+
if low == "true" || low == "false" || low == "yes" || low == "no" {
|
|
991
|
+
return low == "true" || low == "yes"
|
|
966
992
|
}
|
|
967
993
|
if v, err := strconv.ParseInt(value, 10, 64); err == nil {
|
|
968
994
|
return v
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
<%~ includeFile('../header.eta', it) %>
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import event
|
|
4
|
+
|
|
5
|
+
from app.database import Base
|
|
6
|
+
<% it.modules.forEach(([m, name]) => { %>
|
|
7
|
+
from .<%= m %> import <%= name %> # noqa: F401
|
|
8
|
+
<% }) %>
|
|
9
|
+
|
|
10
|
+
# Run by create_all (DATABASE_SYNC=true) before it creates any table: the
|
|
11
|
+
# extensions the tables need, and a check that stops, printing the renames to
|
|
12
|
+
# run, when the database still has a join table or enum type under the name
|
|
13
|
+
# older generated models gave it.
|
|
14
|
+
_BEFORE_CREATE = [
|
|
15
|
+
<% it.statements.forEach((s) => { %>
|
|
16
|
+
<%~ s %>,
|
|
17
|
+
<% }) %>
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@event.listens_for(Base.metadata, "before_create")
|
|
22
|
+
def _apso_before_create(target, connection, **kw):
|
|
23
|
+
for statement in _BEFORE_CREATE:
|
|
24
|
+
connection.exec_driver_sql(statement)
|
|
@@ -6,8 +6,8 @@ from datetime import datetime, date
|
|
|
6
6
|
from decimal import Decimal
|
|
7
7
|
from uuid import UUID
|
|
8
8
|
|
|
9
|
-
from sqlalchemy import Column, Integer, String, Text, Boolean, Float, Numeric, Date, DateTime, JSON, Enum as SAEnum, ForeignKey, Index, UniqueConstraint, Table
|
|
10
|
-
from sqlalchemy.dialects.postgresql import UUID as PGUUID, JSONB, ARRAY,
|
|
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
|
|
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
|
|
13
13
|
|
|
@@ -23,13 +23,18 @@ if TYPE_CHECKING:
|
|
|
23
23
|
<% }) %>
|
|
24
24
|
<% } %>
|
|
25
25
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
# Tables, columns, keys, indexes and constraints are named and typed exactly as
|
|
27
|
+
# the migrations from `apso migrate` create them.
|
|
28
|
+
<% it.joinTables.forEach((join) => { %>
|
|
29
|
+
<%= join.name %> = Table(
|
|
30
|
+
"<%= join.name %>",
|
|
30
31
|
Base.metadata,
|
|
31
|
-
|
|
32
|
-
Column("<%=
|
|
32
|
+
<% join.columns.forEach((c) => { %>
|
|
33
|
+
Column("<%= c.name %>", <%~ c.args.join(', ') %>),
|
|
34
|
+
<% }) %>
|
|
35
|
+
<% join.tableArgs.forEach((a) => { %>
|
|
36
|
+
<%~ a %>,
|
|
37
|
+
<% }) %>
|
|
33
38
|
)
|
|
34
39
|
<% }) %>
|
|
35
40
|
|
|
@@ -38,48 +43,15 @@ class <%= it.name %>(Base):
|
|
|
38
43
|
SQLAlchemy model for <%= it.name %>
|
|
39
44
|
"""
|
|
40
45
|
__tablename__ = "<%= it.tableName %>"
|
|
41
|
-
|
|
42
|
-
<% /* Generate table arguments for indexes and unique constraints */ %>
|
|
43
|
-
<% if ((it.indexes && it.indexes.length > 0) || (it.uniques && it.uniques.length > 0)) { %>
|
|
44
46
|
__table_args__ = (
|
|
45
|
-
<% it.
|
|
46
|
-
|
|
47
|
-
<% }) %>
|
|
48
|
-
<% it.uniques.forEach((unique) => { %>
|
|
49
|
-
UniqueConstraint(<%~ unique.fields.map(f => `"${f}"`).join(', ') %><% if (unique.name) { %>, name="<%= unique.name %>"<% } %>),
|
|
47
|
+
<% it.tableArgs.forEach((a) => { %>
|
|
48
|
+
<%~ a %>,
|
|
50
49
|
<% }) %>
|
|
51
50
|
)
|
|
52
|
-
<% } %>
|
|
53
51
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
<%
|
|
57
|
-
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True)
|
|
58
|
-
<% } else { %>
|
|
59
|
-
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
|
60
|
-
<% } %>
|
|
61
|
-
<% } %>
|
|
62
|
-
|
|
63
|
-
<% /* Timestamp columns */ %>
|
|
64
|
-
<% if (it.createdAt) { %>
|
|
65
|
-
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
66
|
-
<% } %>
|
|
67
|
-
<% if (it.updatedAt) { %>
|
|
68
|
-
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
|
69
|
-
<% } %>
|
|
70
|
-
|
|
71
|
-
# Columns
|
|
72
|
-
<%
|
|
73
|
-
// Filter out id (if createPrimaryKey), createdAt, and updatedAt since they're handled separately
|
|
74
|
-
const columnsToProcess = it.columns.filter(c => {
|
|
75
|
-
if (it.createPrimaryKey && c.name === 'id') return false;
|
|
76
|
-
if (it.createdAt && c.name === 'createdAt') return false;
|
|
77
|
-
if (it.updatedAt && c.name === 'updatedAt') return false;
|
|
78
|
-
return true;
|
|
79
|
-
});
|
|
80
|
-
columnsToProcess.forEach((field) => { -%>
|
|
81
|
-
<%~ includeFile(`./model-col-${field.type}`, { field, entityName: it.name }) %>
|
|
82
|
-
<% }); %>
|
|
52
|
+
<% it.columns.forEach((c) => { %>
|
|
53
|
+
<%= c.name %>: Mapped[<%~ c.pyType %>] = mapped_column(<%~ c.args.join(', ') %>)
|
|
54
|
+
<% }) %>
|
|
83
55
|
|
|
84
56
|
# Relationships
|
|
85
57
|
<% it.associations.forEach((assoc) => { %>
|
|
@@ -87,25 +59,21 @@ columnsToProcess.forEach((field) => { -%>
|
|
|
87
59
|
<%= assoc.pluralizedRelationshipName %>: Mapped[List["<%= assoc.name %>"]] = relationship(
|
|
88
60
|
"<%= assoc.name %>",
|
|
89
61
|
back_populates="<%= assoc.inverseSidePropertyName %>",
|
|
62
|
+
# The foreign key's ON DELETE decides, not the ORM (it would null it).
|
|
63
|
+
passive_deletes="all",
|
|
90
64
|
lazy="selectin"
|
|
91
65
|
)
|
|
92
|
-
<% } else if (assoc.type === 'ManyToOne') { %>
|
|
93
|
-
# Foreign key for <%= assoc.name %>
|
|
94
|
-
<%= assoc.camelCasedId %>: Mapped[<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>Optional[UUID]<% } else { %>Optional[int]<% } %>] = mapped_column(
|
|
95
|
-
<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>PGUUID(as_uuid=True)<% } else { %>Integer<% } %>,
|
|
96
|
-
ForeignKey("<%= it.tableNames[assoc.name] || assoc.name.toLowerCase() %>.id"<% if (assoc.cascadeDelete) { %>, ondelete="CASCADE"<% } %>),
|
|
97
|
-
nullable=<%= assoc.nullable ? 'True' : 'False' %><% if (assoc.index) { %>,
|
|
98
|
-
index=True<% } %>
|
|
99
|
-
)
|
|
66
|
+
<% } else if (assoc.type === 'ManyToOne' || (assoc.type === 'OneToOne' && assoc.joinTable)) { %>
|
|
100
67
|
<%= assoc.relationshipName %>: Mapped[Optional["<%= assoc.name %>"]] = relationship(
|
|
101
68
|
"<%= assoc.name %>",
|
|
69
|
+
foreign_keys=[<%= assoc.type === 'ManyToOne' ? assoc.camelCasedId : assoc.fkColumn %>],
|
|
102
70
|
<% if (assoc.biDirectional) { %>back_populates="<%= assoc.inverseSidePropertyName %>",<% } %>
|
|
103
71
|
lazy="selectin"
|
|
104
72
|
)
|
|
105
|
-
<% } else if (assoc.type === 'ManyToMany') { %>
|
|
73
|
+
<% } else if (assoc.type === 'ManyToMany' && assoc.secondary) { %>
|
|
106
74
|
<%= assoc.pluralizedRelationshipName %>: Mapped[List["<%= assoc.name %>"]] = relationship(
|
|
107
75
|
"<%= assoc.name %>",
|
|
108
|
-
secondary
|
|
76
|
+
secondary="<%= assoc.secondary %>",
|
|
109
77
|
<% if (assoc.biDirectional) { %>back_populates="<%= assoc.inverseSidePropertyName %>",<% } %>
|
|
110
78
|
lazy="selectin"
|
|
111
79
|
)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<%= it.field.name %>: <% if (!it.field.required || it.forUpdate) { %>Optional[List[<%= it.field.
|
|
1
|
+
<%= it.field.name %>: <% if (!it.field.required || it.forUpdate) { %>Optional[List[<%= it.field.arrayItemType %>]] = None<% } else { %>List[<%= it.field.arrayItemType %>]<% } %>
|
|
@@ -25,11 +25,11 @@ def _columns(value: Any) -> Any:
|
|
|
25
25
|
class <%= it.entityName %>Base(BaseModel):
|
|
26
26
|
"""Base schema with common fields for <%= it.entityName %>"""
|
|
27
27
|
<% it.columns.filter(c => !['id', 'createdAt', 'updatedAt', 'created_at', 'updated_at'].includes(c.name)).forEach((field) => { -%>
|
|
28
|
-
<%~ includeFile(`./schema-col-${field.type}`, { field, entityName: it.entityName }) %>
|
|
28
|
+
<%~ includeFile(`./schema-col-${field.schemaTemplate || field.type}`, { field, entityName: it.entityName }) %>
|
|
29
29
|
<% }); -%>
|
|
30
30
|
|
|
31
31
|
<% /* Add foreign key fields for ManyToOne relationships */ -%>
|
|
32
|
-
<% it.associations.filter(a => a.type === 'ManyToOne').forEach((assoc) => { -%>
|
|
32
|
+
<% it.associations.filter(a => a.type === 'ManyToOne' || (a.type === 'OneToOne' && a.joinTable)).forEach((assoc) => { -%>
|
|
33
33
|
<%= assoc.camelCasedId %>: Optional[<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>UUID<% } else { %>int<% } %>] = None
|
|
34
34
|
<% }); -%>
|
|
35
35
|
|
|
@@ -37,21 +37,21 @@ class <%= it.entityName %>Base(BaseModel):
|
|
|
37
37
|
class <%= it.entityName %>Create(BaseModel):
|
|
38
38
|
"""Schema for creating a new <%= it.entityName %>"""
|
|
39
39
|
<% it.columns.filter(c => !['id', 'createdAt', 'updatedAt', 'created_at', 'updated_at'].includes(c.name)).forEach((field) => { -%>
|
|
40
|
-
<%~ includeFile(`./schema-col-${field.type}`, { field, entityName: it.entityName, forCreate: true }) %>
|
|
40
|
+
<%~ includeFile(`./schema-col-${field.schemaTemplate || field.type}`, { field, entityName: it.entityName, forCreate: true }) %>
|
|
41
41
|
<% }); -%>
|
|
42
42
|
<% /* Add foreign key fields for ManyToOne relationships */ -%>
|
|
43
|
-
<% it.associations.filter(a => a.type === 'ManyToOne').forEach((assoc) => { -%>
|
|
44
|
-
<%= assoc.camelCasedId %>: <% if (assoc.nullable) { %>Optional[<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>UUID<% } else { %>int<% } %>] = None<% } else { %><% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>UUID<% } else { %>int<% } %><% } %>
|
|
43
|
+
<% it.associations.filter(a => a.type === 'ManyToOne' || (a.type === 'OneToOne' && a.joinTable)).forEach((assoc) => { -%>
|
|
44
|
+
<%= assoc.camelCasedId %>: <% if (assoc.nullable || assoc.type === 'OneToOne') { %>Optional[<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>UUID<% } else { %>int<% } %>] = None<% } else { %><% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>UUID<% } else { %>int<% } %><% } %>
|
|
45
45
|
<% }); -%>
|
|
46
46
|
|
|
47
47
|
|
|
48
48
|
class <%= it.entityName %>Update(BaseModel):
|
|
49
49
|
"""Schema for updating an existing <%= it.entityName %>"""
|
|
50
50
|
<% it.columns.filter(c => !['id', 'createdAt', 'updatedAt', 'created_at', 'updated_at'].includes(c.name)).forEach((field) => { -%>
|
|
51
|
-
<%~ includeFile(`./schema-col-${field.type}`, { field, entityName: it.entityName, forUpdate: true }) %>
|
|
51
|
+
<%~ includeFile(`./schema-col-${field.schemaTemplate || field.type}`, { field, entityName: it.entityName, forUpdate: true }) %>
|
|
52
52
|
<% }); -%>
|
|
53
53
|
<% /* Add foreign key fields for ManyToOne relationships */ -%>
|
|
54
|
-
<% it.associations.filter(a => a.type === 'ManyToOne').forEach((assoc) => { -%>
|
|
54
|
+
<% it.associations.filter(a => a.type === 'ManyToOne' || (a.type === 'OneToOne' && a.joinTable)).forEach((assoc) => { -%>
|
|
55
55
|
<%= assoc.camelCasedId %>: Optional[<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>UUID<% } else { %>int<% } %>] = None
|
|
56
56
|
<% }); -%>
|
|
57
57
|
|
|
@@ -74,10 +74,10 @@ class <%= it.entityName %>(BaseModel):
|
|
|
74
74
|
updatedAt: datetime = Field(alias="updated_at")
|
|
75
75
|
<% } -%>
|
|
76
76
|
<% it.columns.filter(c => !['id', 'createdAt', 'updatedAt', 'created_at', 'updated_at'].includes(c.name)).forEach((field) => { -%>
|
|
77
|
-
<%~ includeFile(`./schema-col-${field.type}`, { field, entityName: it.entityName }) %>
|
|
77
|
+
<%~ includeFile(`./schema-col-${field.schemaTemplate || field.type}`, { field, entityName: it.entityName }) %>
|
|
78
78
|
<% }); -%>
|
|
79
79
|
<% /* Add foreign key fields for ManyToOne relationships */ -%>
|
|
80
|
-
<% it.associations.filter(a => a.type === 'ManyToOne').forEach((assoc) => { -%>
|
|
80
|
+
<% it.associations.filter(a => a.type === 'ManyToOne' || (a.type === 'OneToOne' && a.joinTable)).forEach((assoc) => { -%>
|
|
81
81
|
<%= assoc.camelCasedId %>: Optional[<% if (assoc.referencedEntityPrimaryKeyType === 'uuid') { %>UUID<% } else { %>int<% } %>] = None
|
|
82
82
|
<% }); -%>
|
|
83
83
|
<% /* Add relationship fields */ -%>
|
|
@@ -12,6 +12,18 @@ export declare const fieldTypeToColumnType: Record<string, string>;
|
|
|
12
12
|
*/
|
|
13
13
|
export declare const normalizeFieldType: (type: string) => string;
|
|
14
14
|
export declare const getJsTypeFromFieldType: (type: FieldType | string) => string;
|
|
15
|
+
/**
|
|
16
|
+
* Postgres element type of an "array" field, as the DDL writer reads it.
|
|
17
|
+
* Python read `arrayType` and Go `arrayItemType` before `elementType`; both
|
|
18
|
+
* still work so older schemas generate the same code.
|
|
19
|
+
*
|
|
20
|
+
* @param {Field} field - An "array" field from .apsorc.
|
|
21
|
+
* @returns {string} The element type, "text" when none is set.
|
|
22
|
+
*/
|
|
23
|
+
export declare const arrayElementType: (field: Field & {
|
|
24
|
+
arrayType?: string;
|
|
25
|
+
arrayItemType?: string;
|
|
26
|
+
}) => string;
|
|
15
27
|
export declare const getDefaultValueForField: (field: Field) => string | null;
|
|
16
28
|
export declare const getFieldForTemplate: (fields: Field[], entityName: string) => ComputedField[];
|
|
17
29
|
export declare const fieldToEnumType: (fieldName: string, entityName: string) => string;
|