1 | import os |
2 | import db.sqlite |
3 | |
4 | struct User { |
5 | id i64 [primary; sql: serial] |
6 | name string [unique] |
7 | } |
8 | |
9 | const db_folder = os.join_path(os.vtmp_dir(), 'v', 'orm_sql') |
10 | |
11 | const db_path = os.join_path(db_folder, 'sql_statement_or_blocks.db') |
12 | |
13 | fn testsuite_begin() { |
14 | os.mkdir_all(db_folder) or {} |
15 | } |
16 | |
17 | fn testsuite_end() { |
18 | os.rmdir_all(db_folder) or {} |
19 | } |
20 | |
21 | fn test_ensure_db_exists_and_user_table_is_ok() { |
22 | mut db := sqlite.connect(db_path)! |
23 | assert true |
24 | |
25 | eprintln('> drop pre-existing User table...') |
26 | db.exec('drop table if exists User')! |
27 | |
28 | eprintln('> creating User table...') |
29 | sql db { |
30 | create table User |
31 | } or { panic(err) } |
32 | assert true |
33 | db.close()! |
34 | } |
35 | |
36 | fn test_sql_or_block_for_insert() { |
37 | mut db := sqlite.connect(db_path)! |
38 | user := User{1, 'bilbo'} |
39 | |
40 | eprintln('> inserting user 1 (first try)...') |
41 | mut is_user_inserted := true |
42 | |
43 | sql db { |
44 | insert user into User |
45 | } or { |
46 | println('user should have been inserted, but could not, err: ${err}') |
47 | is_user_inserted = false |
48 | } |
49 | |
50 | assert is_user_inserted |
51 | |
52 | eprintln('> inserting user 1 (second try)...') |
53 | sql db { |
54 | insert user into User |
55 | } or { |
56 | println('user could not be inserted, err: ${err}') |
57 | is_user_inserted = false |
58 | } |
59 | |
60 | assert !is_user_inserted |
61 | eprintln('LINE: ${@LINE}') |
62 | db.close()! |
63 | } |
64 | |
65 | fn test_sql_or_block_for_select() { |
66 | mut db := sqlite.connect(db_path)! |
67 | |
68 | eprintln('> selecting user with id 1...') |
69 | mut users := sql db { |
70 | select from User where id == 1 |
71 | } or { |
72 | eprintln('could not select user, err: ${err}') |
73 | []User{} |
74 | } |
75 | eprintln('LINE: ${@LINE}') |
76 | |
77 | single := users.first() |
78 | assert single.id == 1 |
79 | |
80 | users = sql db { |
81 | select from User where id == 0 |
82 | } or { |
83 | eprintln('could not select user, err: ${err}') |
84 | []User{} |
85 | } |
86 | eprintln('LINE: ${@LINE}') |
87 | |
88 | assert users.len == 0 |
89 | eprintln('LINE: ${@LINE}') |
90 | |
91 | eprintln('> selecting users...') |
92 | multiple := sql db { |
93 | select from User |
94 | } or { |
95 | eprintln('could not users, err: ${err}') |
96 | []User{} |
97 | } |
98 | eprintln('LINE: ${@LINE}') |
99 | |
100 | assert multiple.len == 1 |
101 | eprintln('LINE: ${@LINE}') |
102 | db.close()! |
103 | } |
104 | |
105 | fn test_finish() { |
106 | eprintln('done') |
107 | assert true |
108 | } |