import { log } from './FsOps' ; import Conversion from './Conversion' ; import DBAccess from './DBAccess' ; import DBVendors from './DBVendors' ; import * as extraConfigProcessor from './ExtraConfigProcessor' ; import { mapDataTypes } from './TableProcessor' ; import DBAccessQueryResult from './DBAccessQueryResult' ; import IDBAccessQueryParams from './IDBAccessQueryParams' ; /**
 * Defines which columns of the given table have default value.
 * Sets default values, if need.
 */ export default async ( conversion , tableName ) : Promise < void > => { const logTitle = 'DefaultProcessor::default' ; const msg = `\t--[${ logTitle }] Defines default values for table: "${ conversion . _schema }"."${ tableName }"` ; log ( conversion , msg , conversion . _dicTables [ tableName ] . tableLogPath ) ; const originalTableName = extraConfigProcessor . getTableName ( conversion , tableName , true ) ; const pgSqlNumericTypes = [ 'money' , 'numeric' , 'decimal' , 'double precision' , 'real' , 'bigint' , 'int' , 'smallint' ] ; const sqlReservedValues = { 'CURRENT_DATE' : 'CURRENT_DATE' , '0000-00-00' : "'-INFINITY'" , 'CURRENT_TIME' : 'CURRENT_TIME' , '00:00:00' : '00:00:00' , 'CURRENT_TIMESTAMP' : 'CURRENT_TIMESTAMP' , '0000-00-00 00:00:00' : "'-INFINITY'" , 'LOCALTIME' : 'LOCALTIME' , 'LOCALTIMESTAMP' : 'LOCALTIMESTAMP' , 'NULL' : 'NULL' , 'null' : 'NULL' , 'UTC_DATE' : "(CURRENT_DATE AT TIME ZONE 'UTC')" , 'UTC_TIME' : "(CURRENT_TIME AT TIME ZONE 'UTC')" , 'UTC_TIMESTAMP' : "(NOW() AT TIME ZONE 'UTC')" } ; const promises = conversion . _dicTables [ tableName ] . arrTableColumns . map ( async ( column ) => { const pgSqlDataType = mapDataTypes ( conversion . _dataTypesMap , column . Type ) ; const columnName = extraConfigProcessor . getColumnName ( conversion , originalTableName , column . Field , false ) ; let sql = `ALTER TABLE "${ conversion . _schema }"."${ tableName }" ALTER COLUMN "${ columnName }" SET DEFAULT ` ; if ( sqlReservedValues [ column . Default ] ) { sql += `${ sqlReservedValues [ column . Default ] };` ; } else if ( pgSqlNumericTypes . indexOf ( pgSqlDataType ) === - 1 ) { sql += `'${ column . Default }';` ; } else { sql += `${ column . Default };` ; } const params = { conversion : conversion , caller : logTitle , sql : sql , vendor : DBVendors . PG , processExitOnError : false , shouldReturnClient : false } ; const result = await DBAccess . query ( params ) ; if ( ! result . error ) { const successMsg = `\t--[${ logTitle }] Set default value for "${ conversion . _schema }"."${ tableName }"."${ columnName }"...` ; log ( conversion , successMsg , conversion . _dicTables [ tableName ] . tableLogPath ) ; } } ) ; await Promise . all ( promises ) ; } ;