@@ -3,17 +3,60 @@ interface Source {
33 path : string ;
44}
55
6- export function applySlugs ( query : string , sources : Source [ ] ) {
7- for ( const source of sources ) {
8- query = query . replace ( new RegExp ( `(from|FROM)[ \n\t]+(${ source . slug } )` , 'g' ) , ( match ) =>
9- match . replace ( source . slug , `${ source . path } ${ source . slug } ` )
6+ const SQL_KEYWORDS = new Set ( [
7+ 'WHERE' ,
8+ 'ON' ,
9+ 'GROUP' ,
10+ 'ORDER' ,
11+ 'LIMIT' ,
12+ 'OFFSET' ,
13+ 'HAVING' ,
14+ 'SET' ,
15+ 'LEFT' ,
16+ 'RIGHT' ,
17+ 'INNER' ,
18+ 'OUTER' ,
19+ 'CROSS' ,
20+ 'JOIN' ,
21+ 'UNION' ,
22+ 'RETURNING' ,
23+ 'VALUES' ,
24+ ';'
25+ ] ) ;
26+
27+ export function applyCustomTable ( query : string , sources : Source [ ] ) {
28+ let newQuery = query ;
29+
30+ for ( const { slug, path } of sources ) {
31+ const regex = new RegExp (
32+ `(\\bFROM\\b|\\bJOIN\\b|\\bUPDATE\\b|\\bINTO\\b)\\s+(?:(\\w+)\\.)?(${ slug } )\\b(\\s+(?:AS\\s+)?\\w+)?` ,
33+ 'gi'
34+ ) ;
35+
36+ newQuery = newQuery . replace (
37+ regex ,
38+ ( _fullMatch , keyword , _schema , foundTable , potentialAliasChunk ) => {
39+ let finalAliasPart = '' ;
40+
41+ if ( potentialAliasChunk ) {
42+ const rawAlias = potentialAliasChunk . trim ( ) . replace ( / ^ A S \s + / i, '' ) ;
43+ if ( SQL_KEYWORDS . has ( rawAlias . toUpperCase ( ) ) ) {
44+ finalAliasPart = ` ${ foundTable } ${ potentialAliasChunk } ` ;
45+ } else {
46+ finalAliasPart = potentialAliasChunk ;
47+ }
48+ } else {
49+ finalAliasPart = ` ${ foundTable } ` ;
50+ }
51+ return `${ keyword } ${ path } ${ finalAliasPart } ` ;
52+ }
1053 ) ;
1154
12- query = query . replace (
13- new RegExp ( `(describe| DESCRIBE)([ \n\t]+(table|TABLE))?[ \n\t]+ (${ source . slug } )` , 'g ' ) ,
14- ( match ) => match . replace ( source . slug , ` ${ source . path } `)
55+ newQuery = newQuery . replace (
56+ new RegExp ( `(DESCRIBE)\\s+(?:TABLE\\s+)? (${ slug } )\\b ` , 'gi ' ) ,
57+ `$1 ${ path } `
1558 ) ;
1659 }
1760
18- return query ;
61+ return newQuery ;
1962}
0 commit comments