Skip to content
Source
Sign inSign up
samwillis/neon-realtime-electric
Open History to see the last commit

column-mapper.ts

392 lines12.1 KB

1import { Schema } from './types'
2​
3type DbColumnName = string
4type AppColumnName = string
5​
6/**
7 * Quote a PostgreSQL identifier for safe use in query parameters.
8 *
9 * Wraps the identifier in double quotes and escapes any internal
10 * double quotes by doubling them. This ensures identifiers with
11 * special characters (commas, spaces, etc.) are handled correctly.
12 *
13 * @param identifier - The identifier to quote
14 * @returns The quoted identifier
15 *
16 * @example
17 * ```typescript
18 * quoteIdentifier('user_id') // '"user_id"'
19 * quoteIdentifier('foo,bar') // '"foo,bar"'
20 * quoteIdentifier('has"quote') // '"has""quote"'
21 * ```
22 *
23 * @internal
24 */
25export function quoteIdentifier(identifier: string): string {
26 // Escape internal double quotes by doubling them
27 const escaped = identifier.replace(/"/g, `""`)
28 return `"${escaped}"`
30​
31/**
32 * A bidirectional column mapper that handles transforming column **names**
33 * between database format (e.g., snake_case) and application format (e.g., camelCase).
34 *
35 * **Important**: ColumnMapper only transforms column names, not column values or types.
36 * For type conversions (e.g., string → Date), use the `parser` option.
37 * For value transformations (e.g., encryption), use the `transformer` option.
38 *
39 * @example
40 * ```typescript
41 * const mapper = snakeCamelMapper()
42 * mapper.decode('user_id') // 'userId'
43 * mapper.encode('userId') // 'user_id'
44 * ```
45 */
46export interface ColumnMapper {
47 /**
48 * Transform a column name from database format to application format.
49 * Applied to column names in query results.
50 */
51 decode: (dbColumnName: DbColumnName) => AppColumnName
52​
53 /**
54 * Transform a column name from application format to database format.
55 * Applied to column names in WHERE clauses and other query parameters.
56 */
57 encode: (appColumnName: AppColumnName) => DbColumnName
59​
60/**
61 * Converts a snake_case string to camelCase.
62 *
63 * Handles edge cases:
64 * - Preserves leading underscores: `_user_id` → `_userId`
65 * - Preserves trailing underscores: `user_id_` → `userId_`
66 * - Preserves multi-underscore count for injectivity:
67 * `user__id` → `user_Id`, `user___id` → `user__Id`
68 * - Normalizes to lowercase first: `user_Column` → `userColumn`
69 *
70 * The transform is designed to be injective on lowercase input and
71 * round-trippable via `camelToSnake`, so distinct db columns never
72 * collide on the same app key.
73 *
74 * @example
75 * snakeToCamel('user_id') // 'userId'
76 * snakeToCamel('project_id') // 'projectId'
77 * snakeToCamel('created_at') // 'createdAt'
78 * snakeToCamel('_private') // '_private'
79 * snakeToCamel('user__id') // 'user_Id'
80 * snakeToCamel('user___id') // 'user__Id'
81 * snakeToCamel('user_id_') // 'userId_'
82 */
83export function snakeToCamel(str: string): string {
84 // Preserve leading underscores
85 const leadingUnderscores = str.match(/^_+/)?.[0] ?? ``
86 const withoutLeading = str.slice(leadingUnderscores.length)
87​
88 // Preserve trailing underscores for round-trip safety
89 const trailingUnderscores = withoutLeading.match(/_+$/)?.[0] ?? ``
90 const core = trailingUnderscores
91 ? withoutLeading.slice(
92 0,
93 withoutLeading.length - trailingUnderscores.length
94 )
95 : withoutLeading
96​
97 // Convert to lowercase
98 const normalized = core.toLowerCase()
99​
100 // Convert snake_case to camelCase. For a run of n underscores before
101 // a letter, keep (n-1) literal underscores and uppercase the letter.
102 // This preserves underscore count so distinct inputs never collide.
103 const camelCased = normalized.replace(/_+([a-z])/g, (match, letter) => {
104 const extraUnderscores = `_`.repeat(match.length - 2)
105 return extraUnderscores + letter.toUpperCase()
106 })
107​
108 return leadingUnderscores + camelCased + trailingUnderscores
110​
111/**
112 * Converts a camelCase string to snake_case.
113 *
114 * Handles consecutive capitals (acronyms) properly:
115 * - `userID` → `user_id`
116 * - `userHTTPSURL` → `user_https_url`
117 *
118 * @example
119 * camelToSnake('userId') // 'user_id'
120 * camelToSnake('projectId') // 'project_id'
121 * camelToSnake('createdAt') // 'created_at'
122 * camelToSnake('userID') // 'user_id'
123 * camelToSnake('parseHTMLString') // 'parse_html_string'
124 */
125export function camelToSnake(str: string): string {
126 return (
127 str
128 // Insert underscore before uppercase letters that follow a
129 // lowercase letter or an underscore. The `_` case preserves the
130 // injective encoding from snakeToCamel: `user_Id` → `user__id`.
131 .replace(/([a-z_])([A-Z])/g, `$1_$2`)
132 // Insert underscore before uppercase letters that are followed by lowercase letters
133 // This handles acronyms: userID -> user_ID, but parseHTMLString -> parse_HTML_String
134 .replace(/([A-Z]+)([A-Z][a-z])/g, `$1_$2`)
135 .toLowerCase()
136 )
138​
139/**
140 * Creates a column mapper from an explicit mapping of database columns to application columns.
141 *
142 * @param mapping - Object mapping database column names (keys) to application column names (values)
143 * @returns A ColumnMapper that can encode and decode column names bidirectionally
144 *
145 * @example
146 * const mapper = createColumnMapper({
147 * user_id: 'userId',
148 * project_id: 'projectId',
149 * created_at: 'createdAt'
150 * })
151 *
152 * // Use with ShapeStream
153 * const stream = new ShapeStream({
154 * url: 'http://localhost:3000/v1/shape',
155 * params: { table: 'todos' },
156 * columnMapper: mapper
157 * })
158 */
159export function createColumnMapper(
160 mapping: Record<string, string>
161): ColumnMapper {
162 // Build reverse mapping: app name -> db name
163 const reverseMapping: Record<string, string> = {}
164 for (const [dbName, appName] of Object.entries(mapping)) {
165 reverseMapping[appName] = dbName
166 }
167​
168 return {
169 decode: (dbColumnName: string) => {
170 return mapping[dbColumnName] ?? dbColumnName
171 },
172​
173 encode: (appColumnName: string) => {
174 return reverseMapping[appColumnName] ?? appColumnName
175 },
176 }
178​
179/**
180 * Encodes column names in a WHERE clause using the provided encoder function.
181 * Uses regex to identify column references and replace them.
182 *
183 * Handles common SQL patterns:
184 * - Simple comparisons: columnName = $1
185 * - Function calls: LOWER(columnName)
186 * - Qualified names: table.columnName
187 * - Operators: columnName IS NULL, columnName IN (...)
188 * - Quoted strings: Preserves string literals unchanged
189 *
190 * Note: This uses regex-based replacement which works for most common cases
191 * but may not handle all complex SQL expressions perfectly. For complex queries,
192 * test thoroughly or use database column names directly in WHERE clauses.
193 *
194 * @param whereClause - The WHERE clause string to encode
195 * @param encode - Optional encoder function. If undefined, returns whereClause unchanged.
196 * @returns The encoded WHERE clause
197 *
198 * @internal
199 */
200export function encodeWhereClause(
201 whereClause: string | undefined,
202 encode?: (columnName: string) => string
203): string {
204 if (!whereClause || !encode) return whereClause ?? ``
205​
206 // SQL keywords that should not be transformed (common ones)
207 const sqlKeywords = new Set([
208 `SELECT`,
209 `FROM`,
210 `WHERE`,
211 `AND`,
212 `OR`,
213 `NOT`,
214 `IN`,
215 `IS`,
216 `NULL`,
217 `NULLS`,
218 `FIRST`,
219 `LAST`,
220 `TRUE`,
221 `FALSE`,
222 `LIKE`,
223 `ILIKE`,
224 `BETWEEN`,
225 `ASC`,
226 `DESC`,
227 `LIMIT`,
228 `OFFSET`,
229 `ORDER`,
230 `BY`,
231 `GROUP`,
232 `HAVING`,
233 `DISTINCT`,
234 `AS`,
235 `ON`,
236 `JOIN`,
237 `LEFT`,
238 `RIGHT`,
239 `INNER`,
240 `OUTER`,
241 `CROSS`,
242 `CASE`,
243 `WHEN`,
244 `THEN`,
245 `ELSE`,
246 `END`,
247 `CAST`,
248 `LOWER`,
249 `UPPER`,
250 `COALESCE`,
251 `NULLIF`,
252 ])
253​
254 // Track positions of quoted strings and double-quoted identifiers to skip them
255 const quotedRanges: Array<{ start: number; end: number }> = []
256​
257 // Find all single-quoted strings and double-quoted identifiers
258 let pos = 0
259 while (pos < whereClause.length) {
260 const ch = whereClause[pos]
261 if (ch === `'` || ch === `"`) {
262 const start = pos
263 const quoteChar = ch
264 pos++ // Skip opening quote
265 // Find closing quote, handling escaped quotes ('' or "")
266 while (pos < whereClause.length) {
267 if (whereClause[pos] === quoteChar) {
268 if (whereClause[pos + 1] === quoteChar) {
269 pos += 2 // Skip escaped quote
270 } else {
271 pos++ // Skip closing quote
272 break
273 }
274 } else {
275 pos++
276 }
277 }
278 quotedRanges.push({ start, end: pos })
279 } else {
280 pos++
281 }
282 }
283​
284 // Helper to check if position is within a quoted string or double-quoted identifier
285 const isInQuotedString = (pos: number): boolean => {
286 return quotedRanges.some((range) => pos >= range.start && pos < range.end)
287 }
288​
289 // Pattern explanation:
290 // (?<![a-zA-Z0-9_]) - negative lookbehind: not preceded by identifier char
291 // ([a-zA-Z_][a-zA-Z0-9_]*) - capture: valid SQL identifier
292 // (?![a-zA-Z0-9_]) - negative lookahead: not followed by identifier char
293 //
294 // This avoids matching:
295 // - Parts of longer identifiers
296 // - SQL keywords (handled by checking if result differs from input)
297 const identifierPattern =
298 /(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(?![a-zA-Z0-9_])/g
299​
300 return whereClause.replace(identifierPattern, (match, _p1, offset) => {
301 // Don't transform if inside quoted string
302 if (isInQuotedString(offset)) {
303 return match
304 }
305​
306 // Don't transform SQL keywords
307 if (sqlKeywords.has(match.toUpperCase())) {
308 return match
309 }
310​
311 // Don't transform parameter placeholders ($1, $2, etc.)
312 // This regex won't match them anyway, but being explicit
313 if (match.startsWith(`$`)) {
314 return match
315 }
316​
317 // Apply encoding
318 const encoded = encode(match)
319 return encoded
320 })
322​
323/**
324 * Creates a column mapper that automatically converts between snake_case and camelCase.
325 * This is the most common use case for column mapping.
326 *
327 * When a schema is provided, it will only map columns that exist in the schema.
328 * Otherwise, it will map any column name it encounters.
329 *
330 * **⚠️ Limitations and Edge Cases:**
331 * - **WHERE clause encoding**: Uses regex-based parsing which may not handle all complex
332 * SQL expressions. Test thoroughly with your queries, especially those with:
333 * - Complex nested expressions
334 * - Custom operators or functions
335 * - Column names that conflict with SQL keywords
336 * - Quoted identifiers (e.g., `"$price"`, `"user-id"`) - not supported
337 * - Column names with special characters (non-alphanumeric except underscore)
338 * - **Acronym ambiguity**: `userID` → `user_id` → `userId` (ID becomes Id after roundtrip)
339 * Use `createColumnMapper()` with explicit mapping if you need exact control
340 * - **Type conversion**: This only renames columns, not values. Use `parser` for type conversion
341 *
342 * **When to use explicit mapping instead:**
343 * - You have column names that don't follow snake_case/camelCase patterns
344 * - You need exact control over mappings (e.g., `id` → `identifier`)
345 * - Your WHERE clauses are complex and automatic encoding fails
346 * - You have quoted identifiers or column names with special characters
347 *
348 * @param schema - Optional database schema to constrain mapping to known columns
349 * @returns A ColumnMapper for snake_case ↔ camelCase conversion
350 *
351 * @example
352 * // Basic usage
353 * const mapper = snakeCamelMapper()
354 *
355 * // With schema - only maps columns in schema (recommended)
356 * const mapper = snakeCamelMapper(schema)
357 *
358 * // Use with ShapeStream
359 * const stream = new ShapeStream({
360 * url: 'http://localhost:3000/v1/shape',
361 * params: { table: 'todos' },
362 * columnMapper: snakeCamelMapper()
363 * })
364 *
365 * @example
366 * // If automatic encoding fails, fall back to manual column names in WHERE clauses:
367 * stream.requestSnapshot({
368 * where: "user_id = $1", // Use database column names directly if needed
369 * params: { "1": "123" }
370 * })
371 */
372export function snakeCamelMapper(schema?: Schema): ColumnMapper {
373 // If schema provided, build explicit mapping
374 if (schema) {
375 const mapping: Record<string, string> = {}
376 for (const dbColumn of Object.keys(schema)) {
377 mapping[dbColumn] = snakeToCamel(dbColumn)
378 }
379 return createColumnMapper(mapping)
380 }
381​
382 // Otherwise, map dynamically
383 return {
384 decode: (dbColumnName: string) => {
385 return snakeToCamel(dbColumnName)
386 },
387​
388 encode: (appColumnName: string) => {
389 return camelToSnake(appColumnName)
390 },
391 }