Skip to content

Instantly share code, notes, and snippets.

@Enelar
Created May 13, 2014 13:24
Show Gist options
  • Save Enelar/fdf90a69dfbaf7948ac1 to your computer and use it in GitHub Desktop.
Save Enelar/fdf90a69dfbaf7948ac1 to your computer and use it in GitHub Desktop.
Posgtresql add column after or before.
// Warning! You lose all constraight's
// All depended views NOT updating
function AddColumnPos( $table_name, $pos, $name, $data_type )
{
db::Query("BEGIN");
db::Query("LOCK TABLE {$table_name} IN ACCESS EXCLUSIVE MODE");
db::Query("SET CONSTRAINTS ALL DEFERRED");
$cols = db::Query("SELECT column_name as name, data_type as type FROM information_schema.columns WHERE table_name='{$table_name}'");
assert($cols);
$salt = md5(time());
// Rename all columns (temporary)
for ($i = $pos; $i < count($cols); $i++)
db::Query("ALTER TABLE {$table_name} RENAME {$cols[i].name} TO {$cols[$i].name}_{$salt}");
// Add new column
db::Query("ALTER TABLE {$table_name} ADD {$name} {$data_type}");
// Dublicate columns
for ($i = $pos; $i < count($ret); $i++)
db::Query("ALTER TABLE {$table_name} ADD {$cols[i].name} {$cols[i].type}");
// Copy data
for ($i = $pos; $i < count($ret); $i++)
db::Query("UPDATE {$table_name} SET {$cols[i].name}={$cols[i].name}_{$salt}");
// TODO:
// Apply constraight's
// Find foreign keys and rebind
// Remove orign columns
for ($i = $pos; $i < count($cols); $i++)
db::Query("ALTER TABLE {$table_name} DROM {$cols[$i].name}_{$salt}");
db::Query("COMMIT");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment