#!/usr/bin/env bash set -Eeuo pipefail database="${POSTGRES_DB:-ludarium}" database_user="${POSTGRES_USER:-ludarium}" if [[ ! "$database" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then echo "PostgreSQL collation repair requires a simple validated database identifier." >&2 exit 1 fi psql_base=(psql -v ON_ERROR_STOP=1 -U "$database_user" -d "$database") versions="$("${psql_base[@]}" -At -F '|' -c \ "select coalesce(datcollversion,''),coalesce(pg_database_collation_actual_version(oid),'') from pg_database where datname=current_database()")" IFS='|' read -r stored_version actual_version <<< "$versions" if [[ -z "$actual_version" || "$stored_version" == "$actual_version" ]]; then exit 0 fi printf 'PostgreSQL collation drift detected for %s: stored=%s actual=%s\n' \ "$database" "${stored_version:-}" "$actual_version" has_platform_definitions="$("${psql_base[@]}" -At -c \ "select to_regclass('public.platform_definitions') is not null")" if [[ "$has_platform_definitions" == "t" ]]; then unsafe_duplicates="$("${psql_base[@]}" -At -c " with duplicate_ids as ( select id from platform_definitions group by id having count(*) > 1 ), variants as ( select p.id, count(distinct jsonb_build_object( 'custom',p.custom,'enabled',p.enabled,'version',p.version, 'data',p.data - 'updatedAt')) as semantic_variants, bool_or(p.custom) as contains_custom from platform_definitions p join duplicate_ids d using(id) group by p.id ) select count(*) from variants where contains_custom or semantic_variants <> 1")" if [[ "$unsafe_duplicates" != "0" ]]; then echo "Collation repair found ambiguous or custom platform duplicates; refusing automatic data changes." >&2 exit 1 fi removed_duplicates="$("${psql_base[@]}" -At -c " with ranked as ( select ctid,row_number() over(partition by id order by updated_at desc,ctid desc) as ordinal from platform_definitions ), removed as ( delete from platform_definitions p using ranked r where p.ctid=r.ctid and r.ordinal > 1 returning 1 ) select count(*) from removed")" if [[ "$removed_duplicates" != "0" ]]; then printf 'Removed %s semantically identical built-in platform duplicate(s) before reindex.\n' "$removed_duplicates" fi fi "${psql_base[@]}" -c "REINDEX DATABASE \"$database\"" >/dev/null if [[ -z "$stored_version" ]]; then "${psql_base[@]}" -c " update pg_database set datcollversion=pg_database_collation_actual_version(oid) where datname=current_database() and datcollversion is null" >/dev/null else "${psql_base[@]}" -c "ALTER DATABASE \"$database\" REFRESH COLLATION VERSION" >/dev/null fi refreshed_version="$("${psql_base[@]}" -At -c \ "select coalesce(datcollversion,'') from pg_database where datname=current_database()")" if [[ "$refreshed_version" != "$actual_version" ]]; then echo "PostgreSQL collation version did not refresh to the runtime version." >&2 exit 1 fi printf 'PostgreSQL collation indexes rebuilt and version refreshed to %s.\n' "$refreshed_version"