orm: fix code generation for an option time.Time field (#20031)

This commit is contained in:
Felipe Pena 2023-11-29 14:30:34 -03:00 committed by GitHub
parent dc3ea0f87f
commit 00b1ce5760
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 59 additions and 1 deletions

View File

@ -136,6 +136,7 @@ const skip_with_fsanitize_memory = [
'vlib/orm/orm_custom_operators_test.v',
'vlib/orm/orm_fk_test.v',
'vlib/orm/orm_references_test.v',
'vlib/orm/orm_option_time_test.v',
'vlib/db/sqlite/sqlite_test.v',
'vlib/db/sqlite/sqlite_orm_test.v',
'vlib/db/sqlite/sqlite_vfs_lowlevel_test.v',
@ -223,6 +224,7 @@ const skip_on_ubuntu_musl = [
'vlib/orm/orm_custom_operators_test.v',
'vlib/orm/orm_fk_test.v',
'vlib/orm/orm_references_test.v',
'vlib/orm/orm_option_time_test.v',
'vlib/v/tests/orm_enum_test.v',
'vlib/v/tests/orm_sub_struct_test.v',
'vlib/v/tests/orm_sub_array_struct_test.v',

View File

@ -0,0 +1,54 @@
import db.sqlite
import time
@[table: 'foos']
struct Foo {
id int @[primary; sql: serial]
name string
created_at time.Time @[default: 'CURRENT_TIME']
updated_at ?string @[sql_type: 'TIMESTAMP']
deleted_at ?time.Time
children []Child @[fkey: 'parent_id']
}
struct Child {
id int @[primary; sql: serial]
parent_id int
name string
}
fn test_main() {
mut db := sqlite.connect(':memory:') or { panic(err) }
defer {
db.close() or { panic(err) }
}
sql db {
create table Foo
}!
foo := Foo{
name: 'abc'
created_at: time.now()
// updated_at defaults to none
// deleted_at defaults to none
children: [
Child{
name: 'abc'
},
Child{
name: 'def'
},
]
}
sql db {
insert foo into Foo
}!
data := sql db {
select from Foo
}![0]
assert data.id == 1
assert data.updated_at == none
assert data.deleted_at == none
}

View File

@ -370,6 +370,7 @@ fn (mut g Gen) write_orm_insert_with_last_ids(node ast.SqlStmtLine, connection_v
}
mut sym := g.table.sym(field.typ)
mut typ := sym.cname
mut ctyp := sym.cname
if sym.kind == .struct_ && typ != 'time__Time' {
g.writeln('(*(orm__Primitive*) array_get(${last_ids_arr}, ${structs})),')
structs++
@ -377,13 +378,14 @@ fn (mut g Gen) write_orm_insert_with_last_ids(node ast.SqlStmtLine, connection_v
}
// fields processed hereafter can be NULL...
if typ == 'time__Time' {
ctyp = 'time__Time'
typ = 'time'
} else if sym.kind == .enum_ {
typ = 'i64'
}
var := '${node.object_var}${member_access_type}${c_name(field.name)}'
if field.typ.has_flag(.option) {
g.writeln('${var}.state == 2? _const_orm__null_primitive : orm__${typ}_to_primitive(*(${typ}*)(${var}.data)),')
g.writeln('${var}.state == 2? _const_orm__null_primitive : orm__${typ}_to_primitive(*(${ctyp}*)(${var}.data)),')
} else {
g.writeln('orm__${typ}_to_primitive(${var}),')
}