Skip to content

Instantly share code, notes, and snippets.

@phred
Created May 16, 2016 07:43
Show Gist options
  • Save phred/3c2d2bed3ec6058767f567a30203c94f to your computer and use it in GitHub Desktop.
Save phred/3c2d2bed3ec6058767f567a30203c94f to your computer and use it in GitHub Desktop.
tiny script to dump tables with dependencies / child records in the correct order for later re-insertion
#!/bin/bash
set -eu
export DB=mydb
function dump {
echo '-- mysqldump --compact -t $DB' $@
mysqldump --compact -t $DB $@
}
PK_ID=$1
CUST_ID=`mysql $DB -e "select customer_id from orders where id = $PK_ID" | tail -1`
CART_ID=`mysql $DB -e "select cartId from customers where id = $CUST_ID" | tail -1`
IFS=$'\n'
ORDER_TABLES=$(cat <<-END
orders id
line_items order_id
payment_logs order_id
END
)
# customer tables
CUST_TABLES=$(cat <<-END
customers id
customer_cards customerId
END
)
CART_TABLES$(cat <<-END
cart id
END)
cat <<END
--
-- transaction_id: $PK_ID
-- customer_id: $CUST_ID
-- `mysql -e "show variables like '%hostname%'" | tail -1`
--
END
function dump_dependents {
eval tables=\$$1
for t in $tables; do
TABLE=${t%% *}
INDEX=${t#* }
dump $TABLE -w "$INDEX=$2"
done
}
dump_dependents CART_TABLES $CART_ID
dump_dependents ORDER_TABLES $PK_ID
dump_dependents CUST_TABLES $CUST_ID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment