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

Last change on this file since 32529 was 32529, checked in by ak19, 6 years ago

Split the database functions into their own file gssql.pm, so that GreenstoneSQLPlugin can share some db releated code used by GreenstoneSQLPlugout.

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