orm: add delete stmt (#5725)

pull/5733/head
Louis Schmieder 2020-07-07 16:55:32 +02:00 committed by GitHub
parent 4d7d1eb0c4
commit 2a7a6fa1eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 12 deletions

View File

@ -209,6 +209,15 @@ fn test_orm_sqlite() {
select from User order by age desc limit 1 offset offs
}
assert second_oldest.age == 31
sql db {
delete from User where age == 34
}
updated_oldest := sql db {
select from User order by age desc limit 1
}
assert updated_oldest.age == 31
}
fn test_orm_pg() {

View File

@ -28,8 +28,10 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) {
g.write('sqlite3_stmt* $g.sql_stmt_name = ${dbtype}__DB_init_stmt($db_name, tos_lit("')
if node.kind == .insert {
g.write('INSERT INTO `${util.strip_mod_name(node.table_name)}` (')
} else {
} else if node.kind == .update {
g.write('UPDATE `${util.strip_mod_name(node.table_name)}` SET ')
} else if node.kind == .delete {
g.write('DELETE FROM `${util.strip_mod_name(node.table_name)}` ')
}
if node.kind == .insert {
for i, field in node.fields {
@ -61,8 +63,10 @@ fn (mut g Gen) sql_stmt(node ast.SqlStmt) {
}
}
g.write(' WHERE ')
} else if node.kind == .delete {
g.write(' WHERE ')
}
if node.kind == .update {
if node.kind == .update || node.kind == .delete {
g.expr_to_sql(node.where_expr)
}
g.writeln('"));')

View File

@ -127,6 +127,7 @@ fn (mut p Parser) sql_stmt() ast.SqlStmt {
}
mut inserted_var_name := ''
mut table_name := ''
if kind != .delete {
expr := p.expr(0)
match expr {
ast.Ident {
@ -140,6 +141,7 @@ fn (mut p Parser) sql_stmt() ast.SqlStmt {
p.error('can only insert variables')
}
}
}
n = p.check_name() // into
mut updated_columns := []string{}
mut update_exprs := []ast.Expr{cap: 5}
@ -160,7 +162,10 @@ fn (mut p Parser) sql_stmt() ast.SqlStmt {
break
}
}
} else if kind == .delete && n != 'from' {
p.error('expecting `from`')
}
mut table_type := table.Type(0)
mut where_expr := ast.Expr{}
if kind == .insert {
@ -177,6 +182,12 @@ fn (mut p Parser) sql_stmt() ast.SqlStmt {
}
p.check_sql_keyword('where')
where_expr = p.expr(0)
} else if kind == .delete {
table_type = p.parse_type()
sym := p.table.get_type_symbol(table_type)
table_name = sym.name
p.check_sql_keyword('where')
where_expr = p.expr(0)
}
p.check(.rcbr)
return ast.SqlStmt{