// src/components/postgres/data-store-postgres-schema.ts
var SCHEMA_NAME_PATTERN = /^[a-z_][a-z0-9_]{0,62}$/;
function quoteSchemaIdentifier(schemaName) {
  if (!SCHEMA_NAME_PATTERN.test(schemaName)) {
    throw new Error(
      `Invalid Postgres schema name: ${JSON.stringify(schemaName)}; expected /[a-z_][a-z0-9_]{0,62}/`
    );
  }
  return `"${schemaName}"`;
}
function buildSchemaBootstrapStatements(schemaName) {
  const s = quoteSchemaIdentifier(schemaName);
  return [
    `CREATE SCHEMA IF NOT EXISTS ${s};`,
    [
      `CREATE TABLE IF NOT EXISTS ${s}.resources (`,
      `  tenant_id     text        NOT NULL,`,
      `  workspace_id  text        NOT NULL,`,
      `  resource_type text        NOT NULL,`,
      `  resource_id   text        NOT NULL,`,
      `  version       text        NOT NULL,`,
      `  last_updated  timestamptz NOT NULL,`,
      `  deleted_at    timestamptz,`,
      `  resource      jsonb       NOT NULL,`,
      `  PRIMARY KEY (tenant_id, workspace_id, resource_type, resource_id)`,
      `);`
    ].join("\n"),
    [
      `CREATE INDEX IF NOT EXISTS resources_jsonb_gin`,
      `  ON ${s}.resources USING gin (resource);`
    ].join("\n"),
    [
      `CREATE INDEX IF NOT EXISTS resources_listing`,
      `  ON ${s}.resources (tenant_id, workspace_id, resource_type, last_updated);`
    ].join("\n")
  ];
}
function buildSchemaBootstrapSql(schemaName) {
  return buildSchemaBootstrapStatements(schemaName).join("\n");
}
function buildResourceUpsertSql(schemaName) {
  const s = quoteSchemaIdentifier(schemaName);
  return [
    `INSERT INTO ${s}.resources`,
    `  (tenant_id, workspace_id, resource_type, resource_id, version, last_updated, deleted_at, resource)`,
    `VALUES ($1, $2, $3, $4, $5, $6, NULL, $7::jsonb)`,
    `ON CONFLICT (tenant_id, workspace_id, resource_type, resource_id)`,
    `DO UPDATE SET`,
    `  version       = EXCLUDED.version,`,
    `  last_updated  = EXCLUDED.last_updated,`,
    `  deleted_at    = NULL,`,
    `  resource      = EXCLUDED.resource`,
    `WHERE EXCLUDED.version > ${s}.resources.version;`
  ].join("\n");
}
function buildResourceSoftDeleteSql(schemaName) {
  const s = quoteSchemaIdentifier(schemaName);
  return [
    `UPDATE ${s}.resources`,
    `SET deleted_at = $6,`,
    `    version    = $5`,
    `WHERE LOWER(tenant_id) = LOWER($1)`,
    `  AND LOWER(workspace_id) = LOWER($2)`,
    `  AND LOWER(resource_type) = LOWER($3)`,
    `  AND LOWER(resource_id) = LOWER($4)`,
    `  AND $5 >= version;`
  ].join("\n");
}
async function ensureSchemaBootstrap(client, schemaName) {
  await client.query(buildSchemaBootstrapSql(schemaName));
}

export {
  buildSchemaBootstrapStatements,
  buildResourceUpsertSql,
  buildResourceSoftDeleteSql,
  ensureSchemaBootstrap
};
//# sourceMappingURL=chunk-HQ4CPUPH.mjs.map