From 9a864563654e8dceeec90559249d79f16511048c Mon Sep 17 00:00:00 2001 From: walking devel <104449470+walkingdevel@users.noreply.github.com> Date: Sat, 28 Jan 2023 23:27:34 +0000 Subject: [PATCH] cgen: support string interpolation in ORM queries (#17141) --- cmd/tools/vtest-self.v | 2 ++ .../orm_string_interpolation_in_where_test.v | 36 +++++++++++++++++++ vlib/v/gen/c/sql.v | 6 ++++ 3 files changed, 44 insertions(+) create mode 100644 vlib/orm/orm_string_interpolation_in_where_test.v diff --git a/cmd/tools/vtest-self.v b/cmd/tools/vtest-self.v index 87b6dab890..5eb918cc85 100644 --- a/cmd/tools/vtest-self.v +++ b/cmd/tools/vtest-self.v @@ -126,6 +126,7 @@ const ( 'vlib/orm/orm_create_and_drop_test.v', 'vlib/orm/orm_insert_test.v', 'vlib/orm/orm_fn_calls_test.v', + 'vlib/orm/orm_string_interpolation_in_where_test.v', 'vlib/db/sqlite/sqlite_test.v', 'vlib/db/sqlite/sqlite_orm_test.v', 'vlib/db/sqlite/sqlite_vfs_lowlevel_test.v', @@ -194,6 +195,7 @@ const ( 'vlib/orm/orm_create_and_drop_test.v', 'vlib/orm/orm_insert_test.v', 'vlib/orm/orm_fn_calls_test.v', + 'vlib/orm/orm_string_interpolation_in_where_test.v', 'vlib/v/tests/orm_sub_struct_test.v', 'vlib/v/tests/orm_sub_array_struct_test.v', 'vlib/v/tests/orm_joined_tables_select_test.v', diff --git a/vlib/orm/orm_string_interpolation_in_where_test.v b/vlib/orm/orm_string_interpolation_in_where_test.v new file mode 100644 index 0000000000..ce860d48df --- /dev/null +++ b/vlib/orm/orm_string_interpolation_in_where_test.v @@ -0,0 +1,36 @@ +import db.sqlite + +struct User { + id int [primary; sql: serial] + name string +} + +fn test_string_interpolation() { + mut db := sqlite.connect(':memory:') or { panic(err) } + + sql db { + create table User + } + + user_suffix := '_user' + + first_user := User{ + name: 'first${user_suffix}' + } + + second_user := User{ + name: 'second${user_suffix}' + } + + sql db { + insert first_user into User + insert second_user into User + } + + users := sql db { + select from User where name == 'first${user_suffix}' + } + + assert users.len == 1 + assert users.first().name == 'first${user_suffix}' +} diff --git a/vlib/v/gen/c/sql.v b/vlib/v/gen/c/sql.v index 624143f368..03efa9ddb7 100644 --- a/vlib/v/gen/c/sql.v +++ b/vlib/v/gen/c/sql.v @@ -286,6 +286,9 @@ fn (mut g Gen) sql_expr_to_orm_primitive(expr ast.Expr) { ast.StringLiteral { g.sql_write_orm_primitive(ast.string_type, expr) } + ast.StringInterLiteral { + g.sql_write_orm_primitive(ast.string_type, expr) + } ast.IntegerLiteral { g.sql_write_orm_primitive(ast.int_type, expr) } @@ -419,6 +422,9 @@ fn (mut g Gen) sql_where_data(expr ast.Expr, mut fields []string, mut parenthese ast.StringLiteral { data << expr } + ast.StringInterLiteral { + data << expr + } ast.IntegerLiteral { data << expr }