Guest User

Untitled

a guest
Jun 21st, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. <?php
  2. /**
  3. * Primary keys can be a pain in the neck during multi-master replication
  4. * This script can ensure that the primary keys on any two different
  5. * postgresql databases which are to be replicated in a multi-master
  6. * fashion are always different. How? Just run this script on the
  7. * first database to covert all its sequences to even numbers and
  8. * run it again on the second database to convert all its sequences to
  9. * odd numbers. The script ajusts the increments of the sequences so
  10. * they would forever generate either even or odd numbers.
  11. *
  12. *
  13. * Used this script with bucardo's swap sync.
  14. *
  15. * Usage
  16. * =====
  17. * php update_sequences.php [OPTIONS]
  18. * --host <hostname> The database host
  19. * --user <username> The database username
  20. * --password <password> The password of the user (unsecure right?)
  21. * --db <database> The name of the database
  22. * --mode <mode> The mode of conversion should be even or odd
  23. *
  24. * Note that the mode option doesn't validate.
  25. */
  26.  
  27. // Add the sequences you dont want affected here. The schema doesn't
  28. // really matter.
  29. $exclude = array(
  30. 'client_code_seq',
  31. 'jv_number_seq',
  32. 'pv_number_seq',
  33. );
  34.  
  35. for ($i = 1; $i < $argc; $i++)
  36. {
  37. if(substr($argv[$i], 0, 2) == "--")
  38. {
  39. $parameter = substr($argv[$i], 2, strlen($argv[$i]) - 2);
  40. $i++;
  41. $$parameter = $argv[$i];
  42. }
  43. else
  44. {
  45. $tables[] = $argv[$i];
  46. }
  47. }
  48.  
  49. $conn = pg_connect("host=$host port=5432 dbname=$db user=$user password=$password");
  50.  
  51. pg_query($conn,"BEGIN");
  52. $sequences_result = pg_query($conn, "SELECT * FROM information_schema.sequences");
  53. $sequences = array();
  54. while($sequence = pg_fetch_assoc($sequences_result))
  55. {
  56. if(array_search($sequence['sequence_name'], $exclude) !== false)
  57. {
  58. echo "Skipping " . $sequence['sequence_schema'] . '.' . $sequence['sequence_name'] . "\n";
  59. continue;
  60. }
  61. $sequence = $sequence['sequence_schema'] . '.' . $sequence['sequence_name'];
  62. $value = pg_query($conn, "SELECT last_value from $sequence");
  63. $value = pg_fetch_assoc($value);
  64.  
  65. pg_query($conn, "ALTER SEQUENCE $sequence INCREMENT BY 2");
  66.  
  67. if($value["last_value"] % 2 == 0 && $mode == 'odd')
  68. {
  69. pg_query($conn, "ALTER SEQUENCE $sequence RESTART WITH " . ($value['last_value'] + 1));
  70. }
  71. elseif(($value["last_value"] % 2 == 1 || $value["last_value"] == 1) && $mode == 'even')
  72. {
  73. pg_query($conn, "ALTER SEQUENCE $sequence RESTART WITH " . ($value['last_value'] + 1));
  74. }
  75. }
  76. pg_query($conn,"COMMIT");
Add Comment
Please, Sign In to add comment