import { ISettings } from '@sqltools/types' ; import formatter from '@sqltools/formatter/src/sqlFormatter' ; import multipleQueriesParse from './parse' ; export param { string } query param { ( 'pg' | 'mysql' | 'mssql' ) } driver param { string } delimiter returns { string [ ] } export function parse ( query , driver = 'mysql' ) { return multipleQueriesParse ( query , driver ) ; } export param { string } query returns export function cleanUp ( query = '' ) { if ( ! query ) return '' ; return query . toString ( ) . replace ( '\t' , '  ' ) . replace ( /(--.*)|(((\/\*)+?[\w\W]+?(\*\/)+))/gmi , '' ) . split ( /\r\n|\n/gi ) . map ( v => v . trim ( ) ) . filter ( Boolean ) . join ( ' ' ) . trim ( ) ; } export param { string } insertQuery param { ISettings [ 'format' ] } formatOptions returns { string } export function formatInsertQuery ( insertQuery , formatOptions ? ) { return format ( `${ insertQuery . substr ( 0 , Math . max ( 0 , insertQuery . length - 2 ) ) });` , formatOptions ) . replace ( /'\${(\d+):([\w\s]+):((int|bool|num|real)[\w\s]*)}'/gi , ( _ , pos , colName , type ) => `\${${ pos }:${ colName . trim ( ) }:${ type . trim ( ) }}` ) . concat ( '$0' ) ; } export function extractConnName ( query ) { return ( ( query . match ( /@conn\s*(.+)$/m ) || [ ] ) [ 1 ] || '' ) . trim ( ) || null ; } export function getQueryParameters ( query , regexStr ) { if ( ! query || ! regexStr ) return [ ] ; const regex = new RegExp ( regexStr , 'g' ) ; const paramsMap = { } ; let match ; while ( ( match = regex . exec ( query ) ) !== null ) { const queryPart = query . substring ( Math . max ( 0 , regex . lastIndex - 15 ) , Math . min ( query . length , regex . lastIndex + 15 ) ) . replace ( /[\r\n]/g , '' ) . replace ( /\s+/g , ' ' ) . trim ( ) ; if ( ! paramsMap [ match [ 0 ] ] ) { paramsMap [ match [ 0 ] ] = { param : match [ 0 ] , string : `...${ queryPart }...` , } ; } } return Object . values ( paramsMap ) ; } const dollarRegex = /\$([^\s]+)/gi ; param query param originalQuery function fixParameters ( query , originalQuery ) { if ( ! dollarRegex . test ( originalQuery ) ) return query ; const matches = originalQuery . match ( dollarRegex ) || [ ] ; return matches . reduce ( ( text , match ) => { const matchEscaped = match . replace ( /[.*+?^${}()|[\]\\]/g , '\\$&' ) ; return text . replace ( new RegExp ( '\\\$' + ' +' + matchEscaped . substr ( 2 ) , 'g' ) , match . replace ( /\$/g , '$$$$' ) ) ; } , query ) ; } export function format ( query , formatOptions = { } ) { const { reservedWordCase = null , insertSpaces = true , tabSize = 2 , ... opts } = formatOptions ; return fixParameters ( formatter . format ( query , { ... opts , indent : insertSpaces ? ' ' . repeat ( tabSize ) : '\t' , reservedWordCase , } ) , query ) ; }