Skip to content

Instantly share code, notes, and snippets.

@konsumer
Last active November 7, 2025 00:47
Show Gist options
  • Save konsumer/59e21b5bf4dba6b89307518486b93d68 to your computer and use it in GitHub Desktop.
Save konsumer/59e21b5bf4dba6b89307518486b93d68 to your computer and use it in GitHub Desktop.
Say you have a remote D1 database called "DB". You can run this to produce a diff-migration for structure.sql: `./d1_diff_migrate.sh feature1 DB structure.sql`, then run `npx -y wrangler d1 migrations apply DB`
#!/bin/bash
# this will create a D1 migration that diffs the current remote database
set -eo pipefail
if ! command -v npx &> /dev/null; then
echo "npx needs to be in your path." >&2
exit 1
fi
if ! command -v sqlite3 &> /dev/null; then
echo "sqlite3 needs to be in your path." >&2
exit 1
fi
if ! command -v sqldiff &> /dev/null; then
echo "sqldiff needs to be in your path." >&2
exit 1
fi
MIGRATION_NAME="${1}"
D1_NAME="${2}"
PROPOSED_FILE="${3}"
if [ "${MIGRATION_NAME}" == "" ] || [ "${PROPOSED_FILE}" == "" ] || [ "${D1_NAME}" == "" ];then
echo "Usage d1_diff_migrate <MIGRATION_NAME> <D1_NAME> <PROPOSED_FILE>"
exit 1
fi
rm -f /tmp/current.db /tmp/proposed.db
# build current
npx -y wrangler d1 execute "${D1_NAME}" --remote --json --command "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' AND name <> '_cf_KV' AND name <> 'd1_migrations';" | jq -c -r '.[].results[].sql | . + ";"'| sqlite3 /tmp/current.db
# generate migration file
MIGRATION_FILE="$(npx -y wrangler d1 migrations create DB "${MIGRATION_NAME}" | tail -n 1)"
# build proposed
sqlite3 /tmp/proposed.db < "${PROPOSED_FILE}"
DIFF="$(sqldiff /tmp/current.db /tmp/proposed.db)"
if [ "${DIFF}" == "" ];then
echo "no chnages."
rm "${MIGRATION_FILE}"
else
echo "${DIFF}"
echo "${DIFF}" >> "${MIGRATION_FILE}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment