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

Revision 32530, 12.9 KB (checked in by ak19, 12 months ago)

Some more tidying up: some params passed by GreenstoneSQLPlugout to gssql should be instance variables, others are connection specific and now restricted to the gssql::connect_to_db() method.

RevLine 
[32518]1###########################################################################
2#
[32527]3# GreenstoneSQLPlugout.pm -- plugout module for writing all or some the
4# Greenstone document format (metadata and/or fulltext) into a (My)SQL db.
[32526]5# The rest is then still written out by GreenstoneXMLPlugout as usual.
[32518]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
[32527]28package GreenstoneSQLPlugout;
[32518]29
30use strict;
31no strict 'refs';
32no strict 'subs';
33
[32520]34use GreenstoneXMLPlugout;
[32518]35use docprint;
[32529]36use gssql;
[32518]37
[32524]38use DBI; # the central package for this plugout
39
[32518]40
[32521]41# TODO: SIGTERM rollback and disconnect?
42
43
[32518]44# this plugout does not output xml to a file, but outputs rows into a mysql table
45sub BEGIN {
[32527]46    @GreenstoneSQLPlugout::ISA = ('GreenstoneXMLPlugout');
[32518]47}
48
[32529]49# NOTTODO: die() statements need to be replaced with premature_termination
50# which should ensure the GreenstoneXMLPlugin (group)'s stuff is closed and cleaned up SOMEHOW
51# It's fine: the die() stmts all take place before setting up the super class' begin
[32520]52
53# TODO: deal with -removeold and everything? Or type out instructions for user
54
[32518]55# TODO Q: what is "group" in GreenstoneXMLPlugout?
[32520]56# TODO Q: site_name only exists for GS3. What about GS2?
[32518]57
58my $process_mode_list =
59    [ { 'name' => "meta_only",
[32527]60        'desc' => "{GreenstoneSQLPlugout.process_mode.meta_only}" },     
[32518]61      { 'name' => "text_only",
[32527]62        'desc' => "{GreenstoneSQLPlugout.process_mode.text_only}" },
[32518]63      { 'name' => "all",
[32527]64        'desc' => "{GreenstoneSQLPlugout.process_mode.all}" } ];
[32518]65
66my $arguments = [
67       { 'name' => "process_mode",
[32527]68     'desc' => "{GreenstoneSQLPlugout.process_mode}",
[32518]69     'type' => "enum",
70     'list' => $process_mode_list,
71     'deft' => "all",
72     'reqd' => "no",
73     'hiddengli' => "no"} ];
74
[32527]75my $options = { 'name'     => "GreenstoneSQLPlugout",
76        'desc'     => "{GreenstoneSQLPlugout.desc}",
[32518]77        'abstract' => "no",
78        'inherits' => "yes",
79        'args'     => $arguments };
80
81sub new {
82    my ($class) = shift (@_);
83    my ($plugoutlist, $inputargs,$hashArgOptLists) = @_;
84    push(@$plugoutlist, $class);
85
86    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
87    push(@{$hashArgOptLists->{"OptList"}},$options);
88
89    my $self = new GreenstoneXMLPlugout($plugoutlist,$inputargs,$hashArgOptLists);
90   
91    if ($self->{'info_only'}) {
92        # don't worry about any options etc
93        return bless $self, $class;
94    }
[32527]95    print STDERR "***** GreenstoneSQLPlugout process mode = \"", $self->{'process_mode'}, "\"\n";
[32518]96   
97    return bless $self, $class;
98}
99
[32520]100# connect here and ensure all tables and databases exist
101sub begin {
102
103    my $self= shift (@_);
104
105    ########### TODO: these should be set from cmdline/GLI options to plugout #########
106    $self->{'db_driver'} = "mysql";
107    $self->{'site_name'} = "localsite";   
[32521]108    $self->{'db_client_user'} = "root";
109    $self->{'db_client_pwd'} = "6reenstone3";
[32524]110    $self->{'build_mode'} = "removeold";
[32520]111    #$self->{'db_host'} = "127.0.0.1";
112    #$self->{'db_encoding'} = "utf8";
[32524]113    #TODO: proc_mode is also a saveas option   
[32520]114   
115    ############ LOAD NECESSARY OPTIONS ###########
116    print STDERR "########## COLLECTION: ". $ENV{'GSDLCOLLECTION'}."\n";
[32529]117    #$self->{'collection_name'} = $ENV{'GSDLCOLLECTION'};
[32527]118    print STDERR "***** GreenstoneSQLPlugout process mode = \"", $self->{'process_mode'}, "\"\n";
[32529]119
120    my $db_params = {
[32530]121    'collection_name' => $ENV{'GSDLCOLLECTION'},   
[32529]122    'db_encoding' => $self->{'db_encoding'}
123    #'db_name' => $self->{'site_name'},
124    #'build_mode' => $self->{'build_mode'},
125    };
126
127    my $gs_sql = new gssql($db_params);
[32520]128   
[32530]129    # try connecting to the mysql db, if that fails it will die
130    # so don't bother preparing GreenstoneXMLPlugout by calling superclass' begin()
131    if(!$gs_sql->connect_to_db({
132    'db_driver' => $self->{'db_driver'},
133    'db_client_user' => $self->{'db_client_user'},
134    'db_client_pwd' => $self->{'db_client_pwd'},
135    'db_host' => $self->{'db_host'}
136                   })
137    )
138    {
[32520]139    # This is fatal for the plugout, let's terminate here
140    # PrintError would already have displayed the warning message on connection fail   
141    die("Could not connect to db. Can't proceed.\n");
142    }
[32524]143   
144    my $db_name = $self->{'site_name'} || "localsite"; # one database per GS3 site
145    my $build_mode = $self->{'build_mode'} || "removeold";
[32529]146    if(!$gs_sql->load_db_and_tables($db_name, $build_mode)) {
[32524]147   
[32520]148    # This is fatal for the plugout, let's terminate here
149    # PrintError would already have displayed the warning message on connection fail   
150    die("Could not use db or prepare its tables. Can't proceed.\n");
151    }
152
153    # prepare the shared/common HANDLES to SQL insert statements that contain placeholders
[32521]154    # and which we will reuse repeatedly when actually executing the insert statements
[32520]155    my $proc_mode = $self->{'process_mode'};
156    if($proc_mode eq "all" || $proc_mode eq "meta_only" ) {
[32529]157    $self->{'metadata_prepared_insert_statement_handle'} = $gs_sql->prepare_insert_metadata_row_stmthandle();
[32520]158    }
159    if($proc_mode eq "all" || $proc_mode eq "text_only" ) {
[32529]160    $self->{'fulltxt_prepared_insert_statement_handle'} = $gs_sql->prepare_insert_fulltxt_row_stmthandle();
[32520]161    }
[32521]162
[32529]163    # store the DBI wrapper instance
164    $self->{'gs_sql'} = $gs_sql;
165   
[32524]166    print STDERR "#### Meta stmt: " . $self->{'metadata_prepared_insert_statement_handle'}->{'Statement'} . "\n";
167    print STDERR "#### Full stmt: " . $self->{'fulltxt_prepared_insert_statement_handle'}->{'Statement'} . "\n";
168   
[32521]169    # if setting up to work with sql db failed, we'd have terminated and wouldn't come up to here:
170    # won't bother preparing GreenstoneXMLPlugout by calling superclass' begin()
171    # finally, can call begin on super - important as doc.xml is opened as a group etc
[32523]172   
[32526]173    $self->SUPER::begin(@_);
[32520]174}
175
176# disconnect from database here, see inexport.pm
177sub end
178{
179    my $self = shift(@_);
180
[32521]181    # do the superclass stuff first, as any sql db failures should not prevent superclass cleanup
[32526]182    $self->SUPER::end(@_);   
[32521]183   
[32529]184    $self->{'gs_sql'}->disconnect_from_db() || warn("Unable to disconnect from database " . $self->{'site_name'} . "\n"); # disconnect_from_db() will also issue a warning, but this may be clearer
[32520]185}
[32521]186 
187   
[32518]188# TODO: check arc-inf.db for whether each entry is to be deleted/indexed/reindexed/been indexed
189sub saveas {
190    my $self = shift (@_);
191    my ($doc_obj, $doc_dir) = @_;
192
[32524]193    print STDERR "\n\n@@@ In saveas\n\n";
194   
[32522]195    my $proc_mode = $self->{'process_mode'};
196   
[32521]197    # 1. pre save out and saving debug handle
[32518]198
[32523]199    # must call superclass (pre/post) saveas methods, as they handle assoc_files too
[32526]200    my ($docxml_outhandler, $output_file) = $self->SUPER::pre_saveas(@_);
[32523]201
202    $self->{'debug_outhandle'} = $docxml_outhandler if ($self->{'debug'}); # STDOUT if debug
203
204    # TODO: also set debugging in begin()? Then stmts creating db and tables also sent to debug out and not executed
205
206    # TODO: remove unused old_unused_saveas from GreenstoneXMLPlugout
[32521]207   
208   
209    # 2. overriding saving behaviour to do what the superclass does PLUS saving to sql db   
[32518]210
[32523]211    #NOTE: if proc_mode == all, then "breadcrumbs" go into both meta and txt elements of doc.xml:
212    # statements pointing viewer to the sql db for contents
[32522]213   
[32523]214    # write the INVERSE into doc.xml as to what is written to the db   
215    my $docxml_output_options = { 'output' => docprint::OUTPUT_NONE };
216    if($proc_mode eq "meta_only" ) { # since only meta to go into MySQL db, text will go into docxml
217    $docxml_output_options->{'output'} = docprint::OUTPUT_TEXT_ONLY;
218    } elsif($proc_mode eq "text_only" ) { # since only full text to go into MySQL db, meta will go into docxml
219    $docxml_output_options->{'output'} = docprint::OUTPUT_META_ONLY;
[32521]220    }
221   
[32523]222    # now we've prepared to write out whatever is meant to go into docxml
223    # and can do actual the steps superclass GreenstoneXMLPlugout carries out to write out docxml
224    # So: write out the doc xml file for the current document
225    my $section_text = &docprint::get_section_xml($doc_obj, $docxml_output_options);
226    print $docxml_outhandler $section_text;   
227   
228   
[32518]229    # We also write out whatever needs to go into the MySQL database
230    $self->write_meta_and_text($doc_obj);
231
[32520]232   
[32521]233    # 3. post save out
[32526]234    #$self->SUPER::post_saveas(@_);
235    $self->SUPER::post_saveas($doc_obj, $doc_dir, $docxml_outhandler, $output_file);
[32521]236   
[32523]237   
[32521]238    # database connection is closed in end() method
239    # so we don't open and close over and over for each doc during a single build
[32518]240}
241
242
[32520]243# write meta and/or text PER DOC out to DB
[32518]244sub write_meta_and_text {
245    my $self = shift (@_);
246    my ($doc_obj) = @_;
247    my $root_section = $doc_obj->get_top_section();
[32520]248    my $doc_oid = $doc_obj->get_OID(); # we're processing a single doc at a time, so single OID
[32518]249
[32520]250    # load the prepared INSERT statement handles for both tables (can be undef for any table depending on whether meta_only or txt_only are set)
251    my $metadata_table_sth = $self->{'metadata_prepared_insert_statement_handle'};
252    my $fulltxt_table_sth = $self->{'fulltxt_prepared_insert_statement_handle'};
[32518]253   
[32524]254    $self->recursive_write_meta_and_text($doc_obj, $doc_oid, $root_section, $metadata_table_sth, $fulltxt_table_sth);
[32518]255}
[32521]256
[32518]257# Perl: Reading or Writing to Another Program
258# https://nnc3.com/mags/Perl3/cookbook/ch16_05.htm
259sub recursive_write_meta_and_text {
[32520]260    my $self = shift (@_);
261    my ($doc_obj, $doc_oid, $section, $metadata_table_sth, $fulltxt_table_sth) = @_;   
262
263    # If section=ROOT, write "root" as section name into table
264    # doc->get_top_section() is the name of the doc root section, which is ""
265    my $section_name = ($section eq "") ? "root" : $section;
[32518]266   
267    my $section_ptr = $doc_obj->_lookup_section ($section);
268    return "" unless defined $section_ptr;
269
[32520]270    my $debug_out = $self->{'debug_outhandle'};
[32524]271    print STDERR "#### Meta stmt: " . $metadata_table_sth->{'Statement'} . "\n";
272    print STDERR "#### Full stmt: " . $fulltxt_table_sth->{'Statement'} . "\n";
[32520]273   
274    #my $proc_mode = $self->{'process_mode'};
275    #if($proc_mode eq "all" || $proc_mode eq "meta_only" ) {
276    if($metadata_table_sth) { # meta insert statement handle will be undef if not writing meta
277   
278    foreach my $data (@{$section_ptr->{'metadata'}}) {
279        my $meta_name = $data->[0];
[32524]280        my $escaped_meta_value = &docprint::escape_text($data->[1]);
[32518]281
[32520]282        # Write out the current section's meta to collection db's METADATA table       
283       
284        # for each set of values to write to meta table, execute the prepared statement, filling in the values
285
286        if($self->{'debug'}) {
287        # just print the statement we were going to execute
288
[32524]289        print $debug_out $metadata_table_sth->{'Statement'} . "($doc_oid, $section_name, $meta_name, $escaped_meta_value)\n";
[32520]290        }
291        else {
292       
[32524]293        $metadata_table_sth->execute($doc_oid, $section_name, $meta_name, $escaped_meta_value) || warn ("Unable to write metadata row to db:\n\tOID $doc_oid, section $section_name,\n\tmeta name: $meta_name, val: $escaped_meta_value");
[32520]294        # Execution failure will print out info anyway: since db connection sets PrintError
295        }
[32518]296    }
297    }
[32520]298   
299    #if($proc_mode eq "all" || $proc_mode eq "text_only" ) {
300    if($fulltxt_table_sth) { # fulltxt insert statement handle will be undef if not writing fulltxt
301
302    if($self->{'debug'}) {
303        # just print the statement we were going to execute, minus the fulltxt value
304        my $txt_repr = $section_ptr->{'text'} ? "<TXT>" : "NULL";
[32524]305        print $debug_out $fulltxt_table_sth->{'Statement'} . "($doc_oid, $section_name, $txt_repr)\n";
[32520]306    } else {
[32524]307        my $section_text = &docprint::escape_text($section_ptr->{'text'});
[32520]308       
309        # fulltxt column can be SQL NULL. undef value gets written out as NULL:
310        # https://stackoverflow.com/questions/12708633/which-one-represents-null-undef-or-empty-string
311       
312        # Write out the current section's text to collection db's FULLTeXT table
[32524]313        $fulltxt_table_sth->execute($doc_oid, $section_name, $section_text) || warn ("Unable to write fulltxt row to db for row:\n\tOID $doc_oid, section $section_name");
[32520]314        # Execution failure will print out info anyway: since db connection sets PrintError
315    }
[32518]316    }
317   
318    # output all subsections: RECURSIVE CALL
319    foreach my $subsection (@{$section_ptr->{'subsection_order'}}) {
[32520]320    &recursive_write_meta_and_text($doc_obj, $doc_oid, "$section.$subsection", $metadata_table_sth, $fulltxt_table_sth);
[32518]321    }
322}
323
324
3251;
Note: See TracBrowser for help on using the browser.