Skip to content

Commit

Permalink
fix: promote query
Browse files Browse the repository at this point in the history
  • Loading branch information
juanmahidalgo committed Nov 28, 2024
1 parent ecaf282 commit 3aac825
Showing 1 changed file with 31 additions and 8 deletions.
39 changes: 31 additions & 8 deletions src/ports/squids/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@ export function escapeLiteral(value: string): string {
}

export function escapeIdentifier(value: string): string {
return client.escapeIdentifier(value) // Escapes an identifier (e.g., schema, table names)
return client.escapeIdentifier(value) // Escapes an identifier (e.g., table names)
}

export const getPromoteQuery = (serviceName: string, schemaName: string, project: string): SQLStatement => {
const safeServiceName = escapeLiteral(serviceName)
const safeSchemaName = escapeIdentifier(schemaName)
const safeProjectName = escapeLiteral(project)

return SQL`
Expand All @@ -27,29 +26,53 @@ export const getPromoteQuery = (serviceName: string, schemaName: string, project
-- Fetch the new schema name and database user from the indexers table
SELECT schema, db_user INTO new_schema_name, writer_user
FROM public.indexers
WHERE service = `.append(safeServiceName).append(SQL`
WHERE service = `
.append(safeServiceName)
.append(
SQL`
ORDER BY created_at DESC LIMIT 1;
-- Fetch the old schema name from the squids table
SELECT schema INTO old_schema_name
FROM squids
WHERE name = `.append(safeProjectName).append(SQL`;
WHERE name = `
.append(safeProjectName)
.append(
SQL`;
-- Rename the old schema
EXECUTE format('ALTER SCHEMA %I RENAME TO %I', `.append(safeSchemaName).append(SQL`, old_schema_name);
EXECUTE format('ALTER SCHEMA %I RENAME TO %I', '`
.append(schemaName)
.append(
SQL`', old_schema_name);
-- Rename the new schema to the desired name
EXECUTE format('ALTER SCHEMA %I RENAME TO %I', new_schema_name, `.append(safeSchemaName).append(SQL`);
EXECUTE format('ALTER SCHEMA %I RENAME TO %I', new_schema_name, '`
.append(schemaName)
.append(
SQL`');
-- Update the search path for the user
EXECUTE format('ALTER USER %I SET search_path TO %I', writer_user, `.append(safeSchemaName).append(SQL`);
EXECUTE format('ALTER USER %I SET search_path TO %I', writer_user, '`
.append(schemaName)
.append(
SQL`');
-- Update the schema in the squids table
UPDATE squids
SET schema = `.append(safeSchemaName).append(SQL`
SET schema = `
.append(escapeLiteral(schemaName))
.append(
SQL`
WHERE name = `.append(safeProjectName).append(SQL`;
END $$;
`)
)
)
)
)
)
)
}

export const getSchemaByServiceNameQuery = (serviceName: string): SQLStatement => {
Expand Down

0 comments on commit 3aac825

Please sign in to comment.