Skip to content

Commit 9702d4c

Browse files
committed
Fix SQLite TIMESTAMP mapping, add catch-all type validation, refactor default func helpers
- Fix critical SQLite dialect bug: TIMESTAMP columns no longer mapped to TEXT in migration/sqliteDialect.go. Previous mapping caused modernc/sqlite to treat timestamp columns as TEXT, breaking time.Time scan. Now TIMESTAMP correctly maps to "TIMESTAMP" so the driver auto-scans strings as time.Time. - Add _time_format=sqlite DSN parameter to integration/main.go SQLite connection string for consistent time serialization. - Add missing catch-all type validation in validate{Model}Create template (model_create.gotpl). Non-string/non-int scalar types (time.Time, bool, float64, json.RawMessage, []byte) now get Go type-assertion validation via the template fallback else branch using trimPrefix. - Add isKnownDefaultFunc() and defaultFuncCall() to generator.go FuncMap. ToRowMap and cols/vals builder in model_create.gotpl use these helpers instead of deep else-if chains per function. Adding a new default function only requires updating the two maps in generator.go. - Add createdAt DateTime @default(now()) to Profile schema and regenerate generated client files to reflect the new field.
1 parent f601471 commit 9702d4c

12 files changed

Lines changed: 142 additions & 43 deletions

File tree

‎generator/generator.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,24 @@ func GenerateClient(sch schema.Schema, pkgName string, parentImportPath string,
130130
return false
131131
},
132132
"trimPrefix": strings.TrimPrefix,
133+
"isKnownDefaultFunc": func(funcName string) bool {
134+
switch funcName {
135+
case "autoincrement", "cuid", "uuid", "now":
136+
return true
137+
}
138+
return false
139+
},
140+
"defaultFuncCall": func(funcName string) string {
141+
switch funcName {
142+
case "cuid":
143+
return "generateCUID()"
144+
case "uuid":
145+
return "generateUUID()"
146+
case "now":
147+
return "time.Now()"
148+
}
149+
return ""
150+
},
133151
"hasStringField": func(m *schema.Model) bool {
134152
for _, sf := range m.ScalarFields {
135153
if sf.GoType == "string" || strings.Contains(sf.GoType, "string") {

‎generator/templates/model_create.gotpl‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,10 @@ func validate{{ .Model.Name }}Create(assignments []FieldAssignment) error {
8282
}
8383
{{- end }}
8484
{{- end }}
85+
{{- else }}
86+
if _, ok := a.Val.({{ trimPrefix $field.GoType "*" }}); !ok {
87+
errs.Add("{{ $field.Name }}", a.Val, "type", "field {{ $field.Name }} must be of type {{ trimPrefix $field.GoType "*" }}")
88+
}
8589
{{- end }}
8690
{{- end }}
8791
}
@@ -173,17 +177,15 @@ func (s *{{ .Model.Name }}Create) ToRowMap() map[string]any {
173177
if s.{{ $fieldName }} != nil {
174178
m["{{ $col }}"] = *s.{{ $fieldName }}
175179
}
176-
{{- else }}
180+
{{- else if $field.Default.FuncName | isKnownDefaultFunc }}
177181
if s.{{ $fieldName }} != nil {
178182
m["{{ $col }}"] = *s.{{ $fieldName }}
179183
} else {
180-
{{- if eq $field.Default.FuncName "cuid" }}
181-
m["{{ $col }}"] = generateCUID()
182-
{{- else if eq $field.Default.FuncName "uuid" }}
183-
m["{{ $col }}"] = generateUUID()
184-
{{- else if eq $field.Default.FuncName "now" }}
185-
m["{{ $col }}"] = time.Now()
186-
{{- end }}
184+
m["{{ $col }}"] = {{ defaultFuncCall $field.Default.FuncName }}
185+
}
186+
{{- else }}
187+
if s.{{ $fieldName }} != nil {
188+
m["{{ $col }}"] = *s.{{ $fieldName }}
187189
}
188190
{{- end }}
189191
{{- else if or $field.Optional (ne $field.Default nil) }}
@@ -250,19 +252,18 @@ func (q *Queries) execute{{ .Model.Name }}Create(ctx context.Context, assignment
250252
cols = append(cols, "{{ $col }}")
251253
vals = append(vals, *input.{{ $fieldName }})
252254
}
253-
{{- else }}
255+
{{- else if $field.Default.FuncName | isKnownDefaultFunc }}
254256
if input.{{ $fieldName }} != nil {
255257
cols = append(cols, "{{ $col }}")
256258
vals = append(vals, *input.{{ $fieldName }})
257259
} else {
258260
cols = append(cols, "{{ $col }}")
259-
{{- if eq $field.Default.FuncName "cuid" }}
260-
vals = append(vals, generateCUID())
261-
{{- else if eq $field.Default.FuncName "uuid" }}
262-
vals = append(vals, generateUUID())
263-
{{- else if eq $field.Default.FuncName "now" }}
264-
vals = append(vals, time.Now())
265-
{{- end }}
261+
vals = append(vals, {{ defaultFuncCall $field.Default.FuncName }})
262+
}
263+
{{- else }}
264+
if input.{{ $fieldName }} != nil {
265+
cols = append(cols, "{{ $col }}")
266+
vals = append(vals, *input.{{ $fieldName }})
266267
}
267268
{{- end }}
268269
{{- else if or $field.Optional (ne $field.Default nil) }}

‎integration/main.go‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"integration/valk/post"
1212
"integration/valk/profile"
1313
"integration/valk/user"
14+
"time"
1415

1516
"log"
1617

@@ -101,11 +102,34 @@ func seed(db *valk.DB, ctx context.Context) *SeedData {
101102
prof, err := db.Profile.Create(
102103
profile.Bio.Set("BLEH"),
103104
profile.UserId.Set(referred.Id),
105+
profile.CreatedAt.Set(time.Now()),
104106
).Exec(ctx)
105107
if err != nil {
106108
log.Fatalf("failed to create profile: %v", err)
107109
}
108-
_ = prof
110+
fmt.Println("PROFILE:")
111+
printJSON(prof)
112+
113+
categoryTest, err := db.Category.Create(
114+
category.Name.Set("TEST"),
115+
).Exec(ctx)
116+
117+
if err != nil {
118+
log.Fatalf("failed to create category: %v", err)
119+
}
120+
fmt.Println("CATEGORY:")
121+
printJSON(categoryTest)
122+
123+
AnothercategoryTest, err := db.Category.Create(
124+
category.Id.Set(24),
125+
category.Name.Set("TEST2"),
126+
).Exec(ctx)
127+
128+
if err != nil {
129+
log.Fatalf("failed to create category: %v", err)
130+
}
131+
fmt.Println("CATEGORY2:")
132+
printJSON(AnothercategoryTest)
109133

110134
p, err := db.Post.Create(
111135
post.Title.Set("Valkyrie ORM Deep Dive"),
@@ -274,7 +298,7 @@ func main() {
274298
}
275299

276300
func openConn() *valk.DB {
277-
db, err := valk.Open("sqlite", "file::memory:?_pragma=foreign_keys(1)")
301+
db, err := valk.Open("sqlite", "file::memory:?_pragma=foreign_keys(1)&_time_format=sqlite")
278302
if err != nil {
279303
log.Fatalf("failed to open db: %v", err)
280304
}

‎integration/schema.prisma‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,11 @@ model User {
2929
}
3030

3131
model Profile {
32-
id String @id @default(cuid())
33-
bio String?
34-
userId String @unique
35-
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
32+
id String @id @default(cuid())
33+
bio String?
34+
userId String @unique
35+
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
36+
createdAt DateTime @default(now())
3637
}
3738

3839
model Post {

‎integration/valk/client.go‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,10 @@ type Queries struct {
167167
User *UserDelegate
168168
// Profile provides CRUD operations for Profile.
169169
//
170-
// id string default: cuid()
171-
// bio string optional
172-
// userId string required
170+
// id string default: cuid()
171+
// bio string optional
172+
// userId string required
173+
// createdAt time.Time default: now()
173174
Profile *ProfileDelegate
174175
// Post provides CRUD operations for Post.
175176
//

‎integration/valk/comment.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,9 @@ func validateCommentCreate(assignments []FieldAssignment) error {
240240
}
241241
}
242242
case "meta":
243+
if _, ok := a.Val.(json.RawMessage); !ok {
244+
errs.Add("meta", a.Val, "type", "field meta must be of type json.RawMessage")
245+
}
243246
}
244247
}
245248
if !provided["dummy3"] {

‎integration/valk/migrations/00001_init.sql‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ CREATE TABLE `Profile` (
1919
`id` text NOT NULL,
2020
`bio` text NULL,
2121
`userId` text NOT NULL,
22+
`createdAt` timestamp NOT NULL DEFAULT (CURRENT_TIMESTAMP),
2223
PRIMARY KEY (`id`),
2324
CONSTRAINT `Profile_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE
2425
);

‎integration/valk/post.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,13 @@ func validatePostCreate(assignments []FieldAssignment) error {
177177
}
178178
}
179179
case "content":
180+
if _, ok := a.Val.(string); !ok {
181+
errs.Add("content", a.Val, "type", "field content must be of type string")
182+
}
180183
case "published":
184+
if _, ok := a.Val.(bool); !ok {
185+
errs.Add("published", a.Val, "type", "field published must be of type bool")
186+
}
181187
case "authorId":
182188
if v, ok := a.Val.(string); ok {
183189
if v == "" {

‎integration/valk/profile.go‎

Lines changed: 50 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,38 +5,43 @@ import (
55
"fmt"
66
"slices"
77
"strings"
8+
"time"
89
"unicode/utf8"
910
)
1011

1112
// Profile represents the database model
1213
type Profile struct {
13-
Id string `db:"id" json:"id"`
14-
Bio *string `db:"bio" json:"bio,omitempty"`
15-
UserId string `db:"userId" json:"userId"`
16-
User *User `json:"user,omitempty"`
14+
Id string `db:"id" json:"id"`
15+
Bio *string `db:"bio" json:"bio,omitempty"`
16+
UserId string `db:"userId" json:"userId"`
17+
CreatedAt time.Time `db:"createdAt" json:"createdAt"`
18+
User *User `json:"user,omitempty"`
1719
}
1820

1921
// ProfileCreate is used for hooks only — the Create API uses FieldAssignment
2022
type ProfileCreate struct {
21-
Id *string `json:"id"`
22-
Bio *string `json:"bio"`
23-
UserId string `json:"userId"`
23+
Id *string `json:"id"`
24+
Bio *string `json:"bio"`
25+
UserId string `json:"userId"`
26+
CreatedAt *time.Time `json:"createdAt"`
2427
}
2528

2629
// ProfileSelect specifies which fields to include
2730
type ProfileSelect struct {
28-
Id bool `json:"id"`
29-
Bio bool `json:"bio"`
30-
UserId bool `json:"userId"`
31-
User *UserSelect `json:"user,omitempty"`
31+
Id bool `json:"id"`
32+
Bio bool `json:"bio"`
33+
UserId bool `json:"userId"`
34+
CreatedAt bool `json:"createdAt"`
35+
User *UserSelect `json:"user,omitempty"`
3236
}
3337

3438
// ProfileOmit specifies which fields to exclude
3539
type ProfileOmit struct {
36-
Id bool `json:"id"`
37-
Bio bool `json:"bio"`
38-
UserId bool `json:"userId"`
39-
User *UserOmit `json:"user,omitempty"`
40+
Id bool `json:"id"`
41+
Bio bool `json:"bio"`
42+
UserId bool `json:"userId"`
43+
CreatedAt bool `json:"createdAt"`
44+
User *UserOmit `json:"user,omitempty"`
4045
}
4146

4247
type ProfileDelegate struct {
@@ -68,6 +73,8 @@ func (m *Profile) ScanFields(cols []string) []any {
6873
targets[i] = &m.Bio
6974
case "userId":
7075
targets[i] = &m.UserId
76+
case "createdAt":
77+
targets[i] = &m.CreatedAt
7178
}
7279
}
7380
return targets
@@ -77,19 +84,21 @@ var profileDefaultCols = []string{
7784
"id",
7885
"bio",
7986
"userId",
87+
"createdAt",
8088
}
8189

8290
func (q *Queries) selectProfileCols(selects *ProfileSelect, omits *ProfileOmit, forceCols ...string) []string {
8391
if selects == nil && omits == nil && len(forceCols) == 0 {
8492
return profileDefaultCols
8593
}
8694

87-
anySelected := selects != nil && (selects.Id || selects.Bio || selects.UserId || selects.User != nil)
95+
anySelected := selects != nil && (selects.Id || selects.Bio || selects.UserId || selects.CreatedAt || selects.User != nil)
8896

8997
specs := []colSpec{
9098
{"id", selects != nil && selects.Id, omits != nil && omits.Id, selects != nil && selects.hasAnyRelation()},
9199
{"bio", selects != nil && selects.Bio, omits != nil && omits.Bio, false},
92100
{"userId", selects != nil && selects.UserId, omits != nil && omits.UserId, selects != nil && selects.User != nil},
101+
{"createdAt", selects != nil && selects.CreatedAt, omits != nil && omits.CreatedAt, false},
93102
}
94103

95104
cols := computeCols(specs, selects != nil, anySelected)
@@ -107,6 +116,7 @@ var ProfileColOrder = []string{
107116
"id",
108117
"bio",
109118
"userId",
119+
"createdAt",
110120
}
111121

112122
func (s *ProfileSelect) hasAnyRelation() bool {
@@ -141,6 +151,9 @@ func validateProfileCreate(assignments []FieldAssignment) error {
141151
}
142152
}
143153
case "bio":
154+
if _, ok := a.Val.(string); !ok {
155+
errs.Add("bio", a.Val, "type", "field bio must be of type string")
156+
}
144157
case "userId":
145158
if v, ok := a.Val.(string); ok {
146159
if v == "" {
@@ -153,6 +166,10 @@ func validateProfileCreate(assignments []FieldAssignment) error {
153166
errs.Add("userId", v, "safety", "string must be valid UTF-8")
154167
}
155168
}
169+
case "createdAt":
170+
if _, ok := a.Val.(time.Time); !ok {
171+
errs.Add("createdAt", a.Val, "type", "field createdAt must be of type time.Time")
172+
}
156173
}
157174
}
158175
if !provided["userId"] {
@@ -181,13 +198,17 @@ func assignmentsToProfileCreate(assignments []FieldAssignment) ProfileCreate {
181198
if v, ok := a.Val.(string); ok {
182199
input.UserId = v
183200
}
201+
case "createdAt":
202+
if v, ok := a.Val.(time.Time); ok {
203+
input.CreatedAt = &v
204+
}
184205
}
185206
}
186207
return input
187208
}
188209

189210
func (s *ProfileCreate) ToRowMap() map[string]any {
190-
m := make(map[string]any, 3)
211+
m := make(map[string]any, 4)
191212
if s.Id != nil {
192213
m["id"] = *s.Id
193214
} else {
@@ -197,6 +218,11 @@ func (s *ProfileCreate) ToRowMap() map[string]any {
197218
m["bio"] = *s.Bio
198219
}
199220
m["userId"] = s.UserId
221+
if s.CreatedAt != nil {
222+
m["createdAt"] = *s.CreatedAt
223+
} else {
224+
m["createdAt"] = time.Now()
225+
}
200226
return m
201227
}
202228

@@ -228,6 +254,13 @@ func (q *Queries) executeProfileCreate(ctx context.Context, assignments []FieldA
228254
}
229255
cols = append(cols, "userId")
230256
vals = append(vals, input.UserId)
257+
if input.CreatedAt != nil {
258+
cols = append(cols, "createdAt")
259+
vals = append(vals, *input.CreatedAt)
260+
} else {
261+
cols = append(cols, "createdAt")
262+
vals = append(vals, time.Now())
263+
}
231264

232265
returningCols := q.selectProfileCols(selects, omits)
233266

‎integration/valk/profile/profile.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package profile
33
import (
44
"fmt"
55
"integration/valk"
6+
"time"
67
)
78

89
type UniquePredicate struct {
@@ -42,3 +43,5 @@ var Id = valk.StringUniqueField{Column: "id"}
4243
var Bio = valk.StringField{Column: "bio"}
4344

4445
var UserId = valk.StringUniqueField{Column: "userId"}
46+
47+
var CreatedAt = valk.Field[time.Time]{Column: "createdAt"}

0 commit comments

Comments
 (0)