# Copyright 1999-2016. Parallels IP Holdings GmbH. All Rights Reserved.
package Db::MysqlUtils;

use strict;

sub doesSupportCharacterSets {
  my ($conn) = @_;

  my $support;
  if ($conn->execute("SHOW VARIABLES LIKE \"character_set_results\"")) {
    $support = $conn->fetchrow();
  }
  $conn->finish();
  return $support;
}

sub getDatabaseCharacterSet{
  my ($conn) = @_;

  my $charset;
  if ($conn->execute("SHOW VARIABLES LIKE \"character_set_database\"")) {
    my $ptrRow = $conn->fetchrow();
    $charset = $ptrRow->[1];
  }
  $conn->finish();
  return $charset;
}

sub getCollations{
  my ($conn) = @_;

  my %res;

  if ($conn->execute("SHOW COLLATION")) {
    while (my $row = $conn->fetchhash()) {
      $res{$row->{'Collation'}} = $row->{'Charset'};
    }
  }
  $conn->finish();

  return %res;
}

sub getTablesCollation{
  my ($conn) = @_;

  my %res;

  if ($conn->execute("SHOW TABLE STATUS")) {
    while (my $row = $conn->fetchhash()) {
      $res{$row->{'Name'}} = $row->{'Collation'};
    }
  }
  $conn->finish();

  return %res;
}

sub getColumnsCollation{
  my ($conn, $table) = @_;

  my %res;

  if ($conn->execute("SHOW FULL COLUMNS IN `$table`")) {
    while (my $row = $conn->fetchhash()) {
      $res{$row->{'Name'}} = $row->{'Collation'} if defined $row->{'Collation'};
    }
  }
  $conn->finish();

  return %res;
}

sub getCharacterSetsSupportSql {
  return "SET character_set_results = 'utf8', character_set_server = 'utf8', character_set_connection = 'utf8', character_set_client = 'utf8'";
}

sub getNamesCharacterSetsSupportSql {
  return "SET NAMES utf8";
}

sub getVersion {
  my $mysql = AgentConfig::mysqlBin();
  my $version = `$mysql --version`;
  if ($version and $version =~ /Distrib (\d+\.\d+)\./){
    return $1;
  }
}

sub getVersionArray {
  my $mysql = AgentConfig::mysqlBin();
  my $version = `$mysql --version`;
  if ($version and $version =~ /Distrib (\d+)\.(\d+)(?:\.(\d+))?/){
    return ($1, $2, $3);
  }
}

1;