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

109 lines
2.0 KiB
V
Raw Normal View History

2022-08-31 14:43:20 +03:00
import os
import db.sqlite
2022-08-31 14:43:20 +03:00
struct User {
id i64 [primary; sql: serial]
name string [unique]
}
const db_folder = os.join_path(os.vtmp_dir(), 'v', 'orm_sql')
const db_path = os.join_path(db_folder, 'sql_statement_or_blocks.db')
fn testsuite_begin() {
os.mkdir_all(db_folder) or {}
}
fn testsuite_end() {
os.rmdir_all(db_folder) or {}
}
2022-08-31 14:43:20 +03:00
fn test_ensure_db_exists_and_user_table_is_ok() {
mut db := sqlite.connect(db_path)!
2022-08-31 14:43:20 +03:00
assert true
eprintln('> drop pre-existing User table...')
db.exec('drop table if exists User')
eprintln('> creating User table...')
sql db {
create table User
} or { panic(err) }
assert true
db.close()!
2022-08-31 14:43:20 +03:00
}
fn test_sql_or_block_for_insert() {
mut db := sqlite.connect(db_path)!
2022-08-31 14:43:20 +03:00
user := User{1, 'bilbo'}
eprintln('> inserting user 1 (first try)...')
mut is_user_inserted := true
2022-08-31 14:43:20 +03:00
sql db {
insert user into User
} or {
println('user should have been inserted, but could not, err: ${err}')
is_user_inserted = false
2022-08-31 14:43:20 +03:00
}
assert is_user_inserted
2022-08-31 14:43:20 +03:00
eprintln('> inserting user 1 (second try)...')
sql db {
insert user into User
} or {
println('user could not be inserted, err: ${err}')
is_user_inserted = false
2022-08-31 14:43:20 +03:00
}
assert !is_user_inserted
eprintln('LINE: ${@LINE}')
db.close()!
2022-08-31 14:43:20 +03:00
}
fn test_sql_or_block_for_select() {
mut db := sqlite.connect(db_path)!
2022-08-31 14:43:20 +03:00
eprintln('> selecting user with id 1...')
mut users := sql db {
2022-08-31 14:43:20 +03:00
select from User where id == 1
} or {
eprintln('could not select user, err: ${err}')
[]User{}
2022-08-31 14:43:20 +03:00
}
eprintln('LINE: ${@LINE}')
2022-08-31 14:43:20 +03:00
single := users.first()
2022-08-31 14:43:20 +03:00
assert single.id == 1
users = sql db {
2022-08-31 14:43:20 +03:00
select from User where id == 0
} or {
eprintln('could not select user, err: ${err}')
[]User{}
2022-08-31 14:43:20 +03:00
}
eprintln('LINE: ${@LINE}')
2022-08-31 14:43:20 +03:00
assert users.len == 0
eprintln('LINE: ${@LINE}')
2022-08-31 14:43:20 +03:00
eprintln('> selecting users...')
multiple := sql db {
select from User
} or {
eprintln('could not users, err: ${err}')
2022-08-31 14:43:20 +03:00
[]User{}
}
eprintln('LINE: ${@LINE}')
2022-08-31 14:43:20 +03:00
assert multiple.len == 1
eprintln('LINE: ${@LINE}')
db.close()!
2022-08-31 14:43:20 +03:00
}
fn test_finish() {
2022-08-31 14:43:20 +03:00
eprintln('done')
assert true
}