orm: limit

pull/5532/head
Alexander Medvednikov 2020-06-27 16:19:12 +02:00
parent f8f2fa246e
commit f073ffa4ad
4 changed files with 46 additions and 27 deletions

View File

@ -168,6 +168,12 @@ fn test_orm_sqlite() {
}
assert no_user.name == '' // TODO optional
assert no_user.age == 0
//
two_users := sql db {
select from User limit 2
}
assert two_users.len == 2
assert two_users[0].id > 0
}
struct User {

View File

@ -809,7 +809,6 @@ pub enum SqlExprKind {
update
}
*/
pub enum SqlStmtKind {
insert
update
@ -838,9 +837,13 @@ pub:
db_expr Expr // `db` in `sql db {`
where_expr Expr
has_where bool
has_offset bool
offset_expr Expr
is_array bool
table_type table.Type
pos token.Position
has_limit bool
limit_expr Expr
pub mut:
table_name string
fields []table.Field
@ -898,8 +901,7 @@ pub fn (expr Expr) position() token.Position {
InfixExpr {
left_pos := expr.left.position()
right_pos := expr.right.position()
if left_pos.pos == 0 ||
right_pos.pos == 0 {
if left_pos.pos == 0 || right_pos.pos == 0 {
return expr.pos
}
return token.Position{

View File

@ -131,7 +131,12 @@ fn (mut g Gen) sql_select_expr(node ast.SqlExpr) {
if node.has_where && node.where_expr is ast.InfixExpr {
g.expr_to_sql(node.where_expr)
}
g.writeln(' order by id"));')
g.write(' order by id ')
if node.has_limit {
g.write(' limit ')
g.expr_to_sql(node.limit_expr)
}
g.writeln('"));')
// Dump all sql parameters generated by our custom expr handler
binds := g.sql_buf.str()
g.sql_buf = strings.new_builder(100)
@ -182,7 +187,7 @@ fn (mut g Gen) sql_select_expr(node ast.SqlExpr) {
g.writeln('\tif (_step_res$tmp == SQLITE_ROW) ;') // another row
g.writeln('\telse if (_step_res$tmp != SQLITE_OK) break;')
} else {
g.writeln('printf("RES: %d\\n", _step_res$tmp) ;')
// g.writeln('printf("RES: %d\\n", _step_res$tmp) ;')
g.writeln('\tif (_step_res$tmp == SQLITE_OK || _step_res$tmp == SQLITE_ROW) {')
}
for i, field in node.fields {

View File

@ -38,13 +38,17 @@ fn (mut p Parser) sql_expr() ast.Expr {
}
}
}
mut has_limit := false
mut limit_expr := ast.Expr{}
if p.tok.kind == .name && p.tok.lit == 'limit' {
// `limit 1` means that a single object is returned
p.check_name() // `limit`
if p.tok.kind == .number && p.tok.lit == '1' {
query_one = true
} else {
has_limit = true
}
p.next()
limit_expr = p.expr(0)
}
if !query_one && !is_count {
// return an array
@ -63,6 +67,8 @@ fn (mut p Parser) sql_expr() ast.Expr {
table_type: table_type
where_expr: where_expr
has_where: has_where
has_limit: has_limit
limit_expr: limit_expr
is_array: !query_one
pos: pos
}