Trog-Data-SQLite.t 24 KB

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