import { inject , injectable } from 'inversify' ; import { Connection , createConnection , getConnectionOptions } from 'typeorm' ; import IConfigFile from '../IConfigFile' ; import IConfiguration from '../IConfiguration' ; import ILogger from '../ILogger' ; import ILoggerModel from '../ILoggerModel' ; import IDBOperator from './IDBOperator' ; @ injectable ( ) export default class DBOperator implements IDBOperator { private connection : Connection | null = null ; private config : IConfigFile ; private log : ILogger ; constructor ( @ inject ( 'ILoggerModel' ) logger , @ inject ( 'IConfiguration' ) conf ) { this . log = logger . getLogger ( ) ; this . config = conf . getConfig ( ) ; } public async getConnection ( ) { if ( this . connection === null ) { const option = await getConnectionOptions ( ) ; this . connection = await createConnection ( option ) ; await this . setSQLiteExtensions ( ) ; } return this . connection ; } return public async checkConnection ( ) { const connection = await this . getConnection ( ) ; await connection . manager . query ( 'select 1' ) ; } return public async closeConnection ( ) { if ( this . connection === null ) { return ; } await this . connection . close ( ) ; } /**
     * sqlite の外部拡張読み込み
     */ private async setSQLiteExtensions ( ) { if ( this . config . dbtype !== 'sqlite' || typeof this . config . sqlite === 'undefined' || typeof this . config . sqlite . extensions === 'undefined' || this . connection === null ) { return ; } for ( const extension of this . config . sqlite . extensions ) { this . log . system . info ( `load extension: ${ extension }` ) ; await new Promise < void > ( ( resolve , reject ) => { ( < any > this . connection ) . driver . databaseConnection . loadExtension ( extension , ( err ) => { if ( err ) { this . log . system . error ( `failed to load extension: ${ extension }` ) ; reject ( err ) ; } else { this . log . system . info ( `loaded extension success: ${ extension }` ) ; resolve ( ) ; } } ) ; } ) ; } } /**
     * regexp が有効か返す
     */ public isEnabledRegexp ( ) { if ( this . config . dbtype !== 'sqlite' ) { return true ; } return typeof this . config . sqlite === 'undefined' ? false : ! ! this . config . sqlite . regexp ; } /**
     * boolean 型を変換する
     */ public convertBoolean ( value ) { if ( this . config . dbtype !== 'sqlite' ) { return value ; } return value === true ? 1 : 0 ; } return public isEnableCS ( ) { return this . config . dbtype === 'sqlite' ? false : true ; } param cs return public getRegexpStr ( cs ) { switch ( this . config . dbtype ) { case 'mysql' : return cs ? 'regexp binary' : 'regexp' ; case 'postgres' : return cs ? '~' : '~*' ; case 'sqlite' : default : return 'regexp' ; } } param cs public getLikeStr ( cs ) { switch ( this . config . dbtype ) { case 'mysql' : return cs ? 'like binary' : 'like' ; case 'postgres' : return cs ? 'like' : 'ilike' ; case 'sqlite' : default : return 'like' ; } } }