{{- if and .Values.migrations.enabled .Values.postgres.enabled }} apiVersion: batch/v1 kind: Job metadata: name: {{ include "cloudhost-platform.fullname" . }}-migrations namespace: {{ include "cloudhost-platform.namespace" . }} labels: {{- include "cloudhost-platform.labels" . | nindent 4 }} annotations: # Run BEFORE the backend rolls out so schema-dependent code never starts # against an unmigrated database. helm.sh/hook: pre-install,pre-upgrade helm.sh/hook-weight: "5" helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded spec: backoffLimit: 3 template: spec: restartPolicy: OnFailure initContainers: - name: wait-postgres image: {{ .Values.images.busybox | quote }} command: - sh - -c - | until nc -z {{ include "cloudhost-platform.postgres.fullname" . }} 5432; do sleep 2 done containers: - name: migrate image: {{ .Values.migrations.image | quote }} env: - name: PGHOST value: {{ include "cloudhost-platform.postgres.fullname" . }} - name: PGPORT value: "5432" - name: PGDATABASE value: {{ .Values.postgres.database | quote }} - name: PGUSER value: {{ .Values.postgres.username | quote }} - name: PGPASSWORD valueFrom: secretKeyRef: name: {{ include "cloudhost-platform.secretName" . }} key: postgres-password command: - sh - -c - | set -e # Track applied migrations so each file runs exactly once — the # loop is idempotent across every helm upgrade. psql -v ON_ERROR_STOP=1 -c "CREATE TABLE IF NOT EXISTS schema_migrations (filename TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW());" for f in $(ls /migrations/*.sql | sort); do name=$(basename "$f") applied=$(psql -tA -c "SELECT 1 FROM schema_migrations WHERE filename = '$name';") if [ "$applied" = "1" ]; then echo ">>> Skipping $name (already applied)" continue fi echo ">>> Applying $name" psql -v ON_ERROR_STOP=1 --single-transaction \ -f "$f" \ -c "INSERT INTO schema_migrations (filename) VALUES ('$name');" done echo ">>> All migrations applied" volumeMounts: - name: migrations mountPath: /migrations volumes: - name: migrations configMap: name: {{ include "cloudhost-platform.fullname" . }}-migrations {{- end }}