diff --git a/cmd/tools/vtest-self.v b/cmd/tools/vtest-self.v index 55f9e5ed78..8f459abdfc 100644 --- a/cmd/tools/vtest-self.v +++ b/cmd/tools/vtest-self.v @@ -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', diff --git a/vlib/orm/orm_option_time_test.v b/vlib/orm/orm_option_time_test.v new file mode 100644 index 0000000000..4f44a4e1e8 --- /dev/null +++ b/vlib/orm/orm_option_time_test.v @@ -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 +} diff --git a/vlib/v/gen/c/orm.v b/vlib/v/gen/c/orm.v index a0ae8cd68a..683a05b260 100644 --- a/vlib/v/gen/c/orm.v +++ b/vlib/v/gen/c/orm.v @@ -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}),') }