33c40ed86170ebbbb4e263594964df82c760bd45
[scpubgit/stemmatology.git] / lib / Text / Tradition / Directory.pm
1 package Text::Tradition::Directory;
2
3 use strict;
4 use warnings;
5 use Moose;
6 use DBI;
7 use Encode qw/ decode_utf8 /;
8 use KiokuDB::GC::Naive;
9 use KiokuDB::TypeMap;
10 use KiokuDB::TypeMap::Entry::Naive;
11 use Text::Tradition::Error;
12
13 extends 'KiokuX::Model';
14
15 =head1 NAME
16
17 Text::Tradition::Directory - a KiokuDB interface for storing and retrieving traditions
18
19 =head1 SYNOPSIS
20
21   use Text::Tradition::Directory;
22   my $d = Text::Tradition::Directory->new( 
23     'dsn' => 'dbi:SQLite:mytraditions.db',
24     'extra_args' => { 'create' => 1 },
25   );
26   
27   my $tradition = Text::Tradition->new( @args );
28   my $stemma = $tradition->add_stemma( dotfile => $dotfile ); 
29   $d->save_tradition( $tradition );
30   
31   foreach my $id ( $d->traditions ) {
32         print $d->tradition( $id )->name;
33   }
34     
35 =head1 DESCRIPTION
36
37 Text::Tradition::Directory is an interface for storing and retrieving text traditions and all their data, including an associated stemma hypothesis.  It is an instantiation of a KiokuDB::Model, storing traditions and associated stemmas by UUID.
38
39 =head1 METHODS
40
41 =head2 new
42
43 Returns a Directory object. 
44
45 =head2 traditionlist
46
47 Returns a hashref mapping of ID => name for all traditions in the directory.
48
49 =head2 tradition( $id )
50
51 Returns the Text::Tradition object of the given ID.
52
53 =head2 save( $tradition )
54
55 Writes the given tradition to the database, returning its ID.
56
57 =head2 delete( $tradition )
58
59 Deletes the given tradition object from the database.
60 WARNING!! Garbage collection does not yet work. Use this sparingly.
61
62 =begin testing
63
64 use TryCatch;
65 use File::Temp;
66 use Text::Tradition;
67 use_ok 'Text::Tradition::Directory';
68
69 my $fh = File::Temp->new();
70 my $file = $fh->filename;
71 $fh->close;
72 my $dsn = "dbi:SQLite:dbname=$file";
73 my $uuid;
74 my $t = Text::Tradition->new( 
75         'name'  => 'inline', 
76         'input' => 'Tabular',
77         'file'  => 't/data/simple.txt',
78         );
79
80 {
81         my $d = Text::Tradition::Directory->new( 'dsn' => $dsn,
82                 'extra_args' => { 'create' => 1 } );
83         is( ref $d, 'Text::Tradition::Directory', "Got directory object" );
84         
85         my $scope = $d->new_scope;
86         $uuid = $d->save( $t );
87         ok( $uuid, "Saved test tradition" );
88         
89         my $s = $t->add_stemma( dotfile => 't/data/simple.dot' );
90         ok( $d->save( $t ), "Updated tradition with stemma" );
91         is( $d->tradition( $uuid ), $t, "Correct tradition returned for id" );
92         is( $d->tradition( $uuid )->stemma(0), $s, "...and it has the correct stemma" );
93         try {
94                 $d->save( $s );
95         } catch( Text::Tradition::Error $e ) {
96                 is( $e->ident, 'database error', "Got exception trying to save stemma directly" );
97                 like( $e->message, qr/Cannot directly save non-Tradition object/, 
98                         "Exception has correct message" );
99         }
100 }
101 my $nt = Text::Tradition->new(
102         'name' => 'CX',
103         'input' => 'CollateX',
104         'file' => 't/data/Collatex-16.xml',
105         );
106 is( ref( $nt ), 'Text::Tradition', "Made new tradition" );
107
108 {
109         my $f = Text::Tradition::Directory->new( 'dsn' => $dsn );
110         my $scope = $f->new_scope;
111         is( scalar $f->traditionlist, 1, "Directory index has our tradition" );
112         my $nuuid = $f->save( $nt );
113         ok( $nuuid, "Stored second tradition" );
114         my @tlist = $f->traditionlist;
115         is( scalar @tlist, 2, "Directory index has both traditions" );
116         my $tf = $f->tradition( $uuid );
117         my( $tlobj ) = grep { $_->{'id'} eq $uuid } @tlist;
118         is( $tlobj->{'name'}, $tf->name, "Directory index has correct tradition name" );
119         is( $tf->name, $t->name, "Retrieved the tradition from a new directory" );
120         my $sid = $f->object_to_id( $tf->stemma(0) );
121         try {
122                 $f->tradition( $sid );
123         } catch( Text::Tradition::Error $e ) {
124                 is( $e->ident, 'database error', "Got exception trying to fetch stemma directly" );
125                 like( $e->message, qr/not a Text::Tradition/, "Exception has correct message" );
126         }
127         try {
128                 $f->delete( $sid );
129         } catch( Text::Tradition::Error $e ) {
130                 is( $e->ident, 'database error', "Got exception trying to delete stemma directly" );
131                 like( $e->message, qr/Cannot directly delete non-Tradition object/, 
132                         "Exception has correct message" );
133         }
134         
135         $f->delete( $uuid );
136         ok( !$f->exists( $uuid ), "Object is deleted from DB" );
137         ok( !$f->exists( $sid ), "Object stemma also deleted from DB" );
138         is( scalar $f->traditionlist, 1, "Object is deleted from index" );
139 }
140
141 {
142         my $g = Text::Tradition::Directory->new( 'dsn' => $dsn );
143         my $scope = $g->new_scope;
144         is( scalar $g->traditionlist, 1, "Now one object in new directory index" );
145         my $ntobj = $g->tradition( 'CX' );
146         my @w1 = sort { $a->sigil cmp $b->sigil } $ntobj->witnesses;
147         my @w2 = sort{ $a->sigil cmp $b->sigil } $nt->witnesses;
148         is_deeply( \@w1, \@w2, "Looked up remaining tradition by name" );
149 }
150
151 =end testing
152
153 =cut
154 use Text::Tradition::TypeMap::Entry;
155
156 has +typemap => (
157   is      => 'rw',
158   isa     => 'KiokuDB::TypeMap',
159   default => sub {
160     KiokuDB::TypeMap->new(
161       isa_entries => {
162         "Text::Tradition" =>
163           KiokuDB::TypeMap::Entry::Naive->new(),
164         "Graph" => Text::Tradition::TypeMap::Entry->new(),
165         "Graph::AdjacencyMap" => Text::Tradition::TypeMap::Entry->new(),
166                 "Lingua::Features::Structure" => Text::Tradition::TypeMap::Entry->new,
167                 "Lingua::Features::FeatureType" => Text::Tradition::TypeMap::Entry->new,
168       }
169     );
170   },
171 );
172
173 # Push some columns into the extra_args
174 around BUILDARGS => sub {
175         my $orig = shift;
176         my $class = shift;
177         my $args;
178         if( @_ == 1 ) {
179                 $args = $_[0];
180         } else {
181                 $args = { @_ };
182         }
183         if( $args->{'dsn'} =~ /^dbi/ ) { # We're using Backend::DBI
184                 my @column_args = ( 'columns',
185                         [ 'name' => { 'data_type' => 'varchar', 'is_nullable' => 1 } ] );
186                 my $ea = $args->{'extra_args'};
187                 if( ref( $ea ) eq 'ARRAY' ) {
188                         push( @$ea, @column_args );
189                 } elsif( ref( $ea ) eq 'HASH' ) {
190                         $ea = { %$ea, @column_args };
191                 } else {
192                         $ea = { @column_args };
193                 }
194                 $args->{'extra_args'} = $ea;
195         }
196         return $class->$orig( $args );
197 };
198
199 # before [ qw/ store update insert delete / ] => sub {
200 before [ qw/ delete / ] => sub {
201         my $self = shift;
202         my @nontrad;
203         foreach my $obj ( @_ ) {
204                 if( ref( $obj ) && ref( $obj ) ne 'Text::Tradition' ) {
205                         # Is it an id => Tradition hash?
206                         if( ref( $obj ) eq 'HASH' && keys( %$obj ) == 1 ) {
207                                 my( $k ) = keys %$obj;
208                                 next if ref( $obj->{$k} ) eq 'Text::Tradition';
209                         }
210                         push( @nontrad, $obj );
211                 }
212         }
213         if( @nontrad ) {
214                 throw( "Cannot directly save non-Tradition object of type "
215                         . ref( $nontrad[0] ) );
216         }
217 };
218
219 # TODO Garbage collection doesn't work. Suck it up and live with the 
220 # inflated DB.
221 # after delete => sub {
222 #       my $self = shift;
223 #       my $gc = KiokuDB::GC::Naive->new( backend => $self->directory->backend );
224 #       $self->directory->backend->delete( $gc->garbage->members );
225 # };
226
227 sub save {
228         my $self = shift;
229         return $self->store( @_ );
230 }
231
232 sub tradition {
233         my( $self, $id ) = @_;
234         my $obj = $self->lookup( $id );
235         unless( $obj ) {
236                 # Try looking up by name.
237                 foreach my $item ( $self->traditionlist ) {
238                         if( $item->{'name'} eq $id ) {
239                                 $obj = $self->lookup( $item->{'id'} );
240                                 last;
241                         }
242                 }
243         }
244         if( $obj && ref( $obj ) ne 'Text::Tradition' ) {
245                 throw( "Retrieved object is a " . ref( $obj ) . ", not a Text::Tradition" );
246         }
247         return $obj;
248 }
249
250 sub traditionlist {
251         my $self = shift;
252         # If we are using DBI, we can do it the easy way; if not, the hard way.
253         # Easy way still involves making a separate DBI connection. Ew.
254         my @tlist;
255         if( $self->dsn =~ /^dbi:(\w+):/ ) {
256                 my $dbtype = $1;
257                 my @connection = @{$self->directory->backend->connect_info};
258                 # Get rid of KiokuDB-specific arg
259                 pop @connection if scalar @connection > 4;
260                 $connection[3]->{'sqlite_unicode'} = 1 if $dbtype eq 'SQLite';
261                 $connection[3]->{'pg_enable_utf8'} = 1 if $dbtype eq 'Pg';
262                 my $dbh = DBI->connect( @connection );
263                 my $q = $dbh->prepare( 'SELECT id, name from entries WHERE class = "Text::Tradition"' );
264                 $q->execute();
265                 while( my @row = $q->fetchrow_array ) {
266                         my( $id, $name ) = @row;
267                         # Horrible horrible hack
268                         $name = decode_utf8( $name ) if $dbtype eq 'mysql';
269                         push( @tlist, { 'id' => $row[0], 'name' => $row[1] } );
270                 }
271         } else {
272                 $self->scan( sub { my $o = shift; 
273                                                    push( @tlist, { 'id' => $self->object_to_id( $o ), 
274                                                                                    'name' => $o->name } ) } );
275         }
276         return @tlist;
277 }
278
279 sub throw {
280         Text::Tradition::Error->throw( 
281                 'ident' => 'database error',
282                 'message' => $_[0],
283                 );
284 }
285
286 1;
287         
288 =head1 LICENSE
289
290 This package is free software and is provided "as is" without express
291 or implied warranty.  You can redistribute it and/or modify it under
292 the same terms as Perl itself.
293
294 =head1 AUTHOR
295
296 Tara L Andrews E<lt>aurum@cpan.orgE<gt>