Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/database/postgres/schema/indexes.ts
Views: 687
import getLogger from "@cocalc/backend/logger";1import type { Client } from "@cocalc/database/pool";2import type { TableSchema } from "./types";3import { make_valid_name } from "@cocalc/util/misc";45const log = getLogger("db:schema:indexes");67function possiblyAddParens(query: string): string {8if (query[0] == "(") {9return query;10}11if (query.toLowerCase().startsWith("using")) {12// do not add for using queries, since that violates PostgreSQL syntax13return query;14}15return `(${query})`;16}1718export function createIndexesQueries(19schema: TableSchema20): { name: string; query: string; unique: boolean }[] {21const v = schema.pg_indexes ?? [];22if (schema.fields.expire != null && !v.includes("expire")) {23v.push("expire");24}25const queries: { name: string; query: string; unique: boolean }[] = [];26for (let query of v) {27query = query.trim();28const name = `${schema.name}_${make_valid_name(query)}_idx`; // this first, then...29query = possiblyAddParens(query);30queries.push({ name, query, unique: false });31}32const w = schema.pg_unique_indexes ?? [];33for (let query of w) {34query = query.trim();35const name = `${schema.name}_${make_valid_name(query)}_unique_idx`;36query = possiblyAddParens(query);37queries.push({ name, query, unique: true });38}39return queries;40}4142// IMPORTANT: There is also code in database/postgres/schema/sync.ts that creates indexes.43export async function createIndexes(44db: Client,45schema: TableSchema46): Promise<void> {47log.debug("createIndexes", schema.name, " creating SQL query");48for (const { name, query, unique } of createIndexesQueries(schema)) {49// Shorthand index is just the part in parens.50// 2020-10-12: it makes total sense to add CONCURRENTLY to this index command to avoid locking up the table,51// but the first time we tried this in production (postgres 10), it just made "invalid" indices.52// the problem might be that several create index commands were issued rapidly, which threw this off53// So, for now, it's probably best to either create them manually first (concurrently) or be54// aware that this does lock up briefly.55const fullQuery = `CREATE ${unique ? "UNIQUE" : ""} INDEX ${name} ON ${56schema.name57} ${query}`;58log.debug("createIndexes -- creating ", name, " using ", fullQuery);59await db.query(fullQuery);60}61}626364