**What** - always return an index expression, also for unique constraints **why** - constraints can't be partial, meaning `UNIQUE ... WHERE` is not possible with constraints - constraints are indicies under the hood so it doesn't change the behavior of the system when we're not using constraint specific features but just using them for `UNIQUE`
52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
/**
|
|
* Create a PSQL index statement
|
|
* @param name The name of the index
|
|
* @param tableName The name of the table
|
|
* @param columns The columns to index
|
|
* @param type The type of index (e.g GIN, GIST, BTREE, etc)
|
|
* @param where The where clause
|
|
* @param unique If the index should be a unique index
|
|
*
|
|
* @example
|
|
* createPsqlIndexStatementHelper({
|
|
* name: "idx_user_email",
|
|
* tableName: "user",
|
|
* columns: "email",
|
|
* type: "btree",
|
|
* where: "email IS NOT NULL"
|
|
* });
|
|
*
|
|
* // CREATE INDEX IF NOT EXISTS idx_user_email ON user USING btree (email) WHERE email IS NOT NULL;
|
|
*
|
|
* createPsqlIndexStatementHelper({
|
|
* name: "idx_user_email",
|
|
* tableName: "user",
|
|
* columns: "email"
|
|
* });
|
|
*
|
|
* // CREATE INDEX IF NOT EXISTS idx_user_email ON user (email);
|
|
*
|
|
*/
|
|
export function createPsqlIndexStatementHelper({
|
|
name,
|
|
tableName,
|
|
columns,
|
|
type,
|
|
where,
|
|
unique,
|
|
}: {
|
|
name: string
|
|
tableName: string
|
|
columns: string | string[]
|
|
type?: string
|
|
where?: string
|
|
unique?: boolean
|
|
}) {
|
|
columns = Array.isArray(columns) ? columns.join(", ") : columns
|
|
const typeStr = type ? ` USING ${type}` : ""
|
|
const optionsStr = where ? ` WHERE ${where}` : ""
|
|
const uniqueStr = unique ? "UNIQUE " : ""
|
|
|
|
return `CREATE ${uniqueStr}INDEX IF NOT EXISTS "${name}" ON "${tableName}"${typeStr} (${columns})${optionsStr}`
|
|
}
|