patch_seq.pl 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) Roman Dmitriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use open ":encoding(utf8)";
  7. use open ':std', ':encoding(UTF-8)';
  8. use Encode;
  9. no warnings 'utf8';
  10. use English;
  11. use FindBin '$Bin';
  12. use lib "/opt/Eye/scripts";
  13. use Getopt::Long qw(GetOptions);
  14. use Data::Dumper;
  15. use eyelib::config;
  16. use eyelib::main;
  17. use eyelib::database;
  18. use eyelib::common;
  19. use eyelib::net_utils;
  20. use strict;
  21. use warnings;
  22. # debug disable force
  23. $debug = 0;
  24. # === Явное указание портов ===
  25. my $PG_PORT = 5432;
  26. # === Подключение к PostgreSQL (цель) ===
  27. my $pg_dsn = "dbi:Pg:dbname=$DBNAME;host=$DBHOST;port=$PG_PORT;";
  28. my $pg_db = DBI->connect($pg_dsn, $DBUSER, $DBPASS, {
  29. RaiseError => 0,
  30. AutoCommit => 1,
  31. pg_enable_utf8 => 1,
  32. pg_server_prepare => 0
  33. });
  34. if (!defined $pg_db) {
  35. print "Cannot connect to PostgreSQL server: $DBI::errstr\n";
  36. print "For install/configure PostgreSQL server please run migrate2psql.sh!\n";
  37. exit 100;
  38. }
  39. print "\n=== Resetting all table sequences ===\n";
  40. # Получаем список всех таблиц из целевой схемы (PostgreSQL)
  41. my $tables_sql = "SELECT tablename FROM pg_tables WHERE schemaname = 'public'";
  42. my $sth = $pg_db->prepare($tables_sql);
  43. $sth->execute();
  44. while (my ($table) = $sth->fetchrow_array) {
  45. # Формируем имя последовательности
  46. my $seq_name = "${table}_id_seq";
  47. # Проверяем, существует ли такая последовательность
  48. my ($exists) = $pg_db->selectrow_array(
  49. "SELECT 1 FROM pg_class WHERE relname = ? AND relkind = 'S'",
  50. undef, $seq_name
  51. );
  52. if ($exists) {
  53. # Получаем MAX(id)
  54. my ($max_id) = $pg_db->selectrow_array("SELECT MAX(id) FROM \"$table\"");
  55. $max_id //= 1;
  56. # Сбрасываем последовательность
  57. $pg_db->do("SELECT setval('$seq_name', $max_id)");
  58. print " → $table: sequence reset to $max_id\n";
  59. }
  60. }
  61. print "✅ All sequences updated.\n";
  62. exit 0;