Skip to content

Commit b76997a

Browse files
authored
orm: set default value for require field if database value is null (fix #24221) (#24222)
1 parent 3b4c016 commit b76997a

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

vlib/orm/orm_func.v

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -432,7 +432,7 @@ fn (qb &QueryBuilder[T]) map_row(row []Primitive) !T {
432432
if index >= 0 {
433433
value := row[index]
434434

435-
if value == Primitive(Null{}) && m.nullable {
435+
if value == Primitive(Null{}) {
436436
// set to none by default
437437
} else {
438438
$if field.typ is i8 || field.typ is ?i8 {

vlib/orm/orm_func_test.v

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,17 @@ struct User {
4040
option_string ?string
4141
}
4242

43+
// UserPart is part of User, so we can access only part of the `sys_users` table
44+
// note: for test, we modify `created_at` field from option to require
45+
// a `null` value in database, will map to default value of the require field in struct
46+
@[table: 'sys_users']
47+
struct UserPart {
48+
id int @[primary; serial]
49+
name string
50+
created_at time.Time @[sql_type: 'TIMESTAMP']
51+
updated_at time.Time @[sql_type: 'TIMESTAMP']
52+
}
53+
4354
fn test_orm_func_where() {
4455
mut db := sqlite.connect(':memory:')!
4556
defer { db.close() or {} }
@@ -495,4 +506,11 @@ fn test_orm_func_stmts() {
495506
.query()!
496507
assert final_users.len == 5
497508
assert final_users[0].age == 18
509+
510+
// access only part of the table
511+
mut part := orm.new_query[UserPart](db)
512+
part_user := part.query()!
513+
// a `null` value in database, will map to default value of the require field in struct
514+
assert part_user.filter(it.name == 'Silly')[0].created_at == time.Time{}
515+
assert part_user.len == 5
498516
}

0 commit comments

Comments
 (0)