diff --git a/package/migrator/migrator.sh b/package/migrator/migrator.sh index e53ded0..799256a 100644 --- a/package/migrator/migrator.sh +++ b/package/migrator/migrator.sh @@ -22,14 +22,36 @@ while [ $# -gt 0 ]; do shift 2 ;; --inherits) - INHERITS_LIST="${INHERITS_LIST:+$INHERITS_LIST }$2" + INHERITS_LIST="${INHERITS_LIST:+$INHERITS_LIST\"}$2" shift 2 ;; + --init-dry-run) + INIT_DRY_RUN=1 + shift + ;; --*|-*) REMAINING_ARS="$REMAINING_ARS $(quote "$1")"; shift ;; # unknown global -> pass through *) REMAINING_ARS="$REMAINING_ARS $(quote "$1")"; shift ;; esac done +INHERITS_LIST="$(printf '%s' "$INHERITS_LIST" | sed -E 's/"/,/g; s/([^,]+)/"\1"/g')" + +init() { + log debug "inherits: ${WHITE}${INHERITS_LIST}${NC}" + local create_table + create_table="$(printf '%s\n' \ + 'CREATE SCHEMA IF NOT EXISTS hectic;' \ + 'CREATE TABLE IF NOT EXISTS hectic.migration (' \ + ' id SERIAL PRIMARY KEY,' \ + ' name TEXT UNIQUE NOT NULL,'\ + ' applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()' \ + ')')" + + printf '%s INHERITS(%s)' "$create_table" "$INHERITS_LIST" +} + +[ "${INIT_DRY_RUN+x}" ] && { printf '%s\n' "$(init)"; exit; } + [ "${SUBCOMMAND+x}" ] || { log error "no subcomand specified"; exit 1; } help() { diff --git a/test/package/migrator/test/init-migrations.sh b/test/package/migrator/test/init-migrations.sh new file mode 100644 index 0000000..e48cc9c --- /dev/null +++ b/test/package/migrator/test/init-migrations.sh @@ -0,0 +1,6 @@ +if ! migration_table_sql="$(migrator --inherits tablename --inherits 'table name' --init-dry-run)"; then + log error "test failed: error on migration table init dry run" +fi + +printf '%s' "$migration_table_sql" | grep -Eq 'INHERITS[[:space:]]*\([[:space:]]*"tablename"[[:space:]]*,[[:space:]]*"table name"[[:space:]]*\)' || + { log error "not correct migration table inherits"; exit 1; }