App-Zapzi

 view release on metacpan or  search on metacpan

lib/App/Zapzi/Database.pm  view on Meta::CPAN

package App::Zapzi::Database;
# ABSTRACT: database access for Zapzi


use utf8;
use strict;
use warnings;

our $VERSION = '0.017'; # VERSION

use Moo;
use SQL::Translator;
use App::Zapzi::Database::Schema;
use App::Zapzi::Config;


has app => (is => 'ro');


sub database_file
{
    my $self = shift;
    if ($self->app->test_database)
    {
        return ':memory:';
    }
    else
    {
        return $self->app->zapzi_dir . "/zapzi.db";
    }
}


sub dsn
{
    my $self = shift;
    return "dbi:SQLite:dbname=" . $self->database_file;
}

our $_schema;


sub schema
{
    my $self = shift;
    $_schema //= App::Zapzi::Database::Schema->connect({
        dsn =>$self->dsn,
        sqlite_unicode => 1,
        on_connect_do => 'PRAGMA foreign_keys = ON'});
    return $_schema;
}


sub init
{
    my $self = shift;
    my ($ddl) = @_;

    mkdir $self->app->zapzi_dir;
    die "Can't access ", $self->app->zapzi_dir
        if ! -d $self->app->zapzi_dir;
    mkdir $self->app->zapzi_ebook_dir;

    $self->schema->storage->disconnect if $self->app->force;
    unlink $self->database_file unless $self->app->test_database;
    $_schema = undef;

    # Adjust the page size to match the expected blob size for articles
    # http://www.sqlite.org/intern-v-extern-blob.html
    $self->schema->storage->dbh->do("PRAGMA page_size = 8192");

    if (defined($ddl))
    {
        # Create a special version of the database from the supplied DDL
        # Used for testing upgrades
        my @commands = split(/;\n/, $ddl);
        for (@commands)
        {
            $self->schema->storage->dbh->do($_);
        }

        return;
    }

    $self->schema->deploy();

    my @folders = ({id => 100, name => 'Inbox'},
                   {name => 'Archive'});
    $self->schema->populate('Folder', \@folders);

    my @articles = ({title => 'Welcome to Zapzi', folder => 100,
                     article_text =>
                         { text => '<p>Welcome to Zapzi! Please run <pre>zapzi -h</pre> to see documentation.</p>'}});
    scalar $self->schema->populate('Article', \@articles);

    my @config = ({name => 'schema_version',
                   value => $self->schema->schema_version} );
    $self->schema->populate('Config', \@config);
}


sub get_version
{
    my $self = shift;
    my $schema = $self->schema;

    my $version;



( run in 0.799 second using v1.01-cache-2.11-cpan-63c85eba8c4 )