-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathq
executable file
·120 lines (96 loc) · 2.27 KB
/
q
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/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)
}