source: main/trunk/greenstone2/perllib/plugouts/GreenstoneSQLPlugout.pm@ 32542

Last change on this file since 32542 was 32542, checked in by ak19, 4 years ago

Instead of the docoid being stored in the docsql-<OID>.xml filename, all filenames produced are back to being docsql.xml, but the root element Archive now contains the doc oid as attribute: <Archive docoid="oid">

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