orm: fix order by with custom column name (#22813)

This commit is contained in:
Felipe Pena 2024-11-09 02:24:59 -03:00 committed by GitHub
parent a1904154d3
commit fad49da199
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 47 additions and 1 deletions

View File

@ -165,6 +165,7 @@ const skip_with_fsanitize_memory = [
'vlib/orm/orm_references_test.v',
'vlib/orm/orm_option_array_test.v',
'vlib/orm/orm_option_time_test.v',
'vlib/orm/orm_order_by_custom_field_test.v',
'vlib/db/sqlite/sqlite_test.v',
'vlib/db/sqlite/sqlite_orm_test.v',
'vlib/db/sqlite/sqlite_comptime_field_test.v',
@ -261,6 +262,7 @@ const skip_on_ubuntu_musl = [
'vlib/orm/orm_references_test.v',
'vlib/orm/orm_option_array_test.v',
'vlib/orm/orm_option_time_test.v',
'vlib/orm/orm_order_by_custom_field_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,37 @@
import db.sqlite
@[table: 'prefixed_records']
struct Record {
id int @[primary; sql: 'CustomId']
name string @[sql: 'named_name']
}
fn test_main() {
mut db := sqlite.connect(':memory:')!
defer { db.close() or {} }
prepare(db)!
last := sql db {
select from Record where name == 'first' order by id limit 1
}!
assert last.len == 1
assert last[0].name == 'first'
}
fn prepare(db sqlite.DB) ! {
db.exec('
CREATE TABLE prefixed_records (
CustomId INTEGER PRIMARY KEY AUTOINCREMENT,
named_name TEXT
);
')!
db.exec("
INSERT INTO prefixed_records
(named_name)
VALUES
('first'),
('last');
")!
}

View File

@ -865,7 +865,14 @@ fn (mut g Gen) write_orm_select(node ast.SqlExpr, connection_var_name string, re
if node.has_order {
g.write('.order = _SLIT("')
g.expr(node.order_expr)
if node.order_expr is ast.Ident {
field := g.get_orm_current_table_field(node.order_expr.name) or {
verror('field "${node.order_expr.name}" does not exist on "${g.sql_table_name}"')
}
g.write(g.get_orm_column_name_from_struct_field(field))
} else {
g.expr(node.order_expr)
}
g.writeln('"),')
if node.has_desc {
g.writeln('.order_type = orm__OrderType__desc,')