Skip to content

Commit

Permalink
orm: allow comptime field.name as field name (fix #22329) (#22344)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Sep 29, 2024
1 parent 2ab1523 commit 6f97ced
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 2 deletions.
2 changes: 2 additions & 0 deletions cmd/tools/vtest-self.v
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ const skip_with_fsanitize_memory = [
'vlib/orm/orm_option_time_test.v',
'vlib/db/sqlite/sqlite_test.v',
'vlib/db/sqlite/sqlite_orm_test.v',
'vlib/db/sqlite/sqlite_comptime_field_test.v',
'vlib/db/sqlite/parent_child_test.v',
'vlib/db/sqlite/sqlite_vfs_lowlevel_test.v',
'vlib/v/tests/orm_enum_test.v',
Expand Down Expand Up @@ -240,6 +241,7 @@ const skip_on_ubuntu_musl = [
'vlib/net/http/status_test.v',
'vlib/db/sqlite/sqlite_test.v',
'vlib/db/sqlite/sqlite_orm_test.v',
'vlib/db/sqlite/sqlite_comptime_field_test.v',
'vlib/db/sqlite/sqlite_vfs_lowlevel_test.v',
'vlib/db/sqlite/parent_child_test.v',
'vlib/orm/orm_test.v',
Expand Down
43 changes: 43 additions & 0 deletions vlib/db/sqlite/sqlite_comptime_field_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
module main

import db.sqlite

@[table: 'blog']
pub struct Blog {
id int @[primary; sql: serial]
slug string
language string
}

fn records_by_field[T](db sqlite.DB, fieldname string, value string) ![]T {
$for field in T.fields {
if field.name == fieldname {
entries := sql db {
select from Blog where field.name == value
} or { return err }
return entries
}
}
return error('fieldname not found')
}

fn test_main() {
db := sqlite.connect(':memory:')!
sql db {
create table Blog
}!

row := Blog{
slug: 'Test'
language: 'v'
}

sql db {
insert row into Blog
}!
rows := records_by_field[Blog](db, 'language', 'v') or {
println(err)
return
}
assert rows.len == 1
}
3 changes: 2 additions & 1 deletion vlib/v/checker/orm.v
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,8 @@ fn (mut c Checker) check_where_expr_has_no_pointless_exprs(table_type_symbol &as
|| expr.left is ast.PrefixExpr {
c.check_where_expr_has_no_pointless_exprs(table_type_symbol, field_names,
expr.left)
} else {
} else if !(expr.left is ast.SelectorExpr
&& c.comptime.is_comptime_selector_field_name(expr.left, 'name')) {
c.orm_error(has_no_field_error, expr.left.pos())
}

Expand Down
6 changes: 5 additions & 1 deletion vlib/v/gen/c/orm.v
Original file line number Diff line number Diff line change
Expand Up @@ -809,7 +809,11 @@ fn (mut g Gen) write_orm_where_expr(expr ast.Expr, mut fields []string, mut pare
data << expr
}
ast.SelectorExpr {
data << expr
if g.comptime.is_comptime_selector_field_name(expr, 'name') {
fields << g.comptime.comptime_for_field_value.name
} else {
data << expr
}
}
ast.BoolLiteral {
data << expr
Expand Down

0 comments on commit 6f97ced

Please sign in to comment.