root/main/trunk/greenstone2/perllib/plugouts/GreenstoneSQLPlugout.pm @ 32595

Revision 32595, 12.4 KB (checked in by ak19, 6 months ago)

Major tidying up: last remaining debug statements, lots of comments, removed TODO lists.

Line 
1###########################################################################
2#
3# GreenstoneSQLPlugout.pm -- plugout module for writing all or some the
4# Greenstone document format (metadata and/or fulltext) into a (My)SQL db.
5# The rest is then still written out by GreenstoneXMLPlugout as usual.
6# A component of the Greenstone digital library software
7# from the New Zealand Digital Library Project at the
8# University of Waikato, New Zealand.
9#
10# Copyright (C) 2006 New Zealand Digital Library Project
11#
12# This program is free software; you can redistribute it and/or modify
13# it under the terms of the GNU General Public License as published by
14# the Free Software Foundation; either version 2 of the License, or
15# (at your option) any later version.
16#
17# This program is distributed in the hope that it will be useful,
18# but WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20# GNU General Public License for more details.
21#
22# You should have received a copy of the GNU General Public License
23# along with this program; if not, write to the Free Software
24# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25#
26###########################################################################
27
28package GreenstoneSQLPlugout;
29
30use strict;
31no strict 'refs';
32no strict 'subs';
33
34use GreenstoneXMLPlugout;
35use docprint;
36use gsmysql;
37
38use DBI; # the central package for this plugout
39
40
41# This plugout does not output the metadata and/or fulltxt xml to a file,
42# but outputs rows into a MySQL db table for metadata and/or a db table for fulltxt
43
44sub BEGIN {
45    @GreenstoneSQLPlugout::ISA = ('GreenstoneXMLPlugout');
46}
47
48
49my $process_mode_list =
50    [ { 'name' => "meta_only",
51        'desc' => "{GreenstoneSQLPlug.process_mode.meta_only}" },     
52      { 'name' => "text_only",
53        'desc' => "{GreenstoneSQLPlug.process_mode.text_only}" },
54      { 'name' => "all",
55        'desc' => "{GreenstoneSQLPlug.process_mode.all}" } ];
56
57my $rollback_on_cancel_list =
58    [ { 'name' => "true",
59        'desc' => "{GreenstoneSQLPlug.rollback_on_cancel}" },     
60      { 'name' => "false",
61        'desc' => "{GreenstoneSQLPlug.rollbacl_on_cancel}" } ];
62
63# The following are the saveas.options:
64my $arguments = [
65    { 'name' => "process_mode",
66      'desc' => "{GreenstoneSQLPlug.process_mode}",
67      'type' => "enum",
68      'list' => $process_mode_list,
69      'deft' => "all",
70      'reqd' => "no",
71      'hiddengli' => "no"},
72    { 'name' => "rollback_on_cancel",
73      'desc' => "{GreenstoneSQLPlug.rollback_on_cancel}",
74      'type' => "enum",
75      'list' => $rollback_on_cancel_list,
76      'deft' => "false", # better default than true
77      'reqd' => "no",
78      'hiddengli' => "no"},
79    { 'name' => "db_driver",
80      'desc' => "{GreenstoneSQLPlug.db_driver}",
81      'type' => "string",   
82      'deft' => "mysql",
83      'reqd' => "yes"},
84    { 'name' => "db_client_user",
85      'desc' => "{GreenstoneSQLPlug.db_client_user}",
86      'type' => "string",   
87      'deft' => "root",
88      'reqd' => "yes"},
89    { 'name' => "db_client_pwd",
90      'desc' => "{GreenstoneSQLPlug.db_client_pwd}",
91      'type' => "string",
92      'deft' => "",
93      'reqd' => "no"}, # pwd not required: can create mysql accounts without pwd
94    { 'name' => "db_host",
95      'desc' => "{GreenstoneSQLPlug.db_host}",
96      'type' => "string",
97      'deft' => "127.0.0.1", # localhost doesn't work for us, but 127.0.0.1 works. See gsmysql.pm
98      'reqd' => "yes"},
99    { 'name' => "db_port",
100      'desc' => "{GreenstoneSQLPlug.db_port}",
101      'type' => "string", # NOTE: make this int? No default for port, since it's not a required connection param
102      'reqd' => "no"}
103    ];
104
105my $options = { 'name'     => "GreenstoneSQLPlugout",
106        'desc'     => "{GreenstoneSQLPlugout.desc}",
107        'abstract' => "no",
108        'inherits' => "yes",
109        'args'     => $arguments };
110
111##### This entire class is called only during import.pl #####
112
113##### Overridden methods #####
114
115sub new {
116    my ($class) = shift (@_);
117    my ($plugoutlist, $inputargs,$hashArgOptLists) = @_;
118    push(@$plugoutlist, $class);
119
120    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
121    push(@{$hashArgOptLists->{"OptList"}},$options);
122
123    my $self = new GreenstoneXMLPlugout($plugoutlist,$inputargs,$hashArgOptLists);
124   
125    if ($self->{'info_only'}) {
126        # don't worry about any options etc
127        return bless $self, $class;
128    }
129   
130    return bless $self, $class;
131}
132
133# connect here and ensure all tables and databases exist
134sub begin {
135
136    my $self= shift (@_);
137   
138    my $db_params = {
139    'collection_name' => $ENV{'GSDLCOLLECTION'},
140    'verbosity' => $self->{'verbosity'} || 0
141   
142    };
143
144    my $gs_sql = new gsmysql($db_params);
145
146    # if autocommit is set, there's no rollback support
147    my $autocommit = ($self->{'rollback_on_cancel'} eq "false") ? 1 : 0;
148   
149    # try connecting to the mysql db, die if that fails
150    # So don't bother preparing GreenstoneXMLPlugout by calling superclass' begin() yet
151    if(!$gs_sql->connect_to_db({
152    'db_driver' => $self->{'db_driver'},
153    'db_client_user' => $self->{'db_client_user'},
154    'db_client_pwd' => $self->{'db_client_pwd'},
155    'db_host' => $self->{'db_host'},
156    'db_port' => $self->{'db_port'}, # undef by default, can leave as is
157    'autocommit' => $autocommit
158                   })
159    )
160    {
161    # This is fatal for the plugout, let's terminate here
162    # PrintError would already have displayed the warning message on connection fail   
163    die("Could not connect to db. Can't proceed.\n");
164    }
165
166    my $db_name = $self->{'site'} || "greenstone2"; # one database per GS3 site, for GS2 the db is called greenstone2
167    my $proc_mode = $self->{'process_mode'};
168   
169
170    my $success = $gs_sql->use_db($db_name);
171   
172    if($success && $proc_mode ne "text_only") {
173    $success = $gs_sql->ensure_meta_table_exists();
174    }   
175    if($success && $proc_mode ne "meta_only") {
176    $success = $gs_sql->ensure_fulltxt_table_exists();
177    }
178   
179    if(!$success) {
180    # This is fatal for the plugout, let's terminate here after disconnecting again
181    # PrintError would already have displayed the warning message on load fail
182    # And on die() perl will call gsmysql destroy which will ensure a disconnect() from db
183    die("Could not use db $db_name and/or prepare its tables. Can't proceed.\n");
184    }
185
186    # store the DBI wrapper instance
187    $self->{'gs_sql'} = $gs_sql;
188   
189   
190    # If setting up connection to sql db failed, we'd have terminated and wouldn't come up to here
191    # and wouldn't have bothered preparing GreenstoneXMLPlugout by calling superclass' begin().
192    # Finally, can call begin on super - important as doc.xml is opened as a group etc
193   
194    $self->SUPER::begin(@_);
195}
196
197# disconnect from database here, see inexport.pm
198sub end
199{
200    my $self = shift(@_);
201
202    # do the superclass stuff first, as any sql db failures should not prevent superclass cleanup
203    $self->SUPER::end(@_);   
204
205    # Important to call finished():
206    # it will disconnect from db if this is the last gsmysql instance,
207    # and it will commit to db before disconnecting if rollbback_on_cancel turned on
208    $self->{'gs_sql'}->finished();
209    delete $self->{'gs_sql'}; # key gs_sql no longer exists, not just the value being undef
210}
211
212# Produce files called docsql.xml instead of doc.xml
213sub get_doc_xml_filename {
214    my $self = shift (@_);
215    my ($doc_obj) = @_;
216   
217    return "docsql.xml";
218}
219
220# overriding to store doc OID as attribute of top level element: <Archive docoid="oid">
221sub output_xml_header {
222    my $self = shift (@_);
223    my ($outhandle, $doc_oid) = @_;
224
225    print $outhandle '<?xml version="1.0" encoding="utf-8" standalone="no"?>' . "\n";
226    print $outhandle "<!DOCTYPE Archive SYSTEM \"http://greenstone.org/dtd/Archive/1.0/Archive.dtd\">\n";
227    print $outhandle "<Archive docoid=\"$doc_oid\">\n";
228}
229 
230# saveas() only generates the content in archives dir and in the SQL database
231sub saveas {
232    my $self = shift (@_);
233    my ($doc_obj, $doc_dir) = @_;
234
235    my $proc_mode = $self->{'process_mode'};
236   
237    # 1. pre save out and saving debug handle
238
239    # must call superclass (pre/post) saveas methods, as they handle assoc_files too
240    my ($docxml_outhandler, $output_file) = $self->SUPER::pre_saveas(@_);
241
242    $self->{'debug_outhandle'} = $docxml_outhandler if ($self->{'debug'}); # STDOUT if debug
243
244    # 2. overriding saving behaviour to do what the superclass does (writing out doc.xml files,
245    # under new name of docsql.xml, with breadcrumbs pointing to sql db) PLUS saving to sql db   
246
247    # NOTE: if proc_mode == all, then "breadcrumbs" (statements pointing viewer to the sql db
248    # for contents) go into both meta and txt elements of doc.xml (docsql.xml specifically):
249   
250    # write the INVERSE into doc.xml as to what is written to the SQL db   
251    my $docxml_output_options = { 'output' => docprint::OUTPUT_NONE };
252    if($proc_mode eq "meta_only" ) { # since only meta to go into MySQL db, text will go into docxml
253    $docxml_output_options->{'output'} = docprint::OUTPUT_TEXT_ONLY;
254    } elsif($proc_mode eq "text_only" ) { # since only full text to go into MySQL db, meta will go into docxml
255    $docxml_output_options->{'output'} = docprint::OUTPUT_META_ONLY;
256    }
257   
258    # now we've prepared to write out whatever is meant to go into docxml
259    # and can do actual the steps superclass GreenstoneXMLPlugout carries out to write out docxml
260    # So: write out the doc xml file, "docsql.xml", for the current document
261    my $section_text = &docprint::get_section_xml($doc_obj, $docxml_output_options);
262    print $docxml_outhandler $section_text;   
263   
264   
265    # We also write out whatever needs to go into the MySQL database
266    $self->write_meta_and_text($doc_obj);
267
268   
269    # 3. post save out
270    $self->SUPER::post_saveas($doc_obj, $doc_dir, $docxml_outhandler, $output_file);
271   
272   
273    # database connection is closed once, in end() method
274    # We're not opening and closing over and over for each doc during a single build
275}
276
277##### New methods, not inherited  #####
278
279# write meta and/or text PER DOC out to DB
280sub write_meta_and_text {
281    my $self = shift (@_);
282    my ($doc_obj) = @_;
283    my $doc_oid = $doc_obj->get_OID(); # this method processes a single doc at a time, so it uses the same OID throughout
284    my $root_section = $doc_obj->get_top_section();
285
286    $self->recursive_write_meta_and_text($doc_obj, $doc_oid, $root_section);
287}
288
289sub recursive_write_meta_and_text {
290    my $self = shift (@_);
291    my ($doc_obj, $doc_oid, $section) = @_;   
292
293    # If section=ROOT, write "root" as section name into table
294    # doc->get_top_section() is the name of the doc root section, which is ""
295    my $section_name = ($section eq "") ? "root" : $section;
296   
297    my $section_ptr = $doc_obj->_lookup_section ($section);
298    return "" unless defined $section_ptr;
299
300    my $debug_out = $self->{'debug_outhandle'};
301
302    my $gs_sql = $self->{'gs_sql'};
303    my $proc_mode = $self->{'process_mode'};
304    if($proc_mode eq "all" || $proc_mode eq "meta_only" ) {
305   
306    foreach my $data (@{$section_ptr->{'metadata'}}) {
307        my $meta_name = $data->[0];
308
309        # Treat db like a text file instead of an html/xml file: don't need to escape text
310        # going into it, unlike with doc(sql).xml
311        my $meta_value = $data->[1];
312       
313        # Write out the current section's meta to collection db's METADATA table       
314       
315        # For each set of values to write to meta table, this next method call will
316        # efficiently execute an insert SQL statement (using a prepared insert statement),
317        # filling in the values
318        # OR if debugging, then it will print the SQL insert statement but not execute it
319        # (a behaviour following what the GS XML Plugout superclass does on debug)
320       
321        $gs_sql->insert_row_into_metadata_table($doc_oid, $section_name, $meta_name, $meta_value, $self->{'debug'});
322    }
323    }
324   
325   
326    if($proc_mode eq "all" || $proc_mode eq "text_only" ) {
327
328    # See above, no need to html-escape for db
329    my $section_text = $section_ptr->{'text'};
330   
331    # fulltxt column can be SQL NULL. undef value for $section_text gets written out as NULL:
332    # https://stackoverflow.com/questions/12708633/which-one-represents-null-undef-or-empty-string
333    # The following will do the SQL insertion
334    # or if debug, the following will print the SQL insert stmt without executing it
335    $gs_sql->insert_row_into_fulltxt_table($doc_oid, $section_name, \$section_text, $self->{'debug'});
336   
337    }
338   
339    # output all subsections: RECURSIVE CALL
340    foreach my $subsection (@{$section_ptr->{'subsection_order'}}) {
341    $self->recursive_write_meta_and_text($doc_obj, $doc_oid, "$section.$subsection");
342    }
343}
344
345
3461;
Note: See TracBrowser for help on using the browser.