Permalink
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 121 lines (96 sloc) 2.27 KB
#!/usr/bin/perl
use 5.22.0;
use warnings;
use experimental 'postderef';
use DBI;
use Getopt::Long;
my $sql;
my $formatter;
GetOptions (
'sql=s' => \$sql,
'formatter=s' => \$formatter,
) or die("Error in command line arguments\n");
use YAML::Syck 'Load', 'LoadFile';
my $config = LoadFile('./config.yaml');
my @facets = sort(($config->{'q'}{'post-facets'}||[])->@*);
my $dbh = DBI->connect('dbi:SQLite::memory:', {
RaiseError => 1,
});
$dbh->begin_work;
my $facets_sql = @facets
? join ",\n", '', @facets
: '';
$dbh->do(<<"SQL");
CREATE TABLE articles (
title,
date,
guid,
filename $facets_sql
)
SQL
$dbh->do(<<'SQL');
CREATE TABLE article_tag ( guid, tag )
SQL
$dbh->do(<<"SQL");
CREATE VIEW _ ( guid, title, date, filename, tag $facets_sql ) AS
SELECT a.guid, title, date, filename, tag
$facets_sql
FROM articles a
JOIN article_tag at ON a.guid = at.guid
SQL
$dbh->commit;
$dbh->begin_work;
my $qs = join ', ', map '?', qw(guid title date filename), @facets;
my $sth_a = $dbh->prepare(<<"SQL");
INSERT INTO articles (
guid, title, date, filename
$facets_sql
) VALUES ($qs)
SQL
my $sth_a_t = $dbh->prepare(<<'SQL');
INSERT INTO article_tag (guid, tag) VALUES (?, ?)
SQL
FILES:
for my $file (glob('content/pages/*.md'), glob('content/posts/*.md')) {
open my $fh, '<', $file
or die "could not open $file: $!";
my $cnt = 0;
my $yaml = "";
LINES:
while (<$fh>) {
$cnt ++ if $_ eq "---\n";
last LINES if $cnt > 1;
$yaml .= $_;
}
close $fh
or die "could not close $file: $!";
my $data;
local $@;
my $success = eval {
$data = Load($yaml);
$data->{tags} ||= [];
1;
};
unless ($success) {
warn "error processing $file: $@\n";
next FILES
}
$sth_a->execute(
$data->{guid}, $data->{title}, $data->{date}, $file,
map $data->{$_}, @facets
);
$sth_a_t->execute($data->{guid}, $_) for @{$data->{tags}};
}
$dbh->commit;
my $sth = $dbh->prepare($sql || die "pass some SQL yo\n");
$sth->execute(@ARGV);
my $func = eval <<'PERL'
sub {
no warnings 'uninitialized';
my %r = %{$_[0]};
PERL
. ($formatter || 'join "\t", map $r{$_}, sort keys %r') . "\n}";
die $@ if $@;
for my $row (@{$sth->fetchall_arrayref({})}) {
say $func->($row)
}