db-patch-mysql-utf8.pl 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use strict;
  7. use warnings;
  8. use Encode;
  9. use open qw(:std :encoding(UTF-8));
  10. no warnings 'utf8';
  11. use FindBin '$Bin';
  12. use lib "/opt/Eye/scripts";
  13. use Data::Dumper;
  14. use eyelib::config;
  15. use eyelib::main;
  16. use eyelib::database;
  17. use eyelib::common;
  18. use eyelib::logconfig;
  19. use strict;
  20. use warnings;
  21. exit 100 if ($config_ref{DBTYPE} and $config_ref{DBTYPE} ne 'mysql');
  22. my @tables = get_records_sql($dbh,"SHOW TABLES");
  23. my @db_tables=();
  24. foreach my $table_ref (@tables) {
  25. push(@db_tables,$table_ref->{Tables_in_stat});
  26. }
  27. print "Stage1: Migrate tables to UTF8 format\n";
  28. for my $table (@db_tables) {
  29. print "Apply table $table\n";
  30. $dbh->do("SET foreign_key_checks = 0;");
  31. do_sql($dbh,"ALTER TABLE `".$table."` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
  32. $dbh->do("SET foreign_key_checks = 1;");
  33. }
  34. print "Done\n";
  35. print "Stage2: Migrate database\n";
  36. do_sql($dbh,"ALTER DATABASE ".$DBNAME." CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
  37. print "Done\n";
  38. print "Stage3: Revert filed type to TEXT\n";
  39. for my $table (@db_tables) {
  40. my $sql = "select * from $table LIMIT 1";
  41. my $sth = $dbh->prepare( $sql );
  42. $sth->execute();
  43. print "\tStructure of $table \n\n";
  44. my $num_fields = $sth->{NUM_OF_FIELDS};
  45. for ( my $i=0; $i< $num_fields; $i++ ) {
  46. my $field = $sth->{NAME}->[$i];
  47. my $type = $sth->{TYPE}->[$i];
  48. my $precision = $sth->{PRECISION}->[$i];
  49. print "\t\tField: $field is of type: $type precision: $precision\n";
  50. if ($type == "-4" and $precision>262140) {
  51. print "\t\tMigrate field $field to type TEXT\n";
  52. do_sql($dbh,"ALTER TABLE `".$table."` MODIFY `".$field."` TEXT");
  53. }
  54. }
  55. $sth->finish();
  56. }
  57. print "Done!\n";
  58. exit;