1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

orm: update with multiple fields

This commit is contained in:
Alexander Medvednikov 2020-06-25 17:18:44 +02:00
parent b280e08ee0
commit 450c6e843c
3 changed files with 27 additions and 9 deletions

View File

@ -125,6 +125,16 @@ fn test_orm_sqlite() {
println(kate2) println(kate2)
assert kate2.age == 31 assert kate2.age == 31
assert kate2.name == 'Kate' 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 { struct User {

View File

@ -29,7 +29,7 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) {
g.write('insert into $node.table_name (') g.write('insert into $node.table_name (')
} else { } else {
g.write('update $node.table_name set ') g.write('update $node.table_name set ')
} }
if node.kind == .insert { if node.kind == .insert {
for i, field in node.fields { for i, field in node.fields {
if field.name == 'id' { if field.name == 'id' {
@ -55,6 +55,9 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) {
for i, col in node.updated_columns { for i, col in node.updated_columns {
g.write(' $col = ') g.write(' $col = ')
g.expr_to_sql(node.update_exprs[i]) g.expr_to_sql(node.update_exprs[i])
if i < node.updated_columns.len - 1 {
g.write(', ')
}
} }
g.write(' where ') g.write(' where ')
@ -67,6 +70,7 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) {
g.writeln('"));') g.writeln('"));')
if node.kind == .insert { if node.kind == .insert {
// build the object now (`x.name = ... x.id == ...`)
for i, field in node.fields { for i, field in node.fields {
if field.name == 'id' { if field.name == 'id' {
continue 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 // Dump all sql parameters generated by our custom expr handler
binds := g.sql_buf.str() binds := g.sql_buf.str()
g.sql_buf = strings.new_builder(100) g.sql_buf = strings.new_builder(100)

View File

@ -114,10 +114,18 @@ fn (mut p Parser) sql_stmt() ast.SqlStmt {
if n != 'set' { if n != 'set' {
p.error('expecting `set`') p.error('expecting `set`')
} }
column := p.check_name() for {
updated_columns << column column := p.check_name()
p.check(.assign) updated_columns << column
update_exprs << p.expr(0) 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 table_type := table.Type(0)
mut where_expr := ast.Expr{} mut where_expr := ast.Expr{}