SQL template literal with automatic escaping and performance optimization.

Template tag that builds SQL queries by interpolating values with automatic character escaping. Implements tiered performance optimizations based on interpolation count (0, 1, 2-3, 4+ values).

Security Boundary: Escapes string literal breakouts and binary injection. Does NOT prevent logical injection patterns. Use parameterized queries for complete protection.

Performance: Four optimization tiers scale from simple concatenation to pre-sized array joins. Conditional whitespace trimming avoids unnecessary work.

// String literal escaping
sql`SELECT * FROM users WHERE name = '${userInput}'`
// O'Connor → "SELECT * FROM users WHERE name = 'O''Connor'"
// Dynamic identifiers and values
sql`SELECT * FROM ${table} WHERE status = '${status}' LIMIT ${limit}`
// → "SELECT * FROM orders WHERE status = 'pending' LIMIT 10"
// Composed query building
const where = conditions.length ? sql`WHERE ${conditions.join(' AND ')}` : '';
sql`SELECT * FROM users ${where} ORDER BY created_at`
// Advanced composition patterns
const buildInsert = (table, data) => {
const keys = Object.keys(data).join(', ');
const values = Object.values(data).map(v => `'${v}'`).join(', ');
return sql`INSERT INTO ${table} (${keys}) VALUES (${values})`;
};
// Performance consideration: batch operations
const queries = items.map(item => sql`INSERT INTO logs VALUES (${item.id}, '${item.msg}')`);
// Each sql`` call optimizes independently - consider direct string building for massive batches
  • Processes SQL template literals with automatic value escaping and performance optimization.

    Template literal processor that interleaves static strings with escaped dynamic values. Implements four performance tiers based on interpolation count: specialized paths for 0, 1, 2-3, and 4+ values optimize for common usage patterns.

    Performance Optimization: Different algorithms by value count:

    • 0 values: Direct string return with conditional trim
    • 1 value: String concatenation (fastest for single interpolation)
    • 2-3 values: StringBuilder pattern (optimal for few values)
    • 4+ values: Pre-sized array join (scales with many interpolations)
    • Extracted functions: Monomorphic patterns for V8 JIT optimization

    Security: All dynamic values pass through escapeSql() automatically. Whitespace: Trims leading/trailing whitespace only when detected (performance).

    Parameters

    • strings: TemplateStringsArray

      Static template string parts

    • Rest...values: unknown[]

      Dynamic values to interpolate and escape

    Returns string

    Complete SQL query with escaped values and trimmed whitespace

    // Zero values - direct return path
    processSQLTemplate`SELECT * FROM users` // → "SELECT * FROM users"
    // Single value - concatenation path
    processSQLTemplate`SELECT * FROM ${tableName}` // → "SELECT * FROM users"
    // Multiple values - optimized for count
    processSQLTemplate`SELECT * FROM ${table} WHERE status = '${status}' LIMIT ${limit}`
    // → "SELECT * FROM orders WHERE status = 'pending' LIMIT 10"
    // Critical edge case: whitespace detection
    processSQLTemplate`SELECT * FROM users` // → "SELECT * FROM users" (no trim)
    processSQLTemplate` SELECT * FROM users ` // → "SELECT * FROM users" (trimmed)
    // Dangerous pattern: massive batch operations
    const queries = range(10000).map(i => processSQLTemplate`INSERT INTO logs VALUES (${i})`);
    // Each call allocates separately - for massive batches, consider direct string building