plz / database_d_sqlite.v
62 lines · 53 sloc · 1.36 KB · d4104e7627c1594b9de8e026959b196932f293c8
Raw
1module main
2
3import config
4import db.sqlite
5import os
6
7type GitlyDb = sqlite.DB
8
9fn connect_db(conf config.Config) !GitlyDb {
10 path := first_env(['GITLY_SQLITE_PATH', 'GITLY_DB_PATH'], conf.sqlite.path)
11 mut db := sqlite.connect(path)!
12 if db.busy_timeout(10000) != 0 {
13 return error('failed to configure sqlite busy timeout')
14 }
15 db.exec('pragma journal_mode = WAL;') or { eprintln('cannot enable sqlite WAL mode: ${err}') }
16 return GitlyDb(db)
17}
18
19fn db_backend_name() string {
20 return 'sqlite'
21}
22
23fn db_exec_values(mut db GitlyDb, query string) ![][]string {
24 rows := db.exec(query)!
25 mut values := [][]string{cap: rows.len}
26 for row in rows {
27 values << row.vals.clone()
28 }
29 return values
30}
31
32fn db_last_insert_id(mut db GitlyDb) int {
33 rows := db.exec('select last_insert_rowid()') or { return 0 }
34 if rows.len > 0 && rows[0].vals.len > 0 {
35 return rows[0].vals[0].int()
36 }
37 return 0
38}
39
40fn db_column_exists(mut db GitlyDb, table_name string, column_name string) !bool {
41 rows := db_exec_values(mut db, 'pragma table_info(${sql_table(table_name)})')!
42 for row in rows {
43 if row.len > 1 && row[1] == column_name {
44 return true
45 }
46 }
47 return false
48}
49
50fn db_bool_column_type() string {
51 return 'INTEGER NOT NULL DEFAULT 0'
52}
53
54fn first_env(keys []string, fallback string) string {
55 for key in keys {
56 value := os.getenv(key)
57 if value != '' {
58 return value
59 }
60 }
61 return fallback
62}
63