From 450c6e843c5532e1df24fd6d3848c5e62a9ab409 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Thu, 25 Jun 2020 17:18:44 +0200 Subject: [PATCH] orm: `update` with multiple fields --- vlib/orm/orm_test.v | 10 ++++++++++ vlib/v/gen/sql.v | 10 +++++----- vlib/v/parser/sql.v | 16 ++++++++++++---- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/vlib/orm/orm_test.v b/vlib/orm/orm_test.v index 9a3265f7f8..0d56d0a57e 100644 --- a/vlib/orm/orm_test.v +++ b/vlib/orm/orm_test.v @@ -125,6 +125,16 @@ fn test_orm_sqlite() { println(kate2) assert kate2.age == 31 assert kate2.name == 'Kate' + // + sql db { + update User set age = 32, name = 'Kate N' where name == 'Kate' + } + kate3 := sql db { + select from User where id == 3 + } + println(kate3) + assert kate3.age == 32 + assert kate3.name == 'Kate N' } struct User { diff --git a/vlib/v/gen/sql.v b/vlib/v/gen/sql.v index aacc2da99d..2132ec5f3d 100644 --- a/vlib/v/gen/sql.v +++ b/vlib/v/gen/sql.v @@ -29,7 +29,7 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) { g.write('insert into $node.table_name (') } else { g.write('update $node.table_name set ') - } + } if node.kind == .insert { for i, field in node.fields { if field.name == 'id' { @@ -55,6 +55,9 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) { for i, col in node.updated_columns { g.write(' $col = ') g.expr_to_sql(node.update_exprs[i]) + if i < node.updated_columns.len - 1 { + g.write(', ') + } } g.write(' where ') @@ -67,6 +70,7 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) { g.writeln('"));') if node.kind == .insert { + // build the object now (`x.name = ... x.id == ...`) for i, field in node.fields { if field.name == 'id' { continue @@ -79,10 +83,6 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) { } } } - else if node.kind == .update { - - } - // Dump all sql parameters generated by our custom expr handler binds := g.sql_buf.str() g.sql_buf = strings.new_builder(100) diff --git a/vlib/v/parser/sql.v b/vlib/v/parser/sql.v index 7f8461d843..35d4bb8b5d 100644 --- a/vlib/v/parser/sql.v +++ b/vlib/v/parser/sql.v @@ -114,10 +114,18 @@ fn (mut p Parser) sql_stmt() ast.SqlStmt { if n != 'set' { p.error('expecting `set`') } - column := p.check_name() - updated_columns << column - p.check(.assign) - update_exprs << p.expr(0) + for { + column := p.check_name() + updated_columns << column + p.check(.assign) + update_exprs << p.expr(0) + if p.tok.kind == .comma { + p.check(.comma) + } + else { + break + } + } } mut table_type := table.Type(0) mut where_expr := ast.Expr{}