danhuawang commented on code in PR #15001:
URL: https://github.com/apache/gravitino/pull/15001#discussion_r4623890107


##########
dev/charts/gravitino/resources/scripts/schema-migrate.sh:
##########
@@ -0,0 +1,549 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+# Entity-store schema init for the chart schema-migrate Job.
+# Fail on any unexpected SQL error so a broken migration cannot roll out.
+set -euo pipefail
+
+: "${DB_ENGINE:?DB_ENGINE must be mysql or postgresql}"
+: "${DB_HOST:?DB_HOST is required}"
+: "${GRAVITINO_DB:?GRAVITINO_DB is required}"
+: "${SCRIPTS_DIR:=/scripts}"
+
+if [ "$DB_ENGINE" != mysql ] && [ "$DB_ENGINE" != postgresql ]; then
+  echo "ERROR: DB_ENGINE must be mysql or postgresql (got ${DB_ENGINE})" >&2
+  exit 1
+fi
+
+if [ "$DB_ENGINE" = mysql ]; then
+  : "${MYSQL_USER:?MYSQL_USER is required}"
+  : "${MYSQL_PWD:?MYSQL_PWD is required}"
+  export MYSQL_PWD
+else
+  : "${POSTGRES_USER:?POSTGRES_USER is required}"
+  : "${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}"
+fi
+
+DB_PORT="${DB_PORT:-}"
+PG_CURRENT_SCHEMA="${PG_CURRENT_SCHEMA:-}"
+BASELINE_VERSION="${BASELINE_VERSION:-}"
+VERSION_FILE="${SCRIPTS_DIR}/version.txt"
+
+mysql_client() {
+  local extra=()
+  if [ -n "$DB_PORT" ]; then
+    extra+=(-P "$DB_PORT")
+  fi
+  mysql -h "$DB_HOST" "${extra[@]}" -u "$MYSQL_USER" "$@"
+}
+
+psql_client() {
+  local extra=()
+  if [ -n "$DB_PORT" ]; then
+    extra+=(-p "$DB_PORT")
+  fi
+  PGPASSWORD="$POSTGRES_PASSWORD" psql -h "$DB_HOST" "${extra[@]}" -U 
"$POSTGRES_USER" "$@"
+}
+
+version_le() {
+  [ "$(printf '%s\n%s' "$1" "$2" | sort -V | head -n1)" = "$1" ]
+}
+
+version_lt() {
+  [ "$1" != "$2" ] && version_le "$1" "$2"
+}
+
+wait_for_db() {
+  echo "Waiting for ${DB_ENGINE} at ${DB_HOST}..."
+  if [ "$DB_ENGINE" = mysql ]; then
+    until mysql_client -e "SELECT 1" >/dev/null 2>&1; do
+      echo "Waiting for MySQL to be ready..."
+      sleep 2
+    done
+  else
+    until psql_client -d "$GRAVITINO_DB" -c "SELECT 1" >/dev/null 2>&1; do
+      echo "Waiting for PostgreSQL to be ready..."
+      sleep 2
+    done
+  fi
+}
+
+mysql_query() {
+  mysql_client -D "$GRAVITINO_DB" -sNe "$1"
+}
+
+mysql_exec() {
+  mysql_client -D "$GRAVITINO_DB" -e "$1"
+}
+
+psql_query() {
+  psql_client -d "$GRAVITINO_DB" -v ON_ERROR_STOP=1 -tAc "$1"
+}
+
+db_query() {
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_query "$1"
+  else
+    psql_query "$1"
+  fi
+}
+
+# Community upgrade-*-mysql.sql uses ADD COLUMN / DROP INDEX without IF NOT 
EXISTS.
+# Ignore "already applied" errors so re-runs and overlapping snapshots stay 
safe.
+mysql_is_already_applied_error() {
+  case "$1" in
+    1060 | 1061 | 1068 | 1091 | 1176 | 1280) return 0 ;;
+    *) return 1 ;;
+  esac
+}
+
+mysql_apply_sql_file() {
+  local file="$1"
+  local out unexpected code line rc
+  set +e
+  out="$(mysql_client -D "$GRAVITINO_DB" --force <"$file" 2>&1)"
+  rc=$?
+  set -e
+  if [ -n "${out}" ]; then
+    printf '%s\n' "${out}"
+  fi
+  unexpected=""
+  while IFS= read -r line; do
+    [ -z "${line}" ] && continue
+    code="$(printf '%s' "${line}" | sed -n 's/.*ERROR \([0-9][0-9]*\).*/\1/p')"
+    [ -n "${code}" ] || continue
+    if mysql_is_already_applied_error "${code}"; then
+      echo "INFO: ignoring already-applied MySQL error ${code}"
+      continue
+    fi
+    unexpected="${unexpected}${line}"$'\n'
+  done < <(printf '%s\n' "${out}" | grep -E 'ERROR [0-9]+' || true)
+  if [ -n "${unexpected}" ]; then
+    echo "ERROR: SQL script failed: $file" >&2
+    printf '%s' "${unexpected}" >&2
+    exit 1
+  fi
+  if [ "${rc}" != 0 ] && ! printf '%s\n' "${out}" | grep -qE 'ERROR [0-9]+'; 
then
+    echo "ERROR: mysql client failed: $file" >&2
+    printf '%s\n' "${out}" >&2
+    exit 1
+  fi
+}
+
+apply_sql_file() {
+  local file="$1"
+  echo "Applying $file"
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_apply_sql_file "$file"
+  else
+    if ! psql_client -d "$GRAVITINO_DB" -v ON_ERROR_STOP=1 -f "$file"; then
+      echo "ERROR: SQL script failed: $file" >&2
+      exit 1
+    fi
+  fi
+}
+
+# 1.3.2 widened table_column_version_info.column_name. Existing 1.3.x DBs may
+# already record a later version without that ALTER; repair before ready.
+ensure_column_name_capacity() {
+  version_le 1.3.2 "$VERSION" || return 0
+
+  local scope capacity
+  if [ "$DB_ENGINE" = mysql ]; then
+    scope='DATABASE()'
+  else
+    scope='current_schema()'
+  fi
+  capacity=$(db_query "SELECT character_maximum_length FROM 
information_schema.columns
+    WHERE table_schema = ${scope} AND table_name = 'table_column_version_info'
+      AND column_name = 'column_name';" | tr -d '[:space:]')
+  case "$capacity" in
+    '' | *[!0-9]*)
+      echo "ERROR: Cannot determine table_column_version_info.column_name 
capacity" >&2
+      exit 1
+      ;;
+  esac
+  [ "$capacity" -lt 300 ] || return 0
+
+  echo "Expanding table_column_version_info.column_name from ${capacity} to 
300 characters"
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_exec "ALTER TABLE table_column_version_info
+      MODIFY COLUMN column_name VARCHAR(300) NOT NULL COMMENT 'column name';"
+  else
+    psql_query "ALTER TABLE table_column_version_info
+      ALTER COLUMN column_name TYPE VARCHAR(300);" >/dev/null
+  fi
+}
+
+ensure_migration_table() {
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_exec "CREATE TABLE IF NOT EXISTS gravitino_schema_migration (
+      id TINYINT UNSIGNED NOT NULL PRIMARY KEY,
+      schema_version VARCHAR(64) NOT NULL,
+      updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE 
CURRENT_TIMESTAMP
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;"
+  else
+    psql_query "CREATE TABLE IF NOT EXISTS gravitino_schema_migration (
+      id SMALLINT NOT NULL PRIMARY KEY,
+      schema_version VARCHAR(64) NOT NULL,
+      updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+    );" >/dev/null
+  fi
+}
+
+read_recorded_version() {
+  db_query "SELECT schema_version FROM gravitino_schema_migration WHERE id = 
1;" 2>/dev/null | tr -d '[:space:]' || true
+}
+
+write_recorded_version() {
+  local ver="$1"
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_exec "INSERT INTO gravitino_schema_migration (id, schema_version) 
VALUES (1, '${ver}')
+      ON DUPLICATE KEY UPDATE schema_version = '${ver}';"
+  else
+    psql_query "INSERT INTO gravitino_schema_migration (id, schema_version, 
updated_at)
+      VALUES (1, '${ver}', NOW())
+      ON CONFLICT (id) DO UPDATE SET schema_version = EXCLUDED.schema_version, 
updated_at = NOW();" >/dev/null
+  fi
+  echo "Recorded schema version ${ver}"
+}
+
+metalake_exists() {
+  if [ "$DB_ENGINE" = mysql ]; then
+    local count
+    count=$(mysql_query "SELECT COUNT(*) FROM information_schema.tables WHERE 
table_schema='${GRAVITINO_DB}' AND table_name='metalake_meta';" 2>/dev/null || 
echo 0)
+    [ "$count" = "1" ]
+  else
+    local exists
+    exists=$(psql_client -d "$GRAVITINO_DB" -tAc \
+      "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 
'metalake_meta');" 2>/dev/null || echo f)
+    [ "$exists" = "t" ]
+  fi
+}
+
+extract_table_names() {
+  # The backticks are literal MySQL identifier quotes, not command 
substitution.
+  # shellcheck disable=SC2016
+  grep -io 'create table if not exists [`"]*[a-z0-9_]*[`"]*\|create table 
[`"]*[a-z0-9_]*[`"]*' "$1" |
+    sed 's/.*[Tt][Aa][Bb][Ll][Ee] //; s/[Ii][Ff] [Nn][Oo][Tt] 
[Ee][Xx][Ii][Ss][Tt][Ss] //; s/[`"]//g'
+}
+
+schema_tables_exist() {
+  local schema_sql="$1"
+  local tbl exists
+  local found=0
+  while IFS= read -r tbl; do
+    [ -z "$tbl" ] && continue
+    found=1
+    if [ "$DB_ENGINE" = mysql ]; then
+      exists=$(mysql_query "SELECT COUNT(*) FROM information_schema.tables 
WHERE table_schema='${GRAVITINO_DB}' AND table_name='${tbl}';")
+      [ "$exists" = "1" ] || return 1
+    else
+      exists=$(psql_query "SELECT EXISTS (SELECT FROM 
information_schema.tables WHERE table_name = '${tbl}');")
+      [ "$exists" = "t" ] || return 1
+    fi
+  done < <(extract_table_names "$schema_sql")
+  [ "$found" = "1" ]
+}
+
+column_exists() {
+  local table="$1"
+  local column="$2"
+  local count
+  if [ "$DB_ENGINE" = mysql ]; then
+    count=$(mysql_query "SELECT COUNT(*) FROM information_schema.columns
+      WHERE table_schema='${GRAVITINO_DB}' AND table_name='${table}' AND 
column_name='${column}'")
+    [ "$count" = "1" ]
+  else
+    count=$(psql_query "SELECT COUNT(*) FROM information_schema.columns
+      WHERE table_schema=current_schema() AND table_name='${table}' AND 
column_name='${column}'" | tr -d '[:space:]')
+    [ "$count" = "1" ]
+  fi
+}
+
+# Emit table<TAB>column for each ADD COLUMN in an upgrade script.
+# Tracks the latest ALTER TABLE target so multi-line MySQL upgrades work.
+extract_upgrade_add_columns() {
+  local file="$1"
+  local table="" line col
+  while IFS= read -r line || [ -n "$line" ]; do
+    if printf '%s\n' "$line" | grep -qiE 'alter[[:space:]]+table'; then
+      table=$(printf '%s\n' "$line" | sed -E \
+        
's/.*[Aa][Ll][Tt][Ee][Rr][[:space:]]+[Tt][Aa][Bb][Ll][Ee][[:space:]]+([Ii][Ff][[:space:]]+[Ee][Xx][Ii][Ss][Tt][Ss][[:space:]]+)?[`"]?([A-Za-z0-9_]+).*/\2/')
+      if [ "$table" = "$line" ]; then
+        table=""
+      fi
+    fi
+    if [ -n "$table" ] && printf '%s\n' "$line" | grep -qiE 
'add[[:space:]]+column'; then
+      col=$(printf '%s\n' "$line" | sed -E \
+        
's/.*[Aa][Dd][Dd][[:space:]]+[Cc][Oo][Ll][Uu][Mm][Nn][[:space:]]+([Ii][Ff][[:space:]]+[Nn][Oo][Tt][[:space:]]+[Ee][Xx][Ii][Ss][Tt][Ss][[:space:]]+)?[`"]?([A-Za-z0-9_]+).*/\2/')
+      if [ -n "$col" ] && [ "$col" != "$line" ]; then
+        printf '%s\t%s\n' "$table" "$col"
+      fi
+    fi
+  done <"$file"
+}
+
+# Snapshots such as 1.3.0 and 2.0.0 share the same CREATE TABLE set; require
+# columns introduced by upgrade-*-to-<ver> before claiming that version.
+schema_version_markers_present() {
+  local ver="$1"
+  local f table column
+  shopt -s nullglob
+  local files=("${SCRIPT_DB_DIR}"/upgrade-*-to-"${ver}"-"${DB_ENGINE}".sql)
+  shopt -u nullglob
+  if [ ${#files[@]} -eq 0 ]; then
+    return 0
+  fi
+  for f in "${files[@]}"; do
+    while IFS=$'\t' read -r table column; do
+      if [ -z "$table" ] || [ -z "$column" ]; then
+        continue
+      fi
+      column_exists "$table" "$column" || return 1
+    done < <(extract_upgrade_add_columns "$f")
+  done
+  # Upgrade exists but only creates tables/indexes: table match is enough.
+  return 0
+}
+
+infer_schema_version() {
+  local best="" f ver
+  local matched_without_markers=""
+  shopt -s nullglob
+  local files=("${SCRIPT_DB_DIR}"/schema-*-"${DB_ENGINE}".sql)
+  shopt -u nullglob
+  if [ ${#files[@]} -eq 0 ]; then
+    return 0
+  fi
+  while IFS= read -r f; do
+    ver=$(basename "$f" | sed "s/schema-\\(.*\\)-${DB_ENGINE}\\.sql/\\1/")
+    if version_le "$ver" "$VERSION" && schema_tables_exist "$f"; then
+      if schema_version_markers_present "$ver"; then
+        best="$ver"
+        matched_without_markers=""
+      else
+        # Tables match a newer snapshot whose upgrade columns are missing
+        # (e.g. 1.3.0 DB vs schema-2.0.0.sql). Keep the prior best.
+        matched_without_markers="$ver"
+      fi
+    fi
+  done < <(printf '%s\n' "${files[@]}" | sort -V)
+  if [ -n "$matched_without_markers" ] && [ -z "$best" ]; then
+    echo "ERROR: Existing tables match schema-${matched_without_markers} but 
upgrade columns for that version are missing." >&2
+    echo "Cannot safely infer the starting schema version." >&2
+    echo "Set schema.baselineVersion to the Gravitino version that created 
this database." >&2
+    exit 1
+  fi
+  if [ -n "$matched_without_markers" ] && [ -n "$best" ] && version_lt "$best" 
"$matched_without_markers"; then
+    echo "INFO: Tables also match schema-${matched_without_markers}, but 
upgrade columns are absent; inferring ${best}."

Review Comment:
   Fixed in the latest commit.
   
   The ambiguous-snapshot `INFO` diagnostic in `infer_schema_version` now goes 
to stderr, so `inferred=$(infer_schema_version)` captures only the selected 
`X.Y.Z`. Added `test_infer_1_3_0_keeps_version_capture_clean` to assert stdout 
stays clean, stderr carries the INFO, and the recorded version is a pure 
version token.



##########
dev/charts/gravitino/resources/scripts/schema-migrate.sh:
##########
@@ -0,0 +1,549 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+# Entity-store schema init for the chart schema-migrate Job.
+# Fail on any unexpected SQL error so a broken migration cannot roll out.
+set -euo pipefail
+
+: "${DB_ENGINE:?DB_ENGINE must be mysql or postgresql}"
+: "${DB_HOST:?DB_HOST is required}"
+: "${GRAVITINO_DB:?GRAVITINO_DB is required}"
+: "${SCRIPTS_DIR:=/scripts}"
+
+if [ "$DB_ENGINE" != mysql ] && [ "$DB_ENGINE" != postgresql ]; then
+  echo "ERROR: DB_ENGINE must be mysql or postgresql (got ${DB_ENGINE})" >&2
+  exit 1
+fi
+
+if [ "$DB_ENGINE" = mysql ]; then
+  : "${MYSQL_USER:?MYSQL_USER is required}"
+  : "${MYSQL_PWD:?MYSQL_PWD is required}"
+  export MYSQL_PWD
+else
+  : "${POSTGRES_USER:?POSTGRES_USER is required}"
+  : "${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}"
+fi
+
+DB_PORT="${DB_PORT:-}"
+PG_CURRENT_SCHEMA="${PG_CURRENT_SCHEMA:-}"
+BASELINE_VERSION="${BASELINE_VERSION:-}"
+VERSION_FILE="${SCRIPTS_DIR}/version.txt"
+
+mysql_client() {
+  local extra=()
+  if [ -n "$DB_PORT" ]; then
+    extra+=(-P "$DB_PORT")
+  fi
+  mysql -h "$DB_HOST" "${extra[@]}" -u "$MYSQL_USER" "$@"
+}
+
+psql_client() {
+  local extra=()
+  if [ -n "$DB_PORT" ]; then
+    extra+=(-p "$DB_PORT")
+  fi
+  PGPASSWORD="$POSTGRES_PASSWORD" psql -h "$DB_HOST" "${extra[@]}" -U 
"$POSTGRES_USER" "$@"
+}
+
+version_le() {
+  [ "$(printf '%s\n%s' "$1" "$2" | sort -V | head -n1)" = "$1" ]
+}
+
+version_lt() {
+  [ "$1" != "$2" ] && version_le "$1" "$2"
+}
+
+wait_for_db() {
+  echo "Waiting for ${DB_ENGINE} at ${DB_HOST}..."
+  if [ "$DB_ENGINE" = mysql ]; then
+    until mysql_client -e "SELECT 1" >/dev/null 2>&1; do
+      echo "Waiting for MySQL to be ready..."
+      sleep 2
+    done
+  else
+    until psql_client -d "$GRAVITINO_DB" -c "SELECT 1" >/dev/null 2>&1; do
+      echo "Waiting for PostgreSQL to be ready..."
+      sleep 2
+    done
+  fi
+}
+
+mysql_query() {
+  mysql_client -D "$GRAVITINO_DB" -sNe "$1"
+}
+
+mysql_exec() {
+  mysql_client -D "$GRAVITINO_DB" -e "$1"
+}
+
+psql_query() {
+  psql_client -d "$GRAVITINO_DB" -v ON_ERROR_STOP=1 -tAc "$1"
+}
+
+db_query() {
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_query "$1"
+  else
+    psql_query "$1"
+  fi
+}
+
+# Community upgrade-*-mysql.sql uses ADD COLUMN / DROP INDEX without IF NOT 
EXISTS.
+# Ignore "already applied" errors so re-runs and overlapping snapshots stay 
safe.
+mysql_is_already_applied_error() {
+  case "$1" in
+    1060 | 1061 | 1068 | 1091 | 1176 | 1280) return 0 ;;
+    *) return 1 ;;
+  esac
+}
+
+mysql_apply_sql_file() {
+  local file="$1"
+  local out unexpected code line rc
+  set +e
+  out="$(mysql_client -D "$GRAVITINO_DB" --force <"$file" 2>&1)"
+  rc=$?
+  set -e
+  if [ -n "${out}" ]; then
+    printf '%s\n' "${out}"
+  fi
+  unexpected=""
+  while IFS= read -r line; do
+    [ -z "${line}" ] && continue
+    code="$(printf '%s' "${line}" | sed -n 's/.*ERROR \([0-9][0-9]*\).*/\1/p')"
+    [ -n "${code}" ] || continue
+    if mysql_is_already_applied_error "${code}"; then
+      echo "INFO: ignoring already-applied MySQL error ${code}"
+      continue
+    fi
+    unexpected="${unexpected}${line}"$'\n'
+  done < <(printf '%s\n' "${out}" | grep -E 'ERROR [0-9]+' || true)
+  if [ -n "${unexpected}" ]; then
+    echo "ERROR: SQL script failed: $file" >&2
+    printf '%s' "${unexpected}" >&2
+    exit 1
+  fi
+  if [ "${rc}" != 0 ] && ! printf '%s\n' "${out}" | grep -qE 'ERROR [0-9]+'; 
then
+    echo "ERROR: mysql client failed: $file" >&2
+    printf '%s\n' "${out}" >&2
+    exit 1
+  fi
+}
+
+apply_sql_file() {
+  local file="$1"
+  echo "Applying $file"
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_apply_sql_file "$file"
+  else
+    if ! psql_client -d "$GRAVITINO_DB" -v ON_ERROR_STOP=1 -f "$file"; then
+      echo "ERROR: SQL script failed: $file" >&2
+      exit 1
+    fi
+  fi
+}
+
+# 1.3.2 widened table_column_version_info.column_name. Existing 1.3.x DBs may
+# already record a later version without that ALTER; repair before ready.
+ensure_column_name_capacity() {
+  version_le 1.3.2 "$VERSION" || return 0
+
+  local scope capacity
+  if [ "$DB_ENGINE" = mysql ]; then
+    scope='DATABASE()'
+  else
+    scope='current_schema()'
+  fi
+  capacity=$(db_query "SELECT character_maximum_length FROM 
information_schema.columns
+    WHERE table_schema = ${scope} AND table_name = 'table_column_version_info'
+      AND column_name = 'column_name';" | tr -d '[:space:]')
+  case "$capacity" in
+    '' | *[!0-9]*)
+      echo "ERROR: Cannot determine table_column_version_info.column_name 
capacity" >&2
+      exit 1
+      ;;
+  esac
+  [ "$capacity" -lt 300 ] || return 0
+
+  echo "Expanding table_column_version_info.column_name from ${capacity} to 
300 characters"
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_exec "ALTER TABLE table_column_version_info
+      MODIFY COLUMN column_name VARCHAR(300) NOT NULL COMMENT 'column name';"
+  else
+    psql_query "ALTER TABLE table_column_version_info
+      ALTER COLUMN column_name TYPE VARCHAR(300);" >/dev/null
+  fi
+}
+
+ensure_migration_table() {
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_exec "CREATE TABLE IF NOT EXISTS gravitino_schema_migration (
+      id TINYINT UNSIGNED NOT NULL PRIMARY KEY,
+      schema_version VARCHAR(64) NOT NULL,
+      updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE 
CURRENT_TIMESTAMP
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;"
+  else
+    psql_query "CREATE TABLE IF NOT EXISTS gravitino_schema_migration (
+      id SMALLINT NOT NULL PRIMARY KEY,
+      schema_version VARCHAR(64) NOT NULL,
+      updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+    );" >/dev/null
+  fi
+}
+
+read_recorded_version() {
+  db_query "SELECT schema_version FROM gravitino_schema_migration WHERE id = 
1;" 2>/dev/null | tr -d '[:space:]' || true
+}
+
+write_recorded_version() {
+  local ver="$1"
+  if [ "$DB_ENGINE" = mysql ]; then
+    mysql_exec "INSERT INTO gravitino_schema_migration (id, schema_version) 
VALUES (1, '${ver}')
+      ON DUPLICATE KEY UPDATE schema_version = '${ver}';"
+  else
+    psql_query "INSERT INTO gravitino_schema_migration (id, schema_version, 
updated_at)
+      VALUES (1, '${ver}', NOW())
+      ON CONFLICT (id) DO UPDATE SET schema_version = EXCLUDED.schema_version, 
updated_at = NOW();" >/dev/null
+  fi
+  echo "Recorded schema version ${ver}"
+}
+
+metalake_exists() {
+  if [ "$DB_ENGINE" = mysql ]; then
+    local count
+    count=$(mysql_query "SELECT COUNT(*) FROM information_schema.tables WHERE 
table_schema='${GRAVITINO_DB}' AND table_name='metalake_meta';" 2>/dev/null || 
echo 0)
+    [ "$count" = "1" ]
+  else
+    local exists
+    exists=$(psql_client -d "$GRAVITINO_DB" -tAc \
+      "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 
'metalake_meta');" 2>/dev/null || echo f)

Review Comment:
   Fixed in the latest commit.
   
   PostgreSQL `metalake_exists` and `schema_tables_exist` now require 
`table_schema = current_schema()`. Added 
`TestSchemaMigratePostgresCurrentSchema` covering a populated 
`public.metalake_meta` plus an empty target schema (`PGOPTIONS` search_path), 
which must take the fresh-install path.



##########
dev/ci/chart-schema-migrate-cross-version.sh:
##########
@@ -0,0 +1,234 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+# Live kind coverage: seed an existing relational schema at FROM_VERSION, then
+# helm upgrade with schema.migrate.enabled so the Job applies the upgrade chain
+# to the image version.
+#
+# Required env:
+#   KIND_REGISTRY, tag
+# Optional env:
+#   ENGINE (mysql|postgresql, default mysql)
+#   FROM_VERSION (1.2.0|1.3.0, default 1.2.0)
+#   NAMESPACE, RELEASE_NAME, CHART_DIR, VALUES_FILE, REPO_ROOT
+set -euo pipefail
+
+REPO_ROOT="${REPO_ROOT:-$(cd "$(dirname "$0")/../.." && pwd)}"
+CHART_DIR="${CHART_DIR:-${REPO_ROOT}/dev/charts/gravitino}"
+ENGINE="${ENGINE:-mysql}"
+FROM_VERSION="${FROM_VERSION:-1.2.0}"
+CHECK_SCRIPT="${REPO_ROOT}/dev/ci/check-schema-migrate.sh"
+
+case "$ENGINE" in
+  mysql)
+    
VALUES_FILE="${VALUES_FILE:-${REPO_ROOT}/dev/charts/gravitino/resources/scenarios/schema-migrate-mysql.yaml}"
+    SCHEMA_SQL="${REPO_ROOT}/scripts/mysql/schema-${FROM_VERSION}-mysql.sql"
+    WAIT_INIT=init-mysql
+    DB_LABEL=mysql
+    ;;
+  postgresql)
+    
VALUES_FILE="${VALUES_FILE:-${REPO_ROOT}/dev/charts/gravitino/resources/scenarios/schema-migrate-postgresql.yaml}"
+    
SCHEMA_SQL="${REPO_ROOT}/scripts/postgresql/schema-${FROM_VERSION}-postgresql.sql"
+    WAIT_INIT=init-postgresql
+    DB_LABEL=postgresql
+    ;;
+  *)
+    echo "ERROR: ENGINE must be mysql or postgresql (got ${ENGINE})" >&2
+    exit 1
+    ;;
+esac
+
+case "$FROM_VERSION" in
+  1.2.0 | 1.3.0) ;;
+  *)
+    echo "ERROR: FROM_VERSION must be 1.2.0 or 1.3.0 (got ${FROM_VERSION})" >&2
+    exit 1
+    ;;
+esac
+
+FROM_SLUG=${FROM_VERSION//./}
+NAMESPACE="${NAMESPACE:-schema-migrate-cross-${ENGINE}-${FROM_SLUG}}"
+RELEASE_NAME="${RELEASE_NAME:-gravitino-sm-${ENGINE}-${FROM_SLUG}}"
+
+: "${KIND_REGISTRY:?KIND_REGISTRY is required}"
+: "${tag:?tag is required}"
+
+if [ ! -f "$SCHEMA_SQL" ]; then
+  echo "ERROR: missing baseline schema SQL: ${SCHEMA_SQL}" >&2
+  exit 1
+fi
+if [ ! -f "$CHECK_SCRIPT" ]; then
+  echo "ERROR: missing ${CHECK_SCRIPT}" >&2
+  exit 1
+fi
+
+chmod +x "$CHECK_SCRIPT"
+helm dependency update "$CHART_DIR"
+
+cleanup() {
+  helm uninstall "$RELEASE_NAME" -n "$NAMESPACE" --wait || true
+  kubectl delete namespace "$NAMESPACE" --wait=false || true
+}
+trap cleanup EXIT
+
+kubectl get namespace "$NAMESPACE" >/dev/null 2>&1 || kubectl create namespace 
"$NAMESPACE"
+
+echo "==> Fresh install with schema.migrate.enabled (${ENGINE})"
+helm upgrade --install "$RELEASE_NAME" "$CHART_DIR" -n "$NAMESPACE" --wait 
--timeout 10m \
+  --values "$VALUES_FILE" \
+  --set image.registry="" \
+  --set image.repository="${KIND_REGISTRY}/gravitino" \
+  --set image.tag="${tag}"
+bash "$CHECK_SCRIPT" "$NAMESPACE" "$RELEASE_NAME" "$ENGINE"
+
+DEPLOY=$(kubectl get deploy -n "$NAMESPACE" -l "release=${RELEASE_NAME}" -o 
jsonpath='{.items[0].metadata.name}')
+DB_POD=$(kubectl get pods -n "$NAMESPACE" -l 
"app.kubernetes.io/name=${DB_LABEL}" \
+  -o jsonpath='{.items[0].metadata.name}')
+DB_NAME=$(kubectl get deploy -n "$NAMESPACE" "$DEPLOY" \
+  -o 
jsonpath="{.spec.template.spec.initContainers[?(@.name==\"${WAIT_INIT}\")].env[?(@.name==\"GRAVITINO_DB\")].value}")
+
+column_count() {
+  local table="$1"
+  local column="$2"
+  if [ "$ENGINE" = mysql ]; then
+    local root_pw
+    root_pw=$(kubectl get secret -n "$NAMESPACE" "${RELEASE_NAME}-mysql" \
+      -o jsonpath='{.data.mysql-root-password}' | base64 -d)
+    kubectl exec -n "$NAMESPACE" "$DB_POD" -- \
+      mysql -uroot -p"${root_pw}" -D "${DB_NAME}" -sNe \
+      "SELECT COUNT(*) FROM information_schema.columns WHERE 
table_schema=DATABASE() AND table_name='${table}' AND column_name='${column}'" \
+      | tr -d '[:space:]'
+  else
+    local pg_user pg_pw
+    pg_user=$(kubectl get deploy -n "$NAMESPACE" "$DEPLOY" \
+      -o 
jsonpath='{.spec.template.spec.initContainers[?(@.name=="init-postgresql")].env[?(@.name=="POSTGRES_USER")].value}')
+    pg_pw=$(kubectl get secret -n "$NAMESPACE" "${RELEASE_NAME}-postgresql" \
+      -o jsonpath='{.data.password}' | base64 -d)
+    kubectl exec -n "$NAMESPACE" "$DB_POD" -- \
+      env PGPASSWORD="${pg_pw}" psql -U "${pg_user}" -d "${DB_NAME}" -tAc \
+      "SELECT COUNT(*) FROM information_schema.columns WHERE 
table_schema=current_schema() AND table_name='${table}' AND 
column_name='${column}'" \
+      | tr -d '[:space:]'
+  fi
+}
+
+assert_column() {
+  local table="$1"
+  local column="$2"
+  local expected="$3"
+  local actual
+  actual=$(column_count "$table" "$column")
+  if [ "$actual" != "$expected" ]; then
+    echo "ERROR: ${table}.${column} count=${actual}, expected ${expected}" >&2
+    exit 1
+  fi
+}
+
+echo "==> Scale Gravitino to zero before reseeding ${FROM_VERSION} ${ENGINE} 
schema"
+kubectl scale deploy -n "$NAMESPACE" "$DEPLOY" --replicas=0
+kubectl wait -n "$NAMESPACE" --for=delete pod -l "release=${RELEASE_NAME}" 
--timeout=180s || true
+
+echo "==> Reset database to schema-${FROM_VERSION}-${ENGINE}.sql"
+REMOTE_SQL="/tmp/schema-${FROM_VERSION}-${ENGINE}.sql"
+kubectl cp "$SCHEMA_SQL" "${NAMESPACE}/${DB_POD}:${REMOTE_SQL}"
+if [ "$ENGINE" = mysql ]; then
+  ROOT_PW=$(kubectl get secret -n "$NAMESPACE" "${RELEASE_NAME}-mysql" \
+    -o jsonpath='{.data.mysql-root-password}' | base64 -d)
+  kubectl exec -n "$NAMESPACE" "$DB_POD" -- \
+    mysql -uroot -p"${ROOT_PW}" -e "DROP DATABASE IF EXISTS \`${DB_NAME}\`; 
CREATE DATABASE \`${DB_NAME}\`;"
+  kubectl exec -n "$NAMESPACE" "$DB_POD" -- \
+    bash -c "mysql -uroot -p\"${ROOT_PW}\" -D '${DB_NAME}' < '${REMOTE_SQL}'"
+else
+  PG_USER=$(kubectl get deploy -n "$NAMESPACE" "$DEPLOY" \
+    -o 
jsonpath='{.spec.template.spec.initContainers[?(@.name=="init-postgresql")].env[?(@.name=="POSTGRES_USER")].value}')
+  PG_PW=$(kubectl get secret -n "$NAMESPACE" "${RELEASE_NAME}-postgresql" \
+    -o jsonpath='{.data.password}' | base64 -d)
+  # Drop schema objects so leftover gravitino_schema_migration cannot leak.
+  # Prefer DROP SCHEMA over DROP DATABASE: the chart app user may not be a 
superuser.
+  kubectl exec -n "$NAMESPACE" "$DB_POD" -- \
+    env PGPASSWORD="${PG_PW}" psql -U "${PG_USER}" -d "${DB_NAME}" -v 
ON_ERROR_STOP=1 \
+    -c "DROP SCHEMA IF EXISTS public CASCADE;" \
+    -c "CREATE SCHEMA public AUTHORIZATION \"${PG_USER}\";" \
+    -c "GRANT ALL ON SCHEMA public TO \"${PG_USER}\";"
+  kubectl exec -n "$NAMESPACE" "$DB_POD" -- \
+    env PGPASSWORD="${PG_PW}" psql -U "${PG_USER}" -d "${DB_NAME}" -v 
ON_ERROR_STOP=1 -f "${REMOTE_SQL}"
+fi
+
+case "$FROM_VERSION" in
+  1.2.0)
+    assert_column view_meta audit_info 0
+    assert_column user_meta enabled 0
+    echo "Seeded ${FROM_VERSION}: view_meta.audit_info and user_meta.enabled 
absent"
+    ;;
+  1.3.0)
+    assert_column view_meta audit_info 1
+    assert_column user_meta enabled 0
+    echo "Seeded ${FROM_VERSION}: view_meta.audit_info present, 
user_meta.enabled absent"
+    ;;
+esac
+
+# 1.3.0 shares table names with 2.0.0; exercise automatic inference (no 
baseline)
+# so upgrade columns such as user_meta.enabled are still applied.
+if [ "$FROM_VERSION" = "1.3.0" ]; then
+  echo "==> Helm upgrade without schema.baselineVersion (${ENGINE}, infer from 
columns)"
+  helm upgrade "$RELEASE_NAME" "$CHART_DIR" -n "$NAMESPACE" --wait --timeout 
10m \
+    --values "$VALUES_FILE" \
+    --set image.registry="" \
+    --set image.repository="${KIND_REGISTRY}/gravitino" \
+    --set image.tag="${tag}" \
+    --set "podAnnotations.schema-migrate-cross=$(date +%s)"
+
+  bash "$CHECK_SCRIPT" "$NAMESPACE" "$RELEASE_NAME" "$ENGINE"
+
+  JOB=$(kubectl get jobs -n "$NAMESPACE" -l 
app.kubernetes.io/component=schema-migrate \
+    --sort-by=.metadata.creationTimestamp -o 
jsonpath='{.items[-1:].metadata.name}')
+  LOG="/tmp/${JOB}-cross-infer.log"
+  kubectl logs -n "$NAMESPACE" "job/${JOB}" --all-containers=true | tee "$LOG"
+  grep -q "inferred 1.3.0 from existing tables" "$LOG"
+  grep -q "upgrade-1.3.0-to-2.0.0-${ENGINE}" "$LOG"
+  if grep -q "upgrade-1.2.0-to-1.3.0-${ENGINE}" "$LOG"; then
+    echo "ERROR: unexpected upgrade-1.2.0-to-1.3.0 when inferred baseline is 
1.3.0" >&2
+    exit 1
+  fi
+  assert_column view_meta audit_info 1
+  assert_column user_meta enabled 1

Review Comment:
   Fixed in the latest commit.
   
   Cross-version seed and post-upgrade asserts now check 
`idp_user_meta.enabled` (the column added by `upgrade-1.3.0-to-2.0.0-*`) 
instead of `user_meta.enabled`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to