Serge

 view release on metacpan or  search on metacpan

lib/Serge/DB.pm  view on Meta::CPAN

package Serge::DB;

use strict;

no warnings qw(uninitialized);

use DBI;
use Digest::MD5 qw(md5);
use Encode qw(encode_utf8);
use File::Basename;
use utf8;

our $DEBUG = $ENV{CI} ne ''; # use debug mode from under CI environment to ensure better coverage

my $DBD_PARAMS = {
    'SQLite' => {
        'options' => {
            'sqlite_unicode' => 1,
        },
        'do' => 'PRAGMA cache_size = 10000', # 10 MB of cache instead of default 2 MB
        'begin_transaction_stmt' => 'BEGIN',
    },

    'SQLite_pre_1_26_06' => {
        'options' => {
            'unicode' => 1, # old version of DBD::SQLite used 'unicode' instead of 'sqlite_unicode'
        },
        'do' => 'PRAGMA cache_size = 10000', # 10 MB of cache instead of default 2 MB
        'begin_transaction_stmt' => 'BEGIN',
    },

    'mysql' => {
        'options' => {
            'mysql_enable_utf8' => 1,
            'mysql_bind_type_guessing' => 1,
        },
        'begin_transaction_stmt' => 'START TRANSACTION',
    },

    'Pg' => { # Postgres
        'options' => {
            'pg_enable_utf8' => 1,
        },
        'begin_transaction_stmt' => 'BEGIN',
    }
};

#
# Initialize object
#
sub new {
    my ($class) = @_;

    my $self = {
        dbh => undef,
        prepare_cache => {},
        transaction_opened => undef,
        dsn => {},
    };

    bless $self, $class;
    return $self;
}

sub open {
    my ($self, $source, $username, $password) = @_;

    $self->close if $self->{dbh}; # close previous connection

    if ($ENV{SERGE_NO_TRANSACTIONS}) {
        print "SERGE_NO_TRANSACTIONS is ON\n" if $DEBUG;
    }

    if ($source =~ m/^DBI:(.*?):/) {
        my $type = $1;
        my $schema_filename = dirname(__FILE__).'/'.lc($type).'_schema.sql';

        if ($type eq 'SQLite') {
            eval('use DBD::SQLite 1.26_06');
            $type = 'SQLite_pre_1_26_06' if $@;
        }

        # expand '~/' in file path to the value of $ENV{HOME}
        # See https://github.com/evernote/serge/issues/1
        $source =~ s!^(DBI:SQLite:dbname=)~/(.*)$!$1.$ENV{HOME}.'/'.$2!se;

        if (exists $DBD_PARAMS->{$type}) {
            $self->{params} = $DBD_PARAMS->{$type};

            $self->{dbh} = DBI->connect(
                $source, $username, $password,
                $self->{params}->{options}
            ) or die "Can't connect to the database [$source]: $!\n";



( run in 1.279 second using v1.01-cache-2.11-cpan-6aa56a78535 )