| 1 | module main |
| 2 | |
| 3 | import config |
| 4 | import db.pg |
| 5 | import os |
| 6 | |
| 7 | type GitlyDb = pg.DB |
| 8 | |
| 9 | fn connect_db(conf config.Config) !GitlyDb { |
| 10 | if conninfo := first_env_opt(['GITLY_DB_CONNINFO', 'DATABASE_URL'], conf.pg.conninfo) { |
| 11 | return GitlyDb(pg.connect_with_conninfo(conninfo)!) |
| 12 | } |
| 13 | return GitlyDb(pg.connect( |
| 14 | host: first_env(['GITLY_DB_HOST', 'PGHOST'], conf.pg.host) |
| 15 | port: first_int_env(['GITLY_DB_PORT', 'PGPORT'], conf.pg.port) |
| 16 | dbname: first_env(['GITLY_DB_NAME', 'PGDATABASE'], conf.pg.dbname) |
| 17 | user: first_env(['GITLY_DB_USER', 'PGUSER'], conf.pg.user) |
| 18 | password: first_env(['GITLY_DB_PASSWORD', 'PGPASSWORD'], conf.pg.password) |
| 19 | )!) |
| 20 | } |
| 21 | |
| 22 | fn db_backend_name() string { |
| 23 | return 'postgres' |
| 24 | } |
| 25 | |
| 26 | fn db_exec_values(db &GitlyDb, query string) ![][]string { |
| 27 | rows := db.exec_no_null(query)! |
| 28 | mut values := [][]string{cap: rows.len} |
| 29 | for row in rows { |
| 30 | values << row.vals.clone() |
| 31 | } |
| 32 | return values |
| 33 | } |
| 34 | |
| 35 | fn db_last_insert_id(db &GitlyDb) int { |
| 36 | rows := db.exec_no_null('SELECT lastval()') or { return 0 } |
| 37 | if rows.len > 0 && rows[0].vals.len > 0 { |
| 38 | return rows[0].vals[0].int() |
| 39 | } |
| 40 | return 0 |
| 41 | } |
| 42 | |
| 43 | fn db_column_exists(db &GitlyDb, table_name string, column_name string) !bool { |
| 44 | rows := db_exec_values(db, |
| 45 | 'select column_name from information_schema.columns where table_name = ${sql_literal(table_name.to_lower())} and column_name = ${sql_literal(column_name)}')! |
| 46 | return rows.len > 0 |
| 47 | } |
| 48 | |
| 49 | fn db_bool_column_type() string { |
| 50 | return 'BOOLEAN NOT NULL DEFAULT false' |
| 51 | } |
| 52 | |
| 53 | fn first_env(keys []string, fallback string) string { |
| 54 | for key in keys { |
| 55 | value := os.getenv(key) |
| 56 | if value != '' { |
| 57 | return value |
| 58 | } |
| 59 | } |
| 60 | return fallback |
| 61 | } |
| 62 | |
| 63 | fn first_env_opt(keys []string, fallback string) ?string { |
| 64 | value := first_env(keys, fallback) |
| 65 | if value == '' { |
| 66 | return none |
| 67 | } |
| 68 | return value |
| 69 | } |
| 70 | |
| 71 | fn first_int_env(keys []string, fallback int) int { |
| 72 | for key in keys { |
| 73 | value := os.getenv(key) |
| 74 | if value != '' { |
| 75 | return value.int() |
| 76 | } |
| 77 | } |
| 78 | return fallback |
| 79 | } |
| 80 | |