# -*- cperl -*-
package RssC::DB;
use strict;
use warnings;
use DBI;
use constant CURRENT_SCHEMA_VER => 0;
use constant MINIMUM_SCHEMA_VER => 0;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(&DB);
my $DB;

sub DB () {
    if ($DB) {
	$DB->{dbh};
    }
    else {
	$DB = __PACKAGE__->_new;
	$DB->{dbh};
    }
}

sub _new {
    my $class = shift;
    my $this = bless {} => $class;

    $this->{dbh} = DBI->connect(
	'dbi:SQLite:dbname=rssc.db',
	'', '', {
	    RaiseError => 1,
	    AutoCommit => 1,
	});
    
    if (!$this->{dbh}) {
	die "Failed to open SQLite3 database rssc.db";
    }

    $this->_setup_db;
    $this;
}

sub _setup_db {
    my $this = shift;

    eval {
	$this->{dbh}->do('SELECT * FROM schema_ver LIMIT 0');
    };
    if ($@) {
	# DBが空。
	$this->{dbh}->do(q{
CREATE TABLE schema_ver (
    current INTEGER,
    minimum INTEGER
)});

	$this->{dbh}->do(q{
            INSERT INTO schema_ver
                   (current, minimum)
            VALUES (?      , ?      )
        }, undef, CURRENT_SCHEMA_VER, MINIMUM_SCHEMA_VER);

	$this->{dbh}->do(q{
CREATE TABLE uri (
    uri_id INTEGER PRIMARY KEY,
    uri    VARCHAR(255),

    UNIQUE (uri)
)});

	$this->{dbh}->do(q{
CREATE TABLE title (
    uri_id INTEGER,
    title  BLOB,

    UNIQUE (uri_id)
)});

	$this->{dbh}->do(q{
CREATE TABLE user_title (
    uri_id     INTEGER,
    user_title BLOB,

    UNIQUE (uri_id)
)});

	$this->{dbh}->do(q{
CREATE TABLE md5 (
    uri_id  INTEGER,
    md5     CHAR(32),

    UNIQUE (uri_id)
)});

	$this->{dbh}->do(q{
CREATE TABLE last_modified (
    uri_id  INTEGER,
    lastmod INTEGER,

    UNIQUE (uri_id)
)});
	
    }
    else {
	my $row = $this->{dbh}->selectrow_hashref(q{
            SELECT *
              FROM schema_ver
             LIMIT 1
        });
	if (CURRENT_SCHEMA_VER < $row->{minimum}) {
	    die sprintf(
		"DB Version Mismatch:\n".
		" - DB minimum  : %d\n".
		" - DB current  : %d\n".
		" - Code current: %d\n",
		@$row{qw(minimum current)}, CURRENT_SCHEMA_VER);
	}
    }
}

1;
