Skip to content

Parameter Reuse Optimization for SQL Template Literals #1387

Description

@programmarchy

Parameter Reuse Optimization for SQL Template Literals

Current Behavior

When using SQL template literals with Kysely, identical parameters are assigned new parameter indices each time they appear in the query, even when the values are the same. This leads to unnecessary parameter duplication in the compiled query.

For example:

const terms = ['test', 'example'];
const query = sql<any>`
  select *
  from some_table
  where
    column1 = any(${terms}::text[])  -- Becomes $1
    or column2 = any(${terms}::text[]) -- Becomes $2
`;

Compiles to:

select * from some_table where column1 = any($1::text[]) or column2 = any($2::text[])
Parameters: [['test', 'example'], ['test', 'example']]

Expected Behavior

When the same parameter value is used multiple times in a query, it would be more efficient to reuse the same parameter index:

select * from some_table where column1 = any($1::text[]) or column2 = any($1::text[])
Parameters: [['test', 'example']]

This optimization would:

  1. Reduce the number of parameters passed to the database
  2. Potentially improve query planning as the database can recognize the parameters are identical
  3. Make the generated SQL more concise

Metadata

Metadata

Assignees

No one assigned

    Labels

    breaking changeIncludes breaking changesbuilt-in dialectRelated to a built-in dialectenhancementNew feature or requestmssqlRelated to MS SQL Server (MSSQL)postgresRelated to PostgreSQLsqliteRelated to sqlite

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions