ibanez270dx of Cognoa
8/16/2018 - 9:00 PM

Backup or restore single database table

Assumes you're in a Rails project. Useful for testing large, destructive migrations.

#!/usr/bin/env bash

# Backup a table. Naming defaults to *_backup, pass additional argument for *_whatever.
function backup_table {
    local t1=${1}
    local t2=${1}_${2:-backup}
    rails db << EOF
    \! echo "dropping $t2 if it exists..."
    drop table if exists $t2;
    \! echo "creating $t2..."
    create table $t2 like $t1;
    \! echo "copying $t1 to $t2..."
    insert into $t2 select * from $t1;
    \! echo "Done!"
    select count(*) from $t2;
EOF
}

# Restore a table. Assumes *_backup, pass additional argument for *_whatever.
function restore_table {
  local t1=${1}
  local t2=${1}_${2:-backup}
  rails db << EOF
    \! echo "dropping $t1..."
    drop table $1;
    \! echo "creating $t1..."
    create table $t1 like $t2;
    \! echo "copying $t2 to $t1...";
    insert into $t1 select * from $t2;
    \! echo "Done!"
    select count(*) from $t1;
EOF
}