Quote SQL Identifiers Safely
Quote table and column identifiers for PostgreSQL or MySQL, doubling embedded quote characters and rejecting invalid names.
Code
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 === 0short-circuits the flow with an earlythrowwhen 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.