[32518] | 1 | ###########################################################################
|
---|
| 2 | #
|
---|
| 3 | # GreenstoneXMLPlugout.pm -- the plugout module for Greenstone Archives
|
---|
| 4 | # A component of the Greenstone digital library software
|
---|
| 5 | # from the New Zealand Digital Library Project at the
|
---|
| 6 | # University of Waikato, New Zealand.
|
---|
| 7 | #
|
---|
| 8 | # Copyright (C) 2006 New Zealand Digital Library Project
|
---|
| 9 | #
|
---|
| 10 | # This program is free software; you can redistribute it and/or modify
|
---|
| 11 | # it under the terms of the GNU General Public License as published by
|
---|
| 12 | # the Free Software Foundation; either version 2 of the License, or
|
---|
| 13 | # (at your option) any later version.
|
---|
| 14 | #
|
---|
| 15 | # This program is distributed in the hope that it will be useful,
|
---|
| 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
| 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
| 18 | # GNU General Public License for more details.
|
---|
| 19 | #
|
---|
| 20 | # You should have received a copy of the GNU General Public License
|
---|
| 21 | # along with this program; if not, write to the Free Software
|
---|
| 22 | # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
|
---|
| 23 | #
|
---|
| 24 | ###########################################################################
|
---|
| 25 |
|
---|
| 26 | package MySQLPlugout;
|
---|
| 27 |
|
---|
| 28 | use strict;
|
---|
| 29 | no strict 'refs';
|
---|
| 30 | no strict 'subs';
|
---|
| 31 |
|
---|
| 32 | use util;
|
---|
| 33 | use FileUtils;
|
---|
[32520] | 34 | use GreenstoneXMLPlugout;
|
---|
[32518] | 35 | use docprint;
|
---|
| 36 |
|
---|
| 37 | use IPC::Open2;
|
---|
| 38 | use POSIX ":sys_wait_h"; # for waitpid, http://perldoc.perl.org/functions/waitpid.html
|
---|
| 39 |
|
---|
[32521] | 40 | # TODO: SIGTERM rollback and disconnect?
|
---|
| 41 |
|
---|
| 42 |
|
---|
[32518] | 43 | # this plugout does not output xml to a file, but outputs rows into a mysql table
|
---|
| 44 | sub BEGIN {
|
---|
| 45 | @MySQLPlugout::ISA = ('GreenstoneXMLPlugout');
|
---|
| 46 | }
|
---|
| 47 |
|
---|
[32520] | 48 |
|
---|
| 49 | # TODO: deal with -removeold and everything? Or type out instructions for user
|
---|
| 50 |
|
---|
[32518] | 51 | # TODO Q: what is "group" in GreenstoneXMLPlugout?
|
---|
[32520] | 52 | # TODO Q: site_name only exists for GS3. What about GS2?
|
---|
[32518] | 53 |
|
---|
| 54 | my $process_mode_list =
|
---|
| 55 | [ { 'name' => "meta_only",
|
---|
| 56 | 'desc' => "{MySQLPlugout.process_mode.meta_only}" },
|
---|
| 57 | { 'name' => "text_only",
|
---|
| 58 | 'desc' => "{MySQLPlugout.process_mode.text_only}" },
|
---|
| 59 | { 'name' => "all",
|
---|
| 60 | 'desc' => "{MySQLPlugout.process_mode.all}" } ];
|
---|
| 61 |
|
---|
| 62 | my $arguments = [
|
---|
| 63 | { 'name' => "process_mode",
|
---|
| 64 | 'desc' => "{MySQLPlugout.process_mode}",
|
---|
| 65 | 'type' => "enum",
|
---|
| 66 | 'list' => $process_mode_list,
|
---|
| 67 | 'deft' => "all",
|
---|
| 68 | 'reqd' => "no",
|
---|
| 69 | 'hiddengli' => "no"} ];
|
---|
| 70 |
|
---|
| 71 | my $options = { 'name' => "MySQLPlugout",
|
---|
| 72 | 'desc' => "{MySQLPlugout.desc}",
|
---|
| 73 | 'abstract' => "no",
|
---|
| 74 | 'inherits' => "yes",
|
---|
| 75 | 'args' => $arguments };
|
---|
| 76 |
|
---|
| 77 | sub new {
|
---|
| 78 | my ($class) = shift (@_);
|
---|
| 79 | my ($plugoutlist, $inputargs,$hashArgOptLists) = @_;
|
---|
| 80 | push(@$plugoutlist, $class);
|
---|
| 81 |
|
---|
| 82 | push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
|
---|
| 83 | push(@{$hashArgOptLists->{"OptList"}},$options);
|
---|
| 84 |
|
---|
| 85 | my $self = new GreenstoneXMLPlugout($plugoutlist,$inputargs,$hashArgOptLists);
|
---|
| 86 |
|
---|
| 87 | if ($self->{'info_only'}) {
|
---|
| 88 | # don't worry about any options etc
|
---|
| 89 | return bless $self, $class;
|
---|
| 90 | }
|
---|
| 91 | print STDERR "***** MySQLPlugout process mode = \"", $self->{'process_mode'}, "\"\n";
|
---|
| 92 |
|
---|
| 93 | return bless $self, $class;
|
---|
| 94 | }
|
---|
| 95 |
|
---|
[32520] | 96 | # connect here and ensure all tables and databases exist
|
---|
| 97 | sub begin {
|
---|
| 98 |
|
---|
| 99 | my $self= shift (@_);
|
---|
| 100 |
|
---|
| 101 | ########### TODO: these should be set from cmdline/GLI options to plugout #########
|
---|
| 102 | $self->{'db_driver'} = "mysql";
|
---|
| 103 | $self->{'site_name'} = "localsite";
|
---|
[32521] | 104 | $self->{'db_client_user'} = "root";
|
---|
| 105 | $self->{'db_client_pwd'} = "6reenstone3";
|
---|
[32520] | 106 | #$self->{'db_host'} = "127.0.0.1";
|
---|
| 107 | #$self->{'db_encoding'} = "utf8";
|
---|
[32521] | 108 | #TODO: proc_mode is also a saveas option
|
---|
[32520] | 109 |
|
---|
| 110 | ############ LOAD NECESSARY OPTIONS ###########
|
---|
| 111 | print STDERR "########## COLLECTION: ". $ENV{'GSDLCOLLECTION'}."\n";
|
---|
| 112 | $self->{'collection_name'} = $ENV{'GSDLCOLLECTION'};
|
---|
| 113 |
|
---|
| 114 | if(!$self->connect_to_db()) {
|
---|
| 115 | # This is fatal for the plugout, let's terminate here
|
---|
| 116 | # PrintError would already have displayed the warning message on connection fail
|
---|
| 117 | die("Could not connect to db. Can't proceed.\n");
|
---|
| 118 | }
|
---|
| 119 | if(!$self->load_db_and_tables()) {
|
---|
| 120 | # This is fatal for the plugout, let's terminate here
|
---|
| 121 | # PrintError would already have displayed the warning message on connection fail
|
---|
| 122 | die("Could not use db or prepare its tables. Can't proceed.\n");
|
---|
| 123 | }
|
---|
| 124 |
|
---|
| 125 | # prepare the shared/common HANDLES to SQL insert statements that contain placeholders
|
---|
[32521] | 126 | # and which we will reuse repeatedly when actually executing the insert statements
|
---|
[32520] | 127 | my $proc_mode = $self->{'process_mode'};
|
---|
| 128 | if($proc_mode eq "all" || $proc_mode eq "meta_only" ) {
|
---|
| 129 | $self->{'metadata_prepared_insert_statement_handle'} = $self->prepare_insert_metadata_row_stmthandle();
|
---|
| 130 | }
|
---|
| 131 | if($proc_mode eq "all" || $proc_mode eq "text_only" ) {
|
---|
| 132 | $self->{'fulltxt_prepared_insert_statement_handle'} = $self->prepare_insert_fulltxt_row_stmthandle();
|
---|
| 133 | }
|
---|
[32521] | 134 |
|
---|
| 135 | # if setting up to work with sql db failed, we'd have terminated and wouldn't come up to here:
|
---|
| 136 | # won't bother preparing GreenstoneXMLPlugout by calling superclass' begin()
|
---|
| 137 | # finally, can call begin on super - important as doc.xml is opened as a group etc
|
---|
| 138 |
|
---|
| 139 | if($proc_mode ne "all") { # TODO Q
|
---|
| 140 | $self->GreenstoneXMLPlugout::begin(@_);
|
---|
| 141 | }
|
---|
[32520] | 142 | }
|
---|
| 143 |
|
---|
| 144 | # disconnect from database here, see inexport.pm
|
---|
| 145 | sub end
|
---|
| 146 | {
|
---|
| 147 | my $self = shift(@_);
|
---|
| 148 |
|
---|
[32521] | 149 | # do the superclass stuff first, as any sql db failures should not prevent superclass cleanup
|
---|
| 150 |
|
---|
| 151 | if($self->{'process_mode'} ne "all") {# TODO Q
|
---|
| 152 | $self->GreenstoneXMLPlugout::end(@_);
|
---|
| 153 | }
|
---|
| 154 |
|
---|
| 155 | $self->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] | 156 | }
|
---|
[32521] | 157 |
|
---|
| 158 | sub close_group_output {
|
---|
| 159 | my $self = shift (@_);
|
---|
[32520] | 160 |
|
---|
[32521] | 161 | if($proc_mode ne "all") { # TODO Q
|
---|
| 162 | $self->GreenstoneXMLPlugout::close_group_output();
|
---|
| 163 | }
|
---|
| 164 | }
|
---|
| 165 |
|
---|
[32518] | 166 | # TODO: check arc-inf.db for whether each entry is to be deleted/indexed/reindexed/been indexed
|
---|
| 167 | sub saveas {
|
---|
| 168 | my $self = shift (@_);
|
---|
| 169 | my ($doc_obj, $doc_dir) = @_;
|
---|
| 170 |
|
---|
[32521] | 171 | # 1. pre save out and saving debug handle
|
---|
| 172 | if($proc_mode ne "all") { # TODO Q
|
---|
| 173 | my ($docxml_outhandler, $output_file) = $self->GreenstoneXMLPlugout::pre_saveas(@_);
|
---|
| 174 |
|
---|
| 175 | $self->{'debug_outhandle'} = $docxml_outhandler if ($self->{'debug'}); # STDOUT if debug
|
---|
| 176 | }
|
---|
| 177 | elsif ($self->{'debug'}) { # if we didn't call superclass::pre_saveas, then set debug handle
|
---|
| 178 | $self->{'debug_outhandle'} = STDOUT; # superclass also debugs to STDOUT
|
---|
| 179 | # TODO: also set debugging in begin()? Then stmts creating db and tables also sent to debug out and not executed
|
---|
| 180 | }
|
---|
[32520] | 181 |
|
---|
[32521] | 182 |
|
---|
| 183 | # 2. overriding saving behaviour to do what the superclass does PLUS saving to sql db
|
---|
[32518] | 184 |
|
---|
[32521] | 185 | if($proc_mode ne "all" ) { # if all, then nothing to go into doc.xml
|
---|
| 186 | # write the INVERSE into doc.xml as to what is written to the db
|
---|
| 187 | my $proc_mode = $self->{'process_mode'};
|
---|
| 188 |
|
---|
| 189 | my $docxml_output_options = { 'output' => docprint::OUTPUT_NONE }; # TODO Q
|
---|
| 190 |
|
---|
| 191 | if($proc_mode eq "meta_only" ) { # since only meta to go into MySQL db, text will go into docxml
|
---|
| 192 | $docxml_output_options->{'output'} = docprint::OUTPUT_TEXT_ONLY;
|
---|
| 193 | } elsif($proc_mode eq "text_only" ) { # since only full text to go into MySQL db, meta will go into docxml
|
---|
| 194 | $docxml_output_options->{'output'} = docprint::OUTPUT_META_ONLY;
|
---|
| 195 | }
|
---|
[32520] | 196 |
|
---|
[32521] | 197 | # now we've prepared to write out whatever is meant to go into docxml
|
---|
| 198 | # and can do actual the steps superclass GreenstoneXMLPlugout carries out to write out docxml
|
---|
| 199 | # So: write out the doc xml file for the current document
|
---|
| 200 | my $section_text = &docprint::get_section_xml($doc_obj, $docxml_output_options);
|
---|
| 201 | print $docxml_outhandler $section_text;
|
---|
[32518] | 202 | }
|
---|
[32521] | 203 |
|
---|
[32518] | 204 | # We also write out whatever needs to go into the MySQL database
|
---|
| 205 | $self->write_meta_and_text($doc_obj);
|
---|
| 206 |
|
---|
[32520] | 207 |
|
---|
[32521] | 208 | # 3. post save out
|
---|
| 209 | if($proc_mode ne "all" ) { # TODO Q
|
---|
| 210 | #$self->GreenstoneXMLPlugout::post_saveas(@_);
|
---|
| 211 | $self->GreenstoneXMLPlugout::post_saveas($doc_obj, $doc_dir, $docxml_outhandler, $output_file);
|
---|
| 212 | }
|
---|
| 213 |
|
---|
| 214 | # database connection is closed in end() method
|
---|
| 215 | # so we don't open and close over and over for each doc during a single build
|
---|
[32518] | 216 | }
|
---|
| 217 |
|
---|
| 218 |
|
---|
[32520] | 219 | # write meta and/or text PER DOC out to DB
|
---|
[32518] | 220 | sub write_meta_and_text {
|
---|
| 221 | my $self = shift (@_);
|
---|
| 222 | my ($doc_obj) = @_;
|
---|
| 223 | my $root_section = $doc_obj->get_top_section();
|
---|
[32520] | 224 | my $doc_oid = $doc_obj->get_OID(); # we're processing a single doc at a time, so single OID
|
---|
[32518] | 225 |
|
---|
[32520] | 226 | # 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)
|
---|
| 227 | my $metadata_table_sth = $self->{'metadata_prepared_insert_statement_handle'};
|
---|
| 228 | my $fulltxt_table_sth = $self->{'fulltxt_prepared_insert_statement_handle'};
|
---|
[32518] | 229 |
|
---|
[32520] | 230 | $self->recursive_write_meta_and_text($doc_obj, $root_section, $metadata_table_sth, $fulltxt_table_sth);
|
---|
[32521] | 231 | }
|
---|
[32518] | 232 |
|
---|
| 233 | # Perl: Reading or Writing to Another Program
|
---|
| 234 | # https://nnc3.com/mags/Perl3/cookbook/ch16_05.htm
|
---|
| 235 | sub recursive_write_meta_and_text {
|
---|
[32520] | 236 | my $self = shift (@_);
|
---|
| 237 | my ($doc_obj, $doc_oid, $section, $metadata_table_sth, $fulltxt_table_sth) = @_;
|
---|
| 238 |
|
---|
| 239 | # If section=ROOT, write "root" as section name into table
|
---|
| 240 | # doc->get_top_section() is the name of the doc root section, which is ""
|
---|
| 241 | my $section_name = ($section eq "") ? "root" : $section;
|
---|
[32518] | 242 |
|
---|
| 243 | my $section_ptr = $doc_obj->_lookup_section ($section);
|
---|
| 244 | return "" unless defined $section_ptr;
|
---|
| 245 |
|
---|
[32520] | 246 | my $debug_out = $self->{'debug_outhandle'};
|
---|
| 247 |
|
---|
| 248 | #my $proc_mode = $self->{'process_mode'};
|
---|
| 249 | #if($proc_mode eq "all" || $proc_mode eq "meta_only" ) {
|
---|
| 250 | if($metadata_table_sth) { # meta insert statement handle will be undef if not writing meta
|
---|
| 251 |
|
---|
| 252 | foreach my $data (@{$section_ptr->{'metadata'}}) {
|
---|
| 253 | my $meta_name = $data->[0];
|
---|
| 254 | my $escaped_meta_value = &escape_text($data->[1]);
|
---|
[32518] | 255 |
|
---|
[32520] | 256 | # Write out the current section's meta to collection db's METADATA table
|
---|
| 257 |
|
---|
| 258 | # for each set of values to write to meta table, execute the prepared statement, filling in the values
|
---|
| 259 |
|
---|
| 260 | if($self->{'debug'}) {
|
---|
| 261 | # just print the statement we were going to execute
|
---|
| 262 |
|
---|
| 263 | print $debug_out $metadata_table_sth->Statement . "($doc_oid, $section_name, $meta_name, $escaped_meta_value)\n";
|
---|
| 264 | }
|
---|
| 265 | else {
|
---|
| 266 |
|
---|
| 267 | $metadata_table_sth->execute($doc_oid, $section_name, $meta_name, $escaped_meta_value);
|
---|
| 268 | #|| warn ("Unable to write metadata row to db:\n\tOID $doc_oid, section $section_name,\n\tmeta name: $meta_name, val: $escaped_meta_value");
|
---|
| 269 | # Execution failure will print out info anyway: since db connection sets PrintError
|
---|
| 270 | }
|
---|
[32518] | 271 | }
|
---|
| 272 | }
|
---|
[32520] | 273 |
|
---|
| 274 | #if($proc_mode eq "all" || $proc_mode eq "text_only" ) {
|
---|
| 275 | if($fulltxt_table_sth) { # fulltxt insert statement handle will be undef if not writing fulltxt
|
---|
| 276 |
|
---|
| 277 | if($self->{'debug'}) {
|
---|
| 278 | # just print the statement we were going to execute, minus the fulltxt value
|
---|
| 279 | my $txt_repr = $section_ptr->{'text'} ? "<TXT>" : "NULL";
|
---|
| 280 | print $debug_out $fulltxt_table_sth->Statement . "($doc_oid, $section_name, $txt_repr)\n";
|
---|
| 281 | } else {
|
---|
| 282 | my $section_text = &escape_text($section_ptr->{'text'});
|
---|
| 283 |
|
---|
| 284 | # fulltxt column can be SQL NULL. undef value gets written out as NULL:
|
---|
| 285 | # https://stackoverflow.com/questions/12708633/which-one-represents-null-undef-or-empty-string
|
---|
| 286 |
|
---|
| 287 | # Write out the current section's text to collection db's FULLTeXT table
|
---|
| 288 | $fulltxt_table_sth->execute($doc_oid, $section_name, $section_text);
|
---|
| 289 | #|| warn ("Unable to write fulltxt row to db for row:\n\tOID $doc_oid, section $section_name");
|
---|
| 290 | # Execution failure will print out info anyway: since db connection sets PrintError
|
---|
| 291 | }
|
---|
[32518] | 292 | }
|
---|
| 293 |
|
---|
| 294 | # output all subsections: RECURSIVE CALL
|
---|
| 295 | foreach my $subsection (@{$section_ptr->{'subsection_order'}}) {
|
---|
[32520] | 296 | &recursive_write_meta_and_text($doc_obj, $doc_oid, "$section.$subsection", $metadata_table_sth, $fulltxt_table_sth);
|
---|
[32518] | 297 | }
|
---|
| 298 | }
|
---|
| 299 |
|
---|
| 300 | #################################
|
---|
| 301 |
|
---|
| 302 | # Database access related functions
|
---|
| 303 | # http://g2pc1.bu.edu/~qzpeng/manual/MySQL%20Commands.htm
|
---|
| 304 | # https://www.guru99.com/insert-into.html
|
---|
| 305 |
|
---|
| 306 | # TODO Q: What on cancelling a build: delete table? But what if it was a rebuild and the rebuild is cancelled (not the original build)?
|
---|
| 307 | # Do we create a copy of the orig database as backup, then start populating current db, and if cancelled, delete current db and RENAME backup table to current?
|
---|
| 308 | # https://stackoverflow.com/questions/3280006/duplicating-a-mysql-table-indexes-and-data
|
---|
| 309 | # BUT what if the table is HUGE? (Think of a collection with millions of docs.) Huge overhead in copying?
|
---|
| 310 | # The alternative is we just quit on cancel, but then: cancel could leave the table in a partial committed state, with no way of rolling back.
|
---|
[32520] | 311 | # Unless they do a full rebuild, which will recreate the table from scratch?
|
---|
| 312 | # SOLUTION-> rollback transaction on error, see https://www.effectiveperlprogramming.com/2010/07/set-custom-dbi-error-handlers/
|
---|
[32521] | 313 | # But then should set AutoCommit to off on connection, and remember to commit every time
|
---|
[32518] | 314 |
|
---|
| 315 | #################
|
---|
[32520] | 316 | # Database functions that use the perl DBI module (with the DBD driver module for mysql)
|
---|
| 317 | #################
|
---|
[32518] | 318 |
|
---|
[32520] | 319 | # THE NEW DB FUNCTIONS
|
---|
| 320 | # NOTE: FULLTEXT is a reserved keyword in (My)SQL. So we can't name a table or any of its columns "fulltext".
|
---|
| 321 | # https://dev.mysql.com/doc/refman/5.5/en/keywords.html
|
---|
| 322 |
|
---|
| 323 | # TODO: Consider AutoCommit status (and Autocommit off allowing commit or rollback for GS coll build cancel) later
|
---|
| 324 |
|
---|
| 325 | sub connect_to_db {
|
---|
| 326 | my $self= shift (@_);
|
---|
| 327 |
|
---|
| 328 | my $db_driver = $self->{'db_driver'};
|
---|
[32521] | 329 | my $db_user = $self->{'db_client_user'} || "root";
|
---|
| 330 | my $db_pwd = $self->{'db_client_pwd'};
|
---|
[32520] | 331 | my $db_host = $self->{'db_host'} || "127.0.0.1";
|
---|
| 332 | my $db_enc = $self->{'db_encoding'} || "utf8";
|
---|
| 333 |
|
---|
| 334 | #my $db_name = $self->{'site_name'};
|
---|
| 335 |
|
---|
| 336 | # try connecting to the mysql db, if that fails it will die
|
---|
| 337 | # so don't bother preparing GreenstoneXMLPlugout by calling superclass' begin()
|
---|
| 338 |
|
---|
| 339 | # localhost doesn't work for us, but 127.0.0.1 works
|
---|
| 340 | # https://metacpan.org/pod/DBD::mysql
|
---|
| 341 | # "The hostname, if not specified or specified as '' or 'localhost', will default to a MySQL server
|
---|
| 342 | # running on the local machine using the default for the UNIX socket. To connect to a MySQL server
|
---|
| 343 | # on the local machine via TCP, you must specify the loopback IP address (127.0.0.1) as the host."
|
---|
| 344 | #my $connect_str = "dbi:$db_driver:database=$db_name;host=$db_host";
|
---|
| 345 | my $connect_str = "dbi:$db_driver:host=$db_host"; # don't provide db, so we can check the db is there
|
---|
| 346 | my $dbh = DBI->connect("$connect_str", $db_user, $db_pwd,
|
---|
| 347 | {
|
---|
| 348 | ShowErrorStatement => 1, # more informative as DBI will append failed SQL stmt to error message
|
---|
| 349 | PrintError => 1, # on by default, but being explicit
|
---|
| 350 | RaiseError => 0, # off by default, but being explicit
|
---|
| 351 | AutoCommit => 1, # on by default, but being explicit
|
---|
| 352 | });
|
---|
| 353 |
|
---|
| 354 | if(!$dbh) {
|
---|
| 355 | # NOTE, despite handle dbh being undefined, error code will be in DBI->err
|
---|
| 356 | return 0;
|
---|
| 357 | }
|
---|
| 358 |
|
---|
| 359 | # set encoding https://metacpan.org/pod/DBD::mysql
|
---|
| 360 | # https://dev.mysql.com/doc/refman/5.7/en/charset.html
|
---|
| 361 | # https://dev.mysql.com/doc/refman/5.7/en/charset-conversion.html
|
---|
| 362 | # Setting the encoding at db server level.
|
---|
| 363 | # Not sure if this command is mysql specific:
|
---|
| 364 | my $stmt = "set NAMES '" . $db_enc . "'";
|
---|
| 365 | $dbh->do($stmt) || warn("Unable to set charset encoding at db server level to: " . $db_enc . "\n");
|
---|
| 366 |
|
---|
| 367 | # if we're here, then connection succeeded, store handle
|
---|
| 368 | $self->{'db_handle'} = $dbh;
|
---|
| 369 | return 1;
|
---|
| 370 | }
|
---|
| 371 |
|
---|
| 372 | sub load_db_and_tables {
|
---|
| 373 | my $self= shift (@_);
|
---|
| 374 | my $db_name = $self->{'site_name'}; # one database per GS3 site
|
---|
| 375 | my $dbh = $self->{'db_handle'};
|
---|
| 376 |
|
---|
| 377 | # perl DBI switch database: https://www.perlmonks.org/?node_id=995434
|
---|
| 378 | # do() returns undef on error.
|
---|
| 379 | # connection succeeded, try to load our database. If that didn't work, attempt to create db
|
---|
| 380 | my $success = $dbh->do("use $db_name");
|
---|
| 381 |
|
---|
| 382 | if(!$success && $dbh->err == 1049) { # "Unknown database" error has code 1049 (mysql only?) meaning db doesn't exist yet
|
---|
| 383 | # attempt to create the db and its tables
|
---|
| 384 | $self->create_db($db_name) || return 0;
|
---|
| 385 |
|
---|
| 386 | # once more attempt to use db, now that it exists
|
---|
| 387 | $dbh->do("use $db_name") || return 0;
|
---|
| 388 | #$dbh->do("use localsite") or die "Error (code" . $dbh->err ."): " . $dbh->errstr . "\n";
|
---|
| 389 |
|
---|
| 390 | # attempt to create tables in current db
|
---|
| 391 | $self->create_metadata_table() || return 0;
|
---|
| 392 | $self->create_fulltext_table() || return 0;
|
---|
| 393 |
|
---|
| 394 | $success = 1;
|
---|
| 395 | }
|
---|
| 396 | elsif($success) { # database existed and loaded successfully, but
|
---|
| 397 | # before proceeding check that the current collection's tables exist
|
---|
| 398 |
|
---|
| 399 | # attempt to create tables in current db
|
---|
| 400 | if(!$self->table_exists($self->{'collection_name'} . "metadata")) {
|
---|
| 401 | $self->create_metadata_table() || return 0;
|
---|
| 402 | }
|
---|
| 403 | if(!$self->table_exists($self->{'collection_name'} . "fulltxt")) {
|
---|
| 404 | $self->create_fulltext_table() || return 0;
|
---|
| 405 | }
|
---|
| 406 | }
|
---|
| 407 |
|
---|
| 408 | return $success; # could still return 0, if database failed to load with an error code != 1049
|
---|
| 409 | }
|
---|
| 410 |
|
---|
| 411 | # disconnect from db - https://metacpan.org/pod/DBI#disconnect
|
---|
| 412 | # TODO: make sure to have committed or rolled back before disconnect
|
---|
| 413 | # and that you've call finish() on statement handles if any fetch remnants remain
|
---|
| 414 | sub disconnect_from_db {
|
---|
| 415 | my $self= shift (@_);
|
---|
| 416 | my $dbh = $self->{'db_handle'};
|
---|
| 417 |
|
---|
| 418 | # make sure any active stmt handles are finished
|
---|
| 419 | # NO: "When all the data has been fetched from a SELECT statement, the driver will automatically call finish for you. So you should not call it explicitly except when you know that you've not fetched all the data from a statement handle and the handle won't be destroyed soon."
|
---|
| 420 |
|
---|
| 421 | #$meta_sth = $self->{'metadata_prepared_insert_statement_handle'};
|
---|
| 422 | #$txt_sth = $self->{'fulltxt_prepared_insert_statement_handle'};
|
---|
| 423 | #$meta_sth->finish() if($meta_sth);
|
---|
| 424 | #$txt_sth->finish() if($txt_sth);
|
---|
| 425 |
|
---|
| 426 | my $rc = $dbh->disconnect or warn $dbh->errstr; # The handle is of little use after disconnecting. Possibly PrintError already prints a warning and this duplicates it?
|
---|
| 427 | return $rc;
|
---|
| 428 | }
|
---|
| 429 |
|
---|
| 430 | sub create_db {
|
---|
| 431 | my $self= shift (@_);
|
---|
| 432 | my $db_name = $self->{'site_name'};
|
---|
| 433 | my $dbh = $self->{'db_handle'};
|
---|
| 434 |
|
---|
| 435 | # https://stackoverflow.com/questions/5025768/how-can-i-create-a-mysql-database-from-a-perl-script
|
---|
| 436 | return $dbh->do("create database $db_name"); # do() will return undef on fail, https://metacpan.org/pod/DBI#do
|
---|
| 437 | }
|
---|
| 438 |
|
---|
| 439 | sub create_metadata_table {
|
---|
| 440 | my $self= shift (@_);
|
---|
| 441 | my $dbh = $self->{'db_handle'};
|
---|
| 442 |
|
---|
| 443 | my $table_name = $self->{'collection_name'} . "metadata";
|
---|
| 444 |
|
---|
| 445 | # If using an auto incremented primary key:
|
---|
| 446 | my $stmt = "CREATE TABLE $table_name (id INT NOT NULL AUTO_INCREMENT, did VARCHAR(63) NOT NULL, sid VARCHAR(63) NOT NULL, metaname VARCHAR(127) NOT NULL, metavalue VARCHAR(1023) NOT NULL, PRIMARY KEY(id));";
|
---|
| 447 | return $dbh->do($stmt);
|
---|
| 448 | }
|
---|
| 449 |
|
---|
| 450 | # TODO: Investigate: https://dev.mysql.com/doc/search/?d=10&p=1&q=FULLTEXT
|
---|
| 451 | # 12.9.1 Natural Language Full-Text Searches
|
---|
| 452 | # to see whether we have to index the 'fulltxt' column of the 'fulltext' tables
|
---|
| 453 | # or let user edit this file, or add it as another option
|
---|
| 454 | sub create_fulltext_table {
|
---|
| 455 | my $self= shift (@_);
|
---|
| 456 | my $dbh = $self->{'db_handle'};
|
---|
| 457 |
|
---|
| 458 | my $table_name = $self->{'collection_name'} . "fulltxt";
|
---|
| 459 |
|
---|
| 460 | # If using an auto incremented primary key:
|
---|
| 461 | my $stmt = "CREATE TABLE $table_name (id INT NOT NULL AUTO_INCREMENT, did VARCHAR(63) NOT NULL, sid VARCHAR(63) NOT NULL, fulltxt LONGTEXT, PRIMARY KEY(id));";
|
---|
| 462 | return $dbh->do($stmt);
|
---|
| 463 |
|
---|
| 464 | }
|
---|
| 465 |
|
---|
| 466 |
|
---|
| 467 | # USEFUL: https://metacpan.org/pod/DBI
|
---|
| 468 | # "Many methods have an optional \%attr parameter which can be used to pass information to the driver implementing the method. Except where specifically documented, the \%attr parameter can only be used to pass driver specific hints. In general, you can ignore \%attr parameters or pass it as undef."
|
---|
| 469 |
|
---|
| 470 |
|
---|
| 471 | # https://www.guru99.com/insert-into.html
|
---|
| 472 | # and https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html
|
---|
| 473 | # for inserting multiple rows at once
|
---|
| 474 | # https://www.perlmonks.org/bare/?node_id=316183
|
---|
| 475 | # https://metacpan.org/pod/DBI#do
|
---|
| 476 | # https://www.quora.com/What-is-the-difference-between-prepare-and-do-statements-in-Perl-while-we-make-a-connection-to-the-database-for-executing-the-query
|
---|
| 477 | # https://docstore.mik.ua/orelly/linux/dbi/ch05_05.htm
|
---|
| 478 |
|
---|
| 479 | # https://metacpan.org/pod/DBI#performance
|
---|
| 480 | # 'The q{...} style quoting used in this example avoids clashing with quotes that may be used in the SQL statement. Use the double-quote like qq{...} operator if you want to interpolate variables into the string. See "Quote and Quote-like Operators" in perlop for more details.'
|
---|
| 481 | sub prepare_insert_metadata_row_stmthandle {
|
---|
| 482 | my $self = shift (@_);
|
---|
| 483 | my ($did, $sid, $metaname, $metavalue) = @_;
|
---|
| 484 | my $dbh = $self->{'db_handle'};
|
---|
| 485 |
|
---|
| 486 | my $tablename = $self->{'colname'}."_metadata";
|
---|
| 487 |
|
---|
| 488 | #my $stmt = "INSERT INTO $tablename (did, sid, metaname, metavalue) VALUES ('$did', '$sid', '$metaname', '$metavalue');"; # ?, ?, ?, ?
|
---|
| 489 |
|
---|
| 490 | # using qq{} since we want $tablename placeholder to be filled in
|
---|
| 491 | # returns Statement Handle object!
|
---|
| 492 | my $sth = $dbh->prepare(qq{INSERT INTO $tablename (did, sid, metaname, metavalue) VALUES (?, ?, ?, ?)"}) || warn("Could not prepare insert statement for metadata table\n");
|
---|
| 493 |
|
---|
| 494 | return $sth;
|
---|
| 495 | }
|
---|
| 496 |
|
---|
| 497 | sub prepare_insert_fulltxt_row_stmthandle {
|
---|
| 498 | my $self = shift (@_);
|
---|
| 499 | my ($did, $sid, $fulltext) = @_;
|
---|
| 500 | my $dbh = $self->{'db_handle'};
|
---|
| 501 |
|
---|
| 502 | my $tablename = $self->{'colname'}."_fulltxt";
|
---|
| 503 |
|
---|
| 504 | #my $stmt = "INSERT INTO $tablename (did, sid, fulltxt) VALUES ('$did', '$sid', '$fulltext');"; ?, ?, ?
|
---|
| 505 |
|
---|
| 506 | # using qq{} since we want $tablename placeholder to be filled in
|
---|
| 507 | # returns Statement Handle object!
|
---|
| 508 | my $sth = $dbh->prepare(qq{INSERT INTO $tablename (did, sid, fulltxt) VALUES (?, ?, ?)"}) || warn("Could not prepare insert statement for fulltxt table\n");
|
---|
| 509 |
|
---|
| 510 | return $sth;
|
---|
| 511 | }
|
---|
| 512 |
|
---|
| 513 | # I can get my version of table_exists to work, but it's not so ideal
|
---|
| 514 | # Interesting that MySQL has non-standard command to CREATE TABLE IF NOT EXISTS and DROP TABLE IF EXISTS,
|
---|
| 515 | # see https://www.perlmonks.org/bare/?node=DBI%20Recipes
|
---|
| 516 | # The page further has a table_exists function that could work with proper comparison
|
---|
| 517 | # Couldn't get the first solution at https://www.perlmonks.org/bare/?node_id=500050 to work though
|
---|
| 518 | sub table_exists {
|
---|
| 519 | my ($dbh,$table_name) = @_;
|
---|
| 520 |
|
---|
| 521 | my @table_list = $dbh->tables;
|
---|
| 522 | #my $tables_str = @table_list[0];
|
---|
| 523 | foreach my $table (@table_list) {
|
---|
| 524 | return 1 if ($table =~ m/$table_name/);
|
---|
| 525 | }
|
---|
| 526 | return 0;
|
---|
| 527 | }
|
---|
| 528 |
|
---|
[32518] | 529 | 1;
|
---|