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

use strict;

sub new {
  my $self = {};
  bless($self, shift);
  $self->_init(@_);
  return $self;
}

#
# Required parameters: 'name', 'user', 'password'.
# Optional parameters:
#  'host' - database host name, if remote. If not specified, local UNIX-socket will be used.
#  'port' - database port
#
# Additional parameters are defined in subclasses.
#

sub _init {
  my ($self, %params) = @_;

  $self->{name} = $params{name};
  $self->{user} = $params{user};
  $self->{password} = $params{password};
  $self->{host} = $params{host} if defined $params{host};
  $self->{port} = $params{port} if defined $params{port};
}

sub description {
  my ($self) = @_;

  my $s = "db $self->{name}, user $self->{user}, ";
  if (defined $self->{host}) {
    $s .= "host $self->{host}";
  } else {
    $s .= "local socket";
  }
  return $s;
}

#
# Subclass must override this function.
# Return value: 0 - error, <> 0 - success.
# errstr must be set on error.
#
sub connect {
  die "Pure virtual function call";
}

sub disconnect {
  die "Pure virtual function call";
}

sub execute {
  die "Pure virtual function call";
}

sub errstr {
  my ($self) = @_;

  return $self->{errstr};
}

sub _set_errstr {
  my ($self, $errstr, $errcode) = @_;
  $self->{errstr} = $errstr;
  $self->{errcode} = $errcode;
}

sub errcode {
  my ($self) = @_;

  return $self->{errcode};
}

sub quote {
  my ($self, $sql) = @_;
  $sql =~ s/'/''/g;
  return "'$sql'";
}

1;
