Data.pm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package Trog::Data;
  2. use 5.040;
  3. use re '/aa';
  4. use Trog::Log qw{:all};
  5. #It's just a factory
  6. =head1 Trog::Data
  7. This is a data model factory.
  8. =head2 Trog::Data->new(Trog::Config) = $handle
  9. Returns a new Trog::Data::* class appropriate to what is configured in the Trog::Config object passed.
  10. Memoized: every call after the first returns the first handle, whatever it is passed.
  11. =cut
  12. sub new ( $class, $config ) {
  13. state $datamodule;
  14. return $datamodule if $datamodule;
  15. my $module = "Trog::Data::" . model($config);
  16. my $req = $module;
  17. $req =~ s/::/\//g;
  18. require "$req.pm";
  19. $datamodule = $module->new($config);
  20. return $datamodule;
  21. }
  22. =head2 model(Trog::Config) = STRING
  23. The data model to serve from: general.data_model, except on a site which never
  24. moved its posts across with bin/migrate.pl.
  25. SQLite is the shipped default, so a FlatFile site which never saved a
  26. data_model of its own, or which saved the default back, is configured for a
  27. database that does not exist. While data/posts.sqlite is missing and data/files
  28. holds posts, this answers FlatFile and warns, so the site keeps serving the
  29. posts it has. Once the migration has written the database, the configuration
  30. applies as written.
  31. =cut
  32. # FlatFile's datastore, named here because loading that model creates its tag
  33. # index, and this has to look before choosing. Trog::Data::FlatFile has its own.
  34. our $flatfile_store = 'data/files';
  35. sub model ($config) {
  36. my $model = $config->param('general.data_model');
  37. return $model unless $model eq 'SQLite';
  38. # Which that model only creates on first use.
  39. require Trog::Data::SQLite;
  40. no warnings 'once';
  41. my $sqlite_db = $Trog::Data::SQLite::dbname;
  42. return $model if -e $sqlite_db;
  43. opendir( my $dh, $flatfile_store ) or return $model;
  44. my $posts = grep { -f "$flatfile_store/$_" } readdir $dh; ## no critic (ProhibitFiletest_f) -- counting names, nothing is opened
  45. closedir $dh;
  46. return $model unless $posts;
  47. WARN("general.data_model is SQLite, but $sqlite_db does not exist and $flatfile_store holds $posts post(s). Serving them from FlatFile. Run bin/migrate.pl to move them across.");
  48. return 'FlatFile';
  49. }
  50. 1;