Trog-Data-SQLite.t 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. #!/usr/bin/env perl
  2. # Trog::Data::SQLite answers get() with SQL where Trog::DataModule::filter()
  3. # answers it with grep. The interesting question is not whether the SQL runs,
  4. # it is whether the two agree -- so most of this file writes one corpus into
  5. # both models and asserts they return the same posts for the same query.
  6. use 5.040;
  7. use re '/aasx';
  8. use warnings;
  9. use FindBin;
  10. use lib "$FindBin::Bin/../lib";
  11. use Test::More;
  12. use Test::MockModule qw{strict};
  13. use Test::Fatal qw{exception};
  14. our ( $REPO, $ROOT, $OLDCWD );
  15. BEGIN {
  16. require Cwd;
  17. require File::Copy;
  18. require File::Path;
  19. require File::Temp;
  20. $REPO = Cwd::abs_path("$FindBin::Bin/..");
  21. $OLDCWD = Cwd::getcwd();
  22. $ROOT = File::Temp::tempdir( 'tcms-datamodel-XXXXXX', TMPDIR => 1, CLEANUP => 1 );
  23. # Both models resolve their storage relative to cwd, and Text::Xslate reads
  24. # $HOME once at load time. Both have to be settled before anything loads.
  25. $ENV{HOME} = $ROOT;
  26. File::Path::make_path("$ROOT/$_") for qw{config schema data/files logs};
  27. File::Copy::copy( "$REPO/schema/$_", "$ROOT/schema/$_" ) or die $! for qw{flatfile.schema sqlite.schema};
  28. File::Copy::copy( "$REPO/config/default.cfg", "$ROOT/config/default.cfg" ) or die $!;
  29. chdir($ROOT) or die "could not chdir to the sandbox: $!";
  30. }
  31. END {
  32. chdir($OLDCWD) if $OLDCWD;
  33. }
  34. require_ok('Trog::Data::SQLite') or BAIL_OUT("Can't find SUT");
  35. require_ok('Trog::Data::FlatFile') or BAIL_OUT("Can't find the model to compare against");
  36. require Trog::Config;
  37. require Trog::SQLite::TagIndex;
  38. # _fixup() decorates every post with the author's display name and avatar class,
  39. # which would otherwise drag the auth database in. Not what is under test.
  40. my $auth = Test::MockModule->new('Trog::Auth');
  41. $auth->redefine( username2display => sub { return "Display $_[0]" } );
  42. $auth->redefine( username2classname => sub { return "class-$_[0]" } );
  43. my $conf = Trog::Config::get();
  44. my $sqlite = Trog::Data::SQLite->new($conf);
  45. my $flat = Trog::Data::FlatFile->new($conf);
  46. #--------------------------------------------------------------------------
  47. # One corpus, written to both.
  48. #--------------------------------------------------------------------------
  49. my $t = 1700000000;
  50. sub post {
  51. my (%o) = @_;
  52. return {
  53. title => 'Untitled',
  54. data => 'nothing in particular',
  55. user => 'bob',
  56. author => 'bob',
  57. visibility => 'public',
  58. created => $t++,
  59. version => 0,
  60. form => 'blog.tx',
  61. %o,
  62. # _process() pushes visibility into tags, so the corpus does too.
  63. tags => [ @{ $o{tags} // ['blog'] }, $o{visibility} // 'public' ],
  64. };
  65. }
  66. my @corpus = (
  67. post( id => 'p-public', title => 'The Quick Brown Fox', data => 'jumps over the lazy dog', tags => [qw{blog topbar}] ),
  68. post( id => 'p-private', title => 'Secret Plans', data => 'the mice will never know', visibility => 'private' ),
  69. post( id => 'p-unlisted', title => 'Unlisted Thing', data => 'findable but not listed', visibility => 'unlisted' ),
  70. post( id => 'p-ann', title => 'By Ann', data => 'ann wrote this one', user => 'ann', author => 'ann' ),
  71. post( id => 'p-micro', title => 'A Microblog', data => 'short and sweet', form => 'microblog.tx' ),
  72. post( id => 'p-series', title => 'A Series', data => 'holds other posts', form => 'series.tx', aclname => 'aseries', tags => [qw{series topbar}] ),
  73. post( id => 'p-slides', title => 'A Deck', data => [ 'slide one about foxes', 'slide two' ], form => 'presentation.tx' ),
  74. # What _process() leaves behind for a private post with an acl: the acl is
  75. # folded into tags and the acls field is deleted outright.
  76. post( id => 'p-acl', title => 'Members Only', data => 'for the club', visibility => 'private', tags => [qw{blog aseries}] ),
  77. );
  78. # A second version of one post, so that version handling is exercised.
  79. push( @corpus, post( id => 'p-public', title => 'The Quick Brown Fox (revised)', data => 'jumps over the lazy dog, again', tags => [qw{blog topbar}], version => 1, created => $t++ ) );
  80. foreach my $p (@corpus) {
  81. # Separate copies: FlatFile's index build decorates what it is handed.
  82. $sqlite->write( [ { %$p, tags => [ @{ $p->{tags} } ] } ] );
  83. $flat->write( [ { %$p, tags => [ @{ $p->{tags} } ] } ] );
  84. }
  85. # FlatFile snapshots the tag list at load time and filters queries against it in
  86. # place, so a tag it has not seen is deleted from the query rather than simply
  87. # unmatched. Refresh it, or the comparison measures that bug instead.
  88. {
  89. no warnings qw{once};
  90. @Trog::Data::FlatFile::tags = Trog::SQLite::TagIndex::tags();
  91. %Trog::Data::FlatFile::posts_by_tag = ();
  92. }
  93. sub ids_of {
  94. my (@posts) = @_;
  95. return [ sort map { "$_->{id}\@$_->{version}" } @posts ];
  96. }
  97. #--------------------------------------------------------------------------
  98. subtest 'the two models answer the same questions the same way' => sub {
  99. my @queries = (
  100. [ 'everything an admin can see' => { limit => 0, acls => ['admin'] } ],
  101. [ 'everything a visitor can see' => { limit => 0, acls => ['public'] } ],
  102. [ 'a visitor plus unlisted' => { limit => 0, acls => [qw{public unlisted}] } ],
  103. [ 'no acls at all' => { limit => 0, acls => [] } ],
  104. [ 'one tag' => { limit => 0, acls => ['admin'], tags => ['topbar'] } ],
  105. [ 'several tags' => { limit => 0, acls => ['admin'], tags => [qw{topbar series}] } ],
  106. [ 'a tag nothing has' => { limit => 0, acls => ['admin'], tags => ['nonesuch'] } ],
  107. [ 'excluding a tag' => { limit => 0, acls => ['admin'], exclude_tags => ['topbar'] } ],
  108. [ 'tags and exclude together' => { limit => 0, acls => ['admin'], tags => ['blog'], exclude_tags => ['topbar'] } ],
  109. [ 'by form' => { limit => 0, acls => ['admin'], form => 'microblog.tx' } ],
  110. [ 'by a form nothing has' => { limit => 0, acls => ['admin'], form => 'nonesuch.tx' } ],
  111. [ 'by author' => { limit => 0, acls => ['admin'], author => 'ann' } ],
  112. [ 'by id' => { limit => 0, acls => [qw{admin}], id => 'p-series' } ],
  113. [ 'by an id nothing has' => { limit => 0, acls => [qw{admin}], id => 'p-nonesuch' } ],
  114. [ 'by title' => { limit => 0, acls => [qw{admin}], title => 'A Deck' } ],
  115. [ 'by aclname' => { limit => 0, acls => [qw{admin}], aclname => 'aseries' } ],
  116. [ 'by acl membership' => { limit => 0, acls => ['aseries'] } ],
  117. [ 'a private id, as a visitor' => { limit => 0, acls => ['public'], id => 'p-private' } ],
  118. [ 'a private title, as a visitor' => { limit => 0, acls => ['public'], title => 'Members Only' } ],
  119. [ 'a private id, holding its acl' => { limit => 0, acls => ['aseries'], id => 'p-acl' } ],
  120. [ 'an unlisted id, as a visitor' => { limit => 0, acls => ['public'], id => 'p-unlisted' } ],
  121. [ 'an unlisted id, by its link' => { limit => 0, acls => [qw{public unlisted}], id => 'p-unlisted' } ],
  122. [ 'a public aclname, as a visitor' => { limit => 0, acls => ['public'], aclname => 'aseries' } ],
  123. [ 'an id with no acls at all' => { limit => 0, acls => [], id => 'p-public' } ],
  124. [ 'older than' => { limit => 0, acls => ['admin'], older => $corpus[4]{created} } ],
  125. [ 'newer than' => { limit => 0, acls => ['admin'], newer => $corpus[4]{created} } ],
  126. [ 'a specific version' => { limit => 0, acls => [qw{admin}], id => 'p-public', version => 0 } ],
  127. [ 'the other version' => { limit => 0, acls => [qw{admin}], id => 'p-public', version => 1 } ],
  128. );
  129. foreach my $case (@queries) {
  130. my ( $name, $query ) = @$case;
  131. my $want = ids_of( $flat->get(%$query) );
  132. my $got = ids_of( $sqlite->get(%$query) );
  133. is_deeply( $got, $want, $name ) or diag("flatfile: @$want\nsqlite: @$got");
  134. }
  135. };
  136. subtest 'both models paginate by offset' => sub {
  137. # Not compared page for page: the flat file model returns posts in readdir
  138. # order and this one by created, so which posts land on page two is allowed
  139. # to differ. What is not allowed to differ is that walking the pages visits
  140. # every post, exactly once -- which is the whole of what pagination promises.
  141. foreach my $case ( [ flatfile => $flat ], [ sqlite => $sqlite ] ) {
  142. my ( $name, $model ) = @$case;
  143. my @all = $model->get( limit => 0, acls => ['admin'] );
  144. my $limit = 3;
  145. my ( @walked, %seen );
  146. foreach my $page ( 1 .. 5 ) {
  147. my @got = $model->get( limit => $limit, page => $page, acls => ['admin'] );
  148. ok( scalar(@got) <= $limit, "$name: page $page holds no more than a page" );
  149. push( @walked, map { $_->{id} } @got );
  150. }
  151. is_deeply( [ sort @walked ], [ sort map { $_->{id} } @all ], "$name: the pages between them hold every post" );
  152. is( scalar( grep { $seen{$_}++ } @walked ), 0, "$name: and none of them twice" );
  153. }
  154. };
  155. subtest 'the id query really does return one post' => sub {
  156. # Guards the comparison above: two empty lists are also "the same".
  157. my @found = $sqlite->get( limit => 0, acls => [qw{admin}], id => 'p-series' );
  158. is( scalar(@found), 1, 'exactly one' );
  159. is( $found[0]{id}, 'p-series', 'and the right one' );
  160. is( $found[0]{form}, 'series.tx', 'decoded whole, not just its id' );
  161. my @admin = $sqlite->get( limit => 0, acls => ['admin'] );
  162. is( scalar(@admin), 8, 'an admin sees every post, each at one version' );
  163. # public, ann, micro, series and slides. Not the private one, not the
  164. # members-only one, and not the unlisted one -- unlisted is its own tag, and
  165. # a caller only holding 'public' does not hold it.
  166. my @public = $sqlite->get( limit => 0, acls => ['public'] );
  167. is( scalar(@public), 5, 'a visitor sees only what is tagged public' );
  168. my @plus = $sqlite->get( limit => 0, acls => [qw{public unlisted}] );
  169. is( scalar(@plus), 6, 'and the unlisted one once they hold that too' );
  170. };
  171. subtest 'a direct lookup still answers only to the acls' => sub {
  172. foreach my $case ( [ flatfile => $flat ], [ sqlite => $sqlite ] ) {
  173. my ( $name, $model ) = @$case;
  174. my $ids = sub {
  175. [ sort map { $_->{id} } $model->get( limit => 0, @_ ) ]
  176. };
  177. is_deeply( $ids->( acls => ['public'], id => 'p-private' ), [], "$name: a visitor cannot fetch a private post by id" );
  178. is_deeply( $ids->( acls => ['public'], title => 'Secret Plans' ), [], "$name: nor by title" );
  179. is_deeply( $ids->( acls => [], id => 'p-public' ), [], "$name: no acls fetch nothing, however public" );
  180. is_deeply( $ids->( acls => ['admin'], id => 'p-private' ), ['p-private'], "$name: an admin can" );
  181. is_deeply( $ids->( acls => ['public'], id => 'p-public' ), ['p-public'], "$name: a visitor still gets a public post" );
  182. is_deeply( $ids->( acls => ['aseries'], id => 'p-acl' ), ['p-acl'], "$name: and a member the post their acl names" );
  183. is_deeply( $ids->( acls => ['public'], id => 'p-unlisted' ), [], "$name: unlisted needs its own acl" );
  184. is_deeply( $ids->( acls => [qw{public unlisted}], id => 'p-unlisted' ), ['p-unlisted'], "$name: which a link to it carries" );
  185. }
  186. };
  187. subtest 'a caller who can see nothing is not queried for' => sub {
  188. my $mock = Test::MockModule->new('Trog::Data::SQLite');
  189. $mock->redefine( _dbh => sub { die "queried the database\n" } );
  190. is( exception { is_deeply( $sqlite->read( { limit => 0, acls => [] } ), [], 'no acls get nothing' ) }, undef, 'without asking the database' );
  191. is( exception { is_deeply( $sqlite->read( { limit => 0, acls => [], id => 'p-public' } ), [], 'nor by id' ) }, undef, 'nor for a direct lookup' );
  192. like( exception { $sqlite->read( { limit => 0, acls => ['public'] } ) }, qr/queried[ ]the[ ]database/, 'while a caller with acls is queried' );
  193. };
  194. subtest 'versions' => sub {
  195. my ($latest) = $sqlite->get( limit => 0, acls => [qw{admin}], id => 'p-public' );
  196. is( $latest->{version}, 1, 'the newest version is the one you get' );
  197. is( $latest->{title}, 'The Quick Brown Fox (revised)', 'with its own content' );
  198. is( $latest->{version_max}, 1, 'version_max is the newest' );
  199. is( $latest->{created}, $corpus[0]{created}, 'created is the post birthday, not the revision' );
  200. is( $latest->{modified}, $corpus[-1]{created}, 'modified is the revision' );
  201. my ($first) = $sqlite->get( limit => 0, acls => [qw{admin}], id => 'p-public', version => 0 );
  202. is( $first->{title}, 'The Quick Brown Fox', 'an older version can still be asked for' );
  203. is( $first->{version_max}, 1, 'and knows a newer one exists' );
  204. # raw is the history as stored, which is what bin/migrate.pl reads.
  205. my @raw = $sqlite->get( raw => 1, limit => 0 );
  206. is( scalar(@raw), 9, 'raw gets every version of everything' );
  207. ok( !exists $raw[0]{version_max}, 'and does not decorate them' );
  208. };
  209. subtest 'the like filter goes through FTS5' => sub {
  210. # The substring semantics filter() had, which is why the index is built with
  211. # the trigram tokenizer.
  212. my @cases = (
  213. [ 'quick' => ['p-public'] ],
  214. [ 'QUICK' => ['p-public'] ], # case insensitive
  215. [ 'own fox' => ['p-public'] ], # matches inside words
  216. [ 'lazy dog' => ['p-public'] ],
  217. [ 'Secret Plans' => ['p-private'] ], # title as well as body
  218. [ 'foxes' => ['p-slides'] ], # data stored as an array
  219. [ 'nonesuch' => [] ],
  220. );
  221. foreach my $case (@cases) {
  222. my ( $term, $want ) = @$case;
  223. my @got = map { $_->{id} } $sqlite->get( limit => 0, acls => ['admin'], like => $term );
  224. is_deeply( [ sort @got ], [ sort @$want ], "like '$term'" );
  225. }
  226. # FTS5 query syntax in the search box is text to search for, not syntax.
  227. foreach my $hostile ( 'AND', '"', 'foo OR bar', '*', 'NEAR(a b)', "it's" ) {
  228. is( exception { $sqlite->get( limit => 0, acls => ['admin'], like => $hostile ) }, undef, "'$hostile' is a search term, not a query" );
  229. }
  230. # Trigram cannot index below three characters, so those take the LIKE path.
  231. my @short = map { $_->{id} } $sqlite->get( limit => 0, acls => ['admin'], like => 'ox' );
  232. is_deeply( [ sort @short ], [ sort qw{p-public p-slides} ], 'a two character term still matches, via LIKE' );
  233. # And LIKE's own wildcards are literal there too.
  234. is_deeply( [ $sqlite->get( limit => 0, acls => ['admin'], like => '%' ) ], [], "'%' matches nothing rather than everything" );
  235. };
  236. subtest 'ordering and pagination' => sub {
  237. # By created, which after the version rollup is the post's birthday -- the
  238. # same field the caller gets back, and the same one older/newer filter on.
  239. my @all = $sqlite->get( limit => 0, acls => ['admin'] );
  240. my @created = map { $_->{created} } @all;
  241. is_deeply( \@created, [ reverse sort { $a <=> $b } @created ], 'newest first' );
  242. my @page1 = $sqlite->get( limit => 3, page => 1, acls => ['admin'] );
  243. my @page2 = $sqlite->get( limit => 3, page => 2, acls => ['admin'] );
  244. is( scalar(@page1), 3, 'a page is a page long' );
  245. is( scalar(@page2), 3, 'and so is the next one' );
  246. my %seen = map { $_->{id} => 1 } @page1;
  247. is( scalar( grep { $seen{ $_->{id} } } @page2 ), 0, 'and they do not overlap' );
  248. my @limited = $sqlite->get( limit => 2, acls => ['admin'] );
  249. is( scalar(@limited), 2, 'a limit with no page still limits' );
  250. };
  251. subtest 'count, tags and delete' => sub {
  252. is( $sqlite->count(), 8, 'count counts posts, not versions' );
  253. my @tags = $sqlite->tags();
  254. ok( scalar( grep { $_ eq 'topbar' } @tags ), 'tags lists a tag in use' );
  255. ok( scalar( grep { $_ eq 'aseries' } @tags ), 'including an acl folded into tags' );
  256. ok( !scalar( grep { $_ eq 'nonesuch' } @tags ), 'and nothing else' );
  257. $sqlite->delete( { id => 'p-micro' } );
  258. is( $sqlite->count(), 7, 'delete removes the post' );
  259. # The version bookkeeping has to let go of it too, or the next post to
  260. # reuse that id inherits a pointer to a row that is gone.
  261. my $vdbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  262. my ($stale) = $vdbh->selectrow_array(q{SELECT COUNT(*) FROM post_versions WHERE uuid = 'p-micro'});
  263. is( $stale, 0, 'and its version bookkeeping' );
  264. is_deeply( [ $sqlite->get( limit => 0, acls => [qw{admin}], id => 'p-micro' ) ], [], 'and it cannot be fetched' );
  265. # The schema's triggers own this, not the Perl.
  266. my $dbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  267. my ($orphans) = $dbh->selectrow_array('SELECT COUNT(*) FROM post_tags WHERE post_id NOT IN (SELECT id FROM posts)');
  268. is( $orphans, 0, 'the tag index went with it' );
  269. my ($ghosts) = $dbh->selectrow_array(q{SELECT COUNT(*) FROM posts_fts WHERE posts_fts MATCH '"short and sweet"'});
  270. is( $ghosts, 0, 'and so did the search index' );
  271. };
  272. subtest 'writing' => sub {
  273. my $before = $sqlite->count();
  274. $sqlite->write( [ post( id => 'p-new', title => 'Brand New' ) ] );
  275. is( $sqlite->count(), $before + 1, 'a new post lands' );
  276. # (uuid, version) is unique, which is what stops two workers writing the
  277. # same version rather than one of them silently winning.
  278. # DBI's PrintError would announce the constraint failure on stderr as well,
  279. # and we are provoking it on purpose.
  280. my $clash = do {
  281. local $SIG{__WARN__} = sub { };
  282. exception { $sqlite->write( [ post( id => 'p-new', title => 'Clashing' ) ] ) };
  283. };
  284. like( $clash, qr/Could[ ]not[ ]write[ ]post[ ]'p-new'/, 'the same version twice is refused, loudly' );
  285. is( exception { $sqlite->write( [ post( id => 'p-new', title => 'Second Version', version => 1 ) ] ) }, undef, 'a new version is not' );
  286. my ($now) = $sqlite->get( limit => 0, acls => [qw{admin}], id => 'p-new' );
  287. is( $now->{title}, 'Second Version', 'and wins' );
  288. like( exception { $sqlite->write( [ { title => 'No Id' } ] ) }, qr/no[ ]id/i, 'a post with no id is refused' );
  289. my $count = $sqlite->count();
  290. ok( exception { $sqlite->write( [ post( id => 'p-half', title => 'Half' ), { title => 'No Id' } ] ) }, 'a batch with a post it refuses is refused' );
  291. is( $sqlite->count(), $count, 'and none of the batch lands' );
  292. # These are computed per query out of the version history; storing them
  293. # would bake one query's answer into the post forever.
  294. my $dbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  295. my ($blob) = $dbh->selectrow_array("SELECT post_data FROM posts WHERE uuid='p-new' AND version=1");
  296. unlike( $blob, qr/version_max|"modified"|display_name|user_class/, 'derived fields are not stored' );
  297. };
  298. subtest 'tags a post might really have' => sub {
  299. my $dbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  300. my $tags_of = sub {
  301. my ($id) = @_;
  302. my $rows = $dbh->selectall_arrayref(
  303. 'SELECT tag FROM post_tags t JOIN posts p ON p.id = t.post_id WHERE p.uuid = ? ORDER BY tag',
  304. { Slice => {} }, $id
  305. );
  306. return [ map { $_->{tag} } @$rows ];
  307. };
  308. # A post is storable whatever its tags look like. Refusing one is refusing
  309. # to store the post, which is never the right answer for an index.
  310. my %shapes = (
  311. 'p-tag-missing' => undef,
  312. 'p-tag-null' => undef,
  313. 'p-tag-empty' => [],
  314. 'p-tag-normal' => [qw{blog public}],
  315. 'p-tag-holed' => [ 'public', undef ],
  316. 'p-tag-numeric' => [ 1, 2 ],
  317. );
  318. foreach my $id ( sort keys %shapes ) {
  319. my $post = post( id => $id );
  320. if ( $id eq 'p-tag-missing' ) { delete $post->{tags} }
  321. else { $post->{tags} = $shapes{$id} }
  322. is( exception { $sqlite->write( [$post] ) }, undef, "a post with $id tags is storable" );
  323. }
  324. # The one that actually bit: Trog::DataModule::_process() pushed a post's
  325. # visibility into its tags without defaulting it first, so posts written
  326. # before that carry a null there, and a whole site's migration fell over on
  327. # the NOT NULL constraint rather than on anything wrong with the post.
  328. is_deeply( $tags_of->('p-tag-holed'), ['public'], 'a null in the array is left out of the index' );
  329. is_deeply( $tags_of->('p-tag-normal'), [qw{blog public}], 'and a normal one is indexed whole' );
  330. is_deeply( $tags_of->('p-tag-empty'), [], 'an empty list indexes nothing' );
  331. is_deeply( $tags_of->('p-tag-null'), [], 'and neither does a null tags field' );
  332. is_deeply( $tags_of->('p-tag-missing'), [], 'nor no tags field at all' );
  333. # A null tag matched nothing in the flat file model either, so leaving it
  334. # out of the index changes no answer.
  335. my @found = $sqlite->get( limit => 0, acls => ['public'], tags => ['public'] );
  336. ok( scalar( grep { $_->{id} eq 'p-tag-holed' } @found ), 'the post is still found by the tag it does have' );
  337. };
  338. subtest 'the triggers can be fixed after the fact' => sub {
  339. # Every trigger is dropped and recreated when the schema is applied, rather
  340. # than created IF NOT EXISTS. With IF NOT EXISTS a database that already
  341. # had one kept its old copy for good, so fixing a trigger would have fixed
  342. # it only for sites that had not run yet -- which is no use at all, since
  343. # the site that needs the fix is by definition one that has.
  344. my $dbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  345. $dbh->do('DROP TRIGGER posts_tags_insert');
  346. $dbh->do( 'CREATE TRIGGER posts_tags_insert AFTER INSERT ON posts BEGIN INSERT INTO post_tags (post_id, tag) VALUES (new.id, %s); END;' =~ s/%s/'wrong'/r );
  347. # What a worker starting up does.
  348. Trog::Data::SQLite::_dbh();
  349. my $schema = File::Slurper::read_text('schema/sqlite.schema');
  350. $dbh->{sqlite_allow_multiple_statements} = 1;
  351. $dbh->do($schema);
  352. $dbh->{sqlite_allow_multiple_statements} = 0;
  353. # post() appends the visibility to the tags, so this one carries both.
  354. $sqlite->write( [ post( id => 'p-after-fix', tags => ['afterfix'] ) ] );
  355. my $rows = $dbh->selectall_arrayref(
  356. 'SELECT tag FROM post_tags t JOIN posts p ON p.id = t.post_id WHERE p.uuid = ? ORDER BY tag',
  357. { Slice => {} }, 'p-after-fix'
  358. );
  359. is_deeply( [ map { $_->{tag} } @$rows ], [qw{afterfix public}], 'reapplying the schema replaces a stale trigger' );
  360. unlike( join( ',', map { $_->{tag} } @$rows ), qr/wrong/, 'and the stale one stops firing' );
  361. };
  362. subtest 'indexing a custom field' => sub {
  363. # index_fields() logs what it did, and with no logger configured that comes
  364. # out on stderr with a Carp::Always trace behind it.
  365. local $SIG{__WARN__} = sub { };
  366. my $dbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  367. # xinfo, because table_info does not list generated columns.
  368. my $columns = sub {
  369. return { map { $_->{name} => 1 } @{ $dbh->selectall_arrayref( 'PRAGMA table_xinfo(posts)', { Slice => {} } ) } };
  370. };
  371. my $indexes = sub {
  372. return { map { $_->{name} => 1 } @{ $dbh->selectall_arrayref( "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='posts'", { Slice => {} } ) } };
  373. };
  374. ok( !$columns->()->{cook_time}, 'the field has no column to start with' );
  375. $sqlite->index_fields(qw{cook_time});
  376. ok( $columns->()->{cook_time}, 'indexing a field gives it a column' );
  377. ok( $indexes->()->{'posts_custom_cook_time'}, 'and an index' );
  378. # The column is generated out of the blob, so it is populated for posts that
  379. # were written long before anybody asked for it.
  380. $sqlite->write( [ post( id => 'p-recipe', title => 'Soup', cook_time => '45 minutes' ) ] );
  381. my ($value) = $dbh->selectrow_array(q{SELECT cook_time FROM posts WHERE uuid = 'p-recipe'});
  382. is( $value, '45 minutes', 'and the column reads the value straight out of the post' );
  383. # And SQLite actually uses it, which is the entire point.
  384. my ($plan) = map { $_->{detail} } @{ $dbh->selectall_arrayref( q{EXPLAIN QUERY PLAN SELECT id FROM posts WHERE cook_time = '45 minutes'}, { Slice => {} } ) };
  385. like( $plan, qr/USING[ ]INDEX[ ]posts_custom_cook_time/, 'and searches it rather than every post' );
  386. is( exception { $sqlite->index_fields(qw{cook_time}) }, undef, 'asking twice is not an error' );
  387. # Reconciling against a set that no longer names it.
  388. $sqlite->index_fields(qw{serves});
  389. ok( !$indexes->()->{'posts_custom_cook_time'}, 'a field left out loses its index' );
  390. ok( $columns->()->{cook_time}, 'but keeps its column, which costs nothing' );
  391. ok( $indexes->()->{'posts_custom_serves'}, 'and the newly named one gains an index' );
  392. # Only ever ours.
  393. $sqlite->index_fields();
  394. ok( $indexes->()->{posts_created}, "the schema's own indexes are left alone" );
  395. ok( $indexes->()->{posts_title}, 'all of them' );
  396. # The name reaches SQLite as an identifier and a JSON path, neither of which
  397. # can be bound as a parameter, so it is checked here and not merely upstream.
  398. foreach my $hostile ( 'cook_time; DROP TABLE posts', "cook'time", 'Cook_Time', '1st_course', 'a' x 40, '', 'post_data' ) {
  399. is( exception { $sqlite->index_fields($hostile) }, undef, "'$hostile' is refused rather than run" );
  400. }
  401. ok( $indexes->()->{posts_created}, 'and the table is still there afterwards' );
  402. ok( !$indexes->()->{'posts_custom_post_data'}, 'and a schema column did not pick up an index of its own' );
  403. };
  404. # Last, so the post it adds changes no count asserted above.
  405. subtest 'aliases' => sub {
  406. my $aliased = post(
  407. id => 'p-aliased',
  408. title => 'Many Names',
  409. local_href => '/posts/p-aliased',
  410. method => 'GET',
  411. callback => 'Trog::Routes::HTML::posts',
  412. aliases => [qw{/one /two /three}],
  413. );
  414. $sqlite->write( [ { %$aliased, tags => [ @{ $aliased->{tags} } ] } ] );
  415. $flat->write( [ { %$aliased, tags => [ @{ $aliased->{tags} } ] } ] );
  416. my %want = map { $_ => '/posts/p-aliased' } qw{/one /two /three};
  417. foreach my $case ( [ flatfile => $flat ], [ sqlite => $sqlite ] ) {
  418. my ( $name, $model ) = @$case;
  419. my %got = $model->aliases();
  420. is_deeply( { map { $_ => $got{$_} } grep { exists $want{$_} } keys %got }, \%want, "$name: every alias of a post leads to it, not only the first" );
  421. }
  422. };
  423. done_testing();