| 9 | * Connection settings mirror directus setup |
| 10 | */ |
| 11 | export function createDatabase(env: Env, logger: Logger): Knex { |
| 12 | const client = env.DB_CLIENT; |
| 13 | |
| 14 | const connection: Record<string, any> = |
| 15 | client === 'sqlite3' |
| 16 | ? { filename: env.DB_FILENAME } |
| 17 | : { |
| 18 | host: env.DB_HOST, |
| 19 | port: Number(env.DB_PORT), |
| 20 | user: env.DB_USER, |
| 21 | password: env.DB_PASSWORD, |
| 22 | database: env.DB_DATABASE, |
| 23 | }; |
| 24 | |
| 25 | const poolConfig: Knex.PoolConfig = {}; |
| 26 | |
| 27 | const knexConfig: Knex.Config = { |
| 28 | client, |
| 29 | connection, |
| 30 | pool: poolConfig, |
| 31 | log: { |
| 32 | warn: (msg) => { |
| 33 | // Ignore warnings about returning not being supported in some DBs |
| 34 | if (msg.startsWith('.returning()')) return; |
| 35 | if (msg.endsWith('does not currently support RETURNING clause')) return; |
| 36 | |
| 37 | // Ignore warning about MySQL not supporting TRX for DDL |
| 38 | if (msg.startsWith('Transaction was implicitly committed, do not mix transactions and DDL with MySQL')) return; |
| 39 | |
| 40 | return logger.warn(msg); |
| 41 | }, |
| 42 | error: (msg) => logger.error(msg), |
| 43 | deprecate: (msg) => logger.info(msg), |
| 44 | debug: (msg) => logger.debug(msg), |
| 45 | }, |
| 46 | }; |
| 47 | |
| 48 | if (client === 'sqlite3') { |
| 49 | knexConfig.useNullAsDefault = true; |
| 50 | |
| 51 | poolConfig.afterCreate = (conn: any, callback: any) => { |
| 52 | logger.info('Enabling SQLite Foreign Keys support...'); |
| 53 | |
| 54 | conn.run('PRAGMA foreign_keys = ON'); |
| 55 | |
| 56 | callback(null, conn); |
| 57 | }; |
| 58 | } |
| 59 | |
| 60 | if (client === 'cockroachdb') { |
| 61 | poolConfig.afterCreate = (conn: any, callback: any) => { |
| 62 | logger.info('Setting CRDB serial_normalization and default_int_size'); |
| 63 | |
| 64 | conn.query('SET serial_normalization = "sql_sequence"'); |
| 65 | conn.query('SET default_int_size = 4'); |
| 66 | |
| 67 | callback(null, conn); |
| 68 | }; |