Trog-Data-SQLite.t 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 'the id query really does return one post' => sub {
  129. # Guards the comparison above: two empty lists are also "the same".
  130. my @found = $sqlite->get( limit => 0, id => 'p-series' );
  131. is( scalar(@found), 1, 'exactly one' );
  132. is( $found[0]{id}, 'p-series', 'and the right one' );
  133. is( $found[0]{form}, 'series.tx', 'decoded whole, not just its id' );
  134. my @admin = $sqlite->get( limit => 0, acls => ['admin'] );
  135. is( scalar(@admin), 8, 'an admin sees every post, each at one version' );
  136. # public, ann, micro, series and slides. Not the private one, not the
  137. # members-only one, and not the unlisted one -- unlisted is its own tag, and
  138. # a caller only holding 'public' does not hold it.
  139. my @public = $sqlite->get( limit => 0, acls => ['public'] );
  140. is( scalar(@public), 5, 'a visitor sees only what is tagged public' );
  141. my @plus = $sqlite->get( limit => 0, acls => [qw{public unlisted}] );
  142. is( scalar(@plus), 6, 'and the unlisted one once they hold that too' );
  143. };
  144. subtest 'versions' => sub {
  145. my ($latest) = $sqlite->get( limit => 0, id => 'p-public' );
  146. is( $latest->{version}, 1, 'the newest version is the one you get' );
  147. is( $latest->{title}, 'The Quick Brown Fox (revised)', 'with its own content' );
  148. is( $latest->{version_max}, 1, 'version_max is the newest' );
  149. is( $latest->{created}, $corpus[0]{created}, 'created is the post birthday, not the revision' );
  150. is( $latest->{modified}, $corpus[-1]{created}, 'modified is the revision' );
  151. my ($first) = $sqlite->get( limit => 0, id => 'p-public', version => 0 );
  152. is( $first->{title}, 'The Quick Brown Fox', 'an older version can still be asked for' );
  153. is( $first->{version_max}, 1, 'and knows a newer one exists' );
  154. # raw is the history as stored, which is what bin/migrate*.pl reads.
  155. my @raw = $sqlite->get( raw => 1, limit => 0 );
  156. is( scalar(@raw), 9, 'raw gets every version of everything' );
  157. ok( !exists $raw[0]{version_max}, 'and does not decorate them' );
  158. };
  159. subtest 'the like filter goes through FTS5' => sub {
  160. # The substring semantics filter() had, which is why the index is built with
  161. # the trigram tokenizer.
  162. my @cases = (
  163. [ 'quick' => ['p-public'] ],
  164. [ 'QUICK' => ['p-public'] ], # case insensitive
  165. [ 'own fox' => ['p-public'] ], # matches inside words
  166. [ 'lazy dog' => ['p-public'] ],
  167. [ 'Secret Plans' => ['p-private'] ], # title as well as body
  168. [ 'foxes' => ['p-slides'] ], # data stored as an array
  169. [ 'nonesuch' => [] ],
  170. );
  171. foreach my $case (@cases) {
  172. my ( $term, $want ) = @$case;
  173. my @got = map { $_->{id} } $sqlite->get( limit => 0, acls => ['admin'], like => $term );
  174. is_deeply( [ sort @got ], [ sort @$want ], "like '$term'" );
  175. }
  176. # FTS5 query syntax in the search box is text to search for, not syntax.
  177. foreach my $hostile ( 'AND', '"', 'foo OR bar', '*', 'NEAR(a b)', "it's" ) {
  178. is( exception { $sqlite->get( limit => 0, acls => ['admin'], like => $hostile ) }, undef, "'$hostile' is a search term, not a query" );
  179. }
  180. # Trigram cannot index below three characters, so those take the LIKE path.
  181. my @short = map { $_->{id} } $sqlite->get( limit => 0, acls => ['admin'], like => 'ox' );
  182. is_deeply( [ sort @short ], [ sort qw{p-public p-slides} ], 'a two character term still matches, via LIKE' );
  183. # And LIKE's own wildcards are literal there too.
  184. is_deeply( [ $sqlite->get( limit => 0, acls => ['admin'], like => '%' ) ], [], "'%' matches nothing rather than everything" );
  185. };
  186. subtest 'ordering and pagination' => sub {
  187. # By created, which after the version rollup is the post's birthday -- the
  188. # same field the caller gets back, and the same one older/newer filter on.
  189. my @all = $sqlite->get( limit => 0, acls => ['admin'] );
  190. my @created = map { $_->{created} } @all;
  191. is_deeply( \@created, [ reverse sort { $a <=> $b } @created ], 'newest first' );
  192. my @page1 = $sqlite->get( limit => 3, page => 1, acls => ['admin'] );
  193. my @page2 = $sqlite->get( limit => 3, page => 2, acls => ['admin'] );
  194. is( scalar(@page1), 3, 'a page is a page long' );
  195. is( scalar(@page2), 3, 'and so is the next one' );
  196. my %seen = map { $_->{id} => 1 } @page1;
  197. is( scalar( grep { $seen{ $_->{id} } } @page2 ), 0, 'and they do not overlap' );
  198. my @limited = $sqlite->get( limit => 2, acls => ['admin'] );
  199. is( scalar(@limited), 2, 'a limit with no page still limits' );
  200. };
  201. subtest 'count, tags and delete' => sub {
  202. is( $sqlite->count(), 8, 'count counts posts, not versions' );
  203. my @tags = $sqlite->tags();
  204. ok( scalar( grep { $_ eq 'topbar' } @tags ), 'tags lists a tag in use' );
  205. ok( scalar( grep { $_ eq 'aseries' } @tags ), 'including an acl folded into tags' );
  206. ok( !scalar( grep { $_ eq 'nonesuch' } @tags ), 'and nothing else' );
  207. $sqlite->delete( { id => 'p-micro' } );
  208. is( $sqlite->count(), 7, 'delete removes the post' );
  209. # The version bookkeeping has to let go of it too, or the next post to
  210. # reuse that id inherits a pointer to a row that is gone.
  211. my $vdbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  212. my ($stale) = $vdbh->selectrow_array(q{SELECT COUNT(*) FROM post_versions WHERE uuid = 'p-micro'});
  213. is( $stale, 0, 'and its version bookkeeping' );
  214. is_deeply( [ $sqlite->get( limit => 0, id => 'p-micro' ) ], [], 'and it cannot be fetched' );
  215. # The schema's triggers own this, not the Perl.
  216. my $dbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  217. my ($orphans) = $dbh->selectrow_array('SELECT COUNT(*) FROM post_tags WHERE post_id NOT IN (SELECT id FROM posts)');
  218. is( $orphans, 0, 'the tag index went with it' );
  219. my ($ghosts) = $dbh->selectrow_array(q{SELECT COUNT(*) FROM posts_fts WHERE posts_fts MATCH '"short and sweet"'});
  220. is( $ghosts, 0, 'and so did the search index' );
  221. };
  222. subtest 'writing' => sub {
  223. my $before = $sqlite->count();
  224. $sqlite->write( [ post( id => 'p-new', title => 'Brand New' ) ] );
  225. is( $sqlite->count(), $before + 1, 'a new post lands' );
  226. # (uuid, version) is unique, which is what stops two workers writing the
  227. # same version rather than one of them silently winning.
  228. # DBI's PrintError would announce the constraint failure on stderr as well,
  229. # and we are provoking it on purpose.
  230. my $clash = do {
  231. local $SIG{__WARN__} = sub { };
  232. exception { $sqlite->write( [ post( id => 'p-new', title => 'Clashing' ) ] ) };
  233. };
  234. like( $clash, qr/Could not write post 'p-new'/, 'the same version twice is refused, loudly' );
  235. is( exception { $sqlite->write( [ post( id => 'p-new', title => 'Second Version', version => 1 ) ] ) }, undef, 'a new version is not' );
  236. my ($now) = $sqlite->get( limit => 0, id => 'p-new' );
  237. is( $now->{title}, 'Second Version', 'and wins' );
  238. like( exception { $sqlite->write( [ { title => 'No Id' } ] ) }, qr/no id/i, 'a post with no id is refused' );
  239. # These are computed per query out of the version history; storing them
  240. # would bake one query's answer into the post forever.
  241. my $dbh = Trog::SQLite::dbh( undef, 'data/posts.sqlite' );
  242. my ($blob) = $dbh->selectrow_array("SELECT post_data FROM posts WHERE uuid='p-new' AND version=1");
  243. unlike( $blob, qr/version_max|"modified"|display_name|user_class/, 'derived fields are not stored' );
  244. };
  245. done_testing();