db-patch-mysql-utf8.pl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 strict;
  19. use warnings;
  20. exit 100 if ($config_ref{DBTYPE} and $config_ref{DBTYPE} ne 'mysql');
  21. my @tables = get_records_sql($dbh,"SHOW TABLES");
  22. my @db_tables=();
  23. foreach my $table_ref (@tables) {
  24. push(@db_tables,$table_ref->{Tables_in_stat});
  25. }
  26. print "Stage1: Migrate tables to UTF8 format\n";
  27. for my $table (@db_tables) {
  28. print "Apply table $table\n";
  29. $dbh->do("SET foreign_key_checks = 0;");
  30. do_sql($dbh,"ALTER TABLE `".$table."` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
  31. $dbh->do("SET foreign_key_checks = 1;");
  32. }
  33. print "Done\n";
  34. print "Stage2: Migrate database\n";
  35. do_sql($dbh,"ALTER DATABASE ".$DBNAME." CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
  36. print "Done\n";
  37. print "Stage3: Revert filed type to TEXT\n";
  38. for my $table (@db_tables) {
  39. my $sql = "select * from $table LIMIT 1";
  40. my $sth = $dbh->prepare( $sql );
  41. $sth->execute();
  42. print "\tStructure of $table \n\n";
  43. my $num_fields = $sth->{NUM_OF_FIELDS};
  44. for ( my $i=0; $i< $num_fields; $i++ ) {
  45. my $field = $sth->{NAME}->[$i];
  46. my $type = $sth->{TYPE}->[$i];
  47. my $precision = $sth->{PRECISION}->[$i];
  48. print "\t\tField: $field is of type: $type precision: $precision\n";
  49. if ($type == "-4" and $precision>262140) {
  50. print "\t\tMigrate field $field to type TEXT\n";
  51. do_sql($dbh,"ALTER TABLE `".$table."` MODIFY `".$field."` TEXT");
  52. }
  53. }
  54. $sth->finish();
  55. }
  56. print "Done!\n";
  57. exit;