| 1 | module main |
| 2 | |
| 3 | import config |
| 4 | import db.sqlite |
| 5 | import os |
| 6 | |
| 7 | type GitlyDb = sqlite.DB |
| 8 | |
| 9 | fn 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 | |
| 19 | fn db_backend_name() string { |
| 20 | return 'sqlite' |
| 21 | } |
| 22 | |
| 23 | fn db_exec_values(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 | |
| 32 | fn db_last_insert_id(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 | |
| 40 | fn db_column_exists(db &GitlyDb, table_name string, column_name string) !bool { |
| 41 | rows := db_exec_values(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 | |
| 50 | fn db_bool_column_type() string { |
| 51 | return 'INTEGER NOT NULL DEFAULT 0' |
| 52 | } |
| 53 | |
| 54 | fn 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 | |