|
| 1 | +import { PgTestConnectionOptions, RoleMapping } from '@launchql/types'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Default role mapping configuration |
| 5 | + */ |
| 6 | +export const DEFAULT_ROLE_MAPPING: Required<RoleMapping> = { |
| 7 | + anonymous: 'anonymous', |
| 8 | + authenticated: 'authenticated', |
| 9 | + administrator: 'administrator', |
| 10 | + default: 'anonymous' |
| 11 | +}; |
| 12 | + |
| 13 | +/** |
| 14 | + * Get resolved role mapping with defaults |
| 15 | + */ |
| 16 | +export const getRoleMapping = (options?: PgTestConnectionOptions): Required<RoleMapping> => { |
| 17 | + return { |
| 18 | + ...DEFAULT_ROLE_MAPPING, |
| 19 | + ...(options?.roles || {}) |
| 20 | + }; |
| 21 | +}; |
| 22 | + |
| 23 | +/** |
| 24 | + * Get role name by key with fallback to default mapping |
| 25 | + */ |
| 26 | +export const getRoleName = ( |
| 27 | + roleKey: keyof Omit<RoleMapping, 'default'>, |
| 28 | + options?: PgTestConnectionOptions |
| 29 | +): string => { |
| 30 | + const mapping = getRoleMapping(options); |
| 31 | + return mapping[roleKey]; |
| 32 | +}; |
| 33 | + |
| 34 | +/** |
| 35 | + * Get default role name |
| 36 | + */ |
| 37 | +export const getDefaultRole = (options?: PgTestConnectionOptions): string => { |
| 38 | + const mapping = getRoleMapping(options); |
| 39 | + return mapping.default; |
| 40 | +}; |
| 41 | + |
| 42 | +/** |
| 43 | + * Replace role names in SQL using the current mapping |
| 44 | + */ |
| 45 | +export const substituteRolesInSql = (sql: string, options?: PgTestConnectionOptions): string => { |
| 46 | + const mapping = getRoleMapping(options); |
| 47 | + |
| 48 | + // Replace role names in SQL - handle various patterns |
| 49 | + let result = sql; |
| 50 | + |
| 51 | + // Replace exact role names (word boundaries) |
| 52 | + result = result.replace(/\banonymous\b/g, mapping.anonymous); |
| 53 | + result = result.replace(/\bauthenticated\b/g, mapping.authenticated); |
| 54 | + result = result.replace(/\badministrator\b/g, mapping.administrator); |
| 55 | + |
| 56 | + return result; |
| 57 | +}; |
0 commit comments