Quote SQL Identifiers Safely

Quote table and column identifiers for PostgreSQL or MySQL, doubling embedded quote characters and rejecting invalid names.

TypescriptSecurity Boundaries

Code

typescriptsnippet
26 lines
export type SqlDialect = "postgres" | "mysql";

export function quoteIdentifier(
  identifier: string,
  dialect: SqlDialect = "postgres",
): string {
  if (typeof identifier !== "string" || identifier.length === 0) {
    throw new TypeError("identifier must be a non-empty string");
  }
  if (identifier.includes("\0")) {
    throw new RangeError("identifier must not contain NUL");
  }
  if (dialect !== "postgres" && dialect !== "mysql") {
    throw new RangeError("unsupported SQL dialect");
  }
  const quote = dialect === "mysql" ? "`" : '"';
  return quote + identifier.split(quote).join(quote + quote) + quote;
}

export function qualifyTable(
  schema: string,
  table: string,
  dialect: SqlDialect = "postgres",
): string {
  return quoteIdentifier(schema, dialect) + "." + quoteIdentifier(table, dialect);
}

How the snippet works

Count the functions quoteIdentifier and qualifyTable as the entire surface area of Quote SQL Identifiers Safely.

The failure path is explicit — TypeError and RangeError is raised when the guard condition holds.

Points of care

  • The guard typeof identifier !== "string" || identifier.length === 0 short-circuits the flow with an early throw when its condition holds.

Applying it

Entry signature: export function quoteIdentifier( identifier: string, dialect: SqlDialect = "postgres", )

The surface worth importing is quoteIdentifier; the helpers around it are private to the snippet.

Statements that matter

return quoteIdentifier(schema, dialect) + "." + quoteIdentifier(table, dialect);
return quote + identifier.split(quote).join(quote + quote) + quote;
throw new TypeError("identifier must be a non-empty string");

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
The code throws `TypeError` and `RangeError` — the guard `typeof identifier !== "string" || identifier.length === 0` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `quoteIdentifier`, `qualifyTable` at load time.