Index: main/trunk/greenstone2/perllib/plugouts/MySQLPlugout.pm
===================================================================
--- main/trunk/greenstone2/perllib/plugouts/MySQLPlugout.pm	(revision 32519)
+++ main/trunk/greenstone2/perllib/plugouts/MySQLPlugout.pm	(revision 32520)
@@ -32,5 +32,6 @@
 use util;
 use FileUtils;
-use BasePlugout;
+#use BasePlugout;
+use GreenstoneXMLPlugout;
 use docprint;
 
@@ -43,5 +44,9 @@
 }
 
+
+# TODO: deal with -removeold and everything? Or type out instructions for user
+
 # TODO Q: what is "group" in GreenstoneXMLPlugout?
+# TODO Q: site_name only exists for GS3. What about GS2?
 
 my $process_mode_list =
@@ -87,4 +92,59 @@
 }
 
+# connect here and ensure all tables and databases exist
+sub begin {
+
+    my $self= shift (@_);
+
+    ########### TODO: these should be set from cmdline/GLI options to plugout #########
+    $self->{'db_driver'} = "mysql";
+    $self->{'site_name'} = "localsite";    
+    $self->{'client_user'} = "root";
+    $self->{'client_pwd'} = "6reenstone3";
+    #$self->{'db_host'} = "127.0.0.1";
+    #$self->{'db_encoding'} = "utf8";
+    
+    ############ LOAD NECESSARY OPTIONS ###########
+    print STDERR "########## COLLECTION: ". $ENV{'GSDLCOLLECTION'}."\n";
+    $self->{'collection_name'} = $ENV{'GSDLCOLLECTION'};
+    
+    if(!$self->connect_to_db()) {
+	# This is fatal for the plugout, let's terminate here
+	# PrintError would already have displayed the warning message on connection fail	
+	die("Could not connect to db. Can't proceed.\n");
+    }
+    if(!$self->load_db_and_tables()) {
+	# This is fatal for the plugout, let's terminate here
+	# PrintError would already have displayed the warning message on connection fail	
+	die("Could not use db or prepare its tables. Can't proceed.\n");
+    }
+
+    # prepare the shared/common HANDLES to SQL insert statements that contain placeholders
+    # and which we will reuse repeatedly when executing the actual insert statements
+    my $proc_mode = $self->{'process_mode'};
+    if($proc_mode eq "all" || $proc_mode eq "meta_only" ) {
+	$self->{'metadata_prepared_insert_statement_handle'} = $self->prepare_insert_metadata_row_stmthandle();
+    }
+    if($proc_mode eq "all" || $proc_mode eq "text_only" ) {
+	$self->{'fulltxt_prepared_insert_statement_handle'} = $self->prepare_insert_fulltxt_row_stmthandle();
+    }
+    
+    # finally, call begin on super
+    $self->GreenstoneXMLPlugout::begin(@_);    
+}
+
+# disconnect from database here, see inexport.pm
+sub end
+{
+    my $self = shift(@_);
+
+    # do the superclass stuff
+    $self->GreenstoneXMLPlugout::end(@_);
+    $self->disconnect_from_db() || warn("Unable to disconnect from database " . $self->{'site_name'} . "\n");
+    #my $success = $self->GreenstoneXMLPlugout::end(@_);
+    #$success = $self->disconnect_from_db() && $success;    
+    #return $success;
+}
+    
 # TODO: check arc-inf.db for whether each entry is to be deleted/indexed/reindexed/been indexed
 sub saveas {
@@ -92,12 +152,12 @@
     my ($doc_obj, $doc_dir) = @_;
 
-    # pre
+    # pre save out
     my ($docxml_outhandler, $output_file) = $self->GreenstoneXMLPlugout::pre_saveas(@_);
-
-    
-    print STDERR "########## COLLECTION: ". $ENV{'GSDLCOLLECTION'}."\n";
-    $self->{'collection_name'} = $ENV{'GSDLCOLLECTION'};
-    # set up DB and table or connect to DB and access the table here?
-    
+    
+
+    # saving customisation
+    $self->{'debug_outhandle'} = $docxml_outhandler if ($self->{'debug'}); # STDOUT if debug
+
+    # write the INVERSE into doc.xml as to what is written to the db
     my $proc_mode = $self->{'process_mode'};
     my $docxml_output_options = { 'output' => docprint::OUTPUT_NONE };
@@ -117,5 +177,6 @@
     $self->write_meta_and_text($doc_obj);
 
-    # post
+    
+    # post save out
     $self->GreenstoneXMLPlugout::post_saveas(@_);
 
@@ -125,16 +186,25 @@
 
 
-# write meta and/or text out to DB
+# write meta and/or text PER DOC out to DB
 sub write_meta_and_text {
     my $self = shift (@_);
     my ($doc_obj) = @_;
     my $root_section = $doc_obj->get_top_section();
-
-    # Do we don't want to open and close a connection per doc?
+    my $doc_oid = $doc_obj->get_OID(); # we're processing a single doc at a time, so single OID
+
+    ##binmode($db_handle,":utf8"); ## WRONG FOR DB, NEED TO CREATE IN UTF8 MODE
+    
+    # TODO if $self->debug is on
+    
+    # Do we want to open and close a connection per doc?
     # Would we not rather want to open and close per collection rebuild?
     
     #$self->create_db_connection();
-    
-    $self->recursive_write_meta_and_text($doc_obj, $root_section);
+
+    # 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)
+    my $metadata_table_sth = $self->{'metadata_prepared_insert_statement_handle'};
+    my $fulltxt_table_sth = $self->{'fulltxt_prepared_insert_statement_handle'};
+    
+    $self->recursive_write_meta_and_text($doc_obj, $root_section, $metadata_table_sth, $fulltxt_table_sth);
 
     #$self->close_db_connection();
@@ -143,32 +213,65 @@
 # https://nnc3.com/mags/Perl3/cookbook/ch16_05.htm
 sub recursive_write_meta_and_text {
-    my ($doc_obj, $section) = @_;
-    
-    # TODO
-    my $db_outhandler = undef;
-    binmode($db_outhandler,":utf8");
-    # TODO if $self->debug is on
+    my $self = shift (@_);
+    my ($doc_obj, $doc_oid, $section, $metadata_table_sth, $fulltxt_table_sth) = @_;    
+
+    # If section=ROOT, write "root" as section name into table
+    # doc->get_top_section() is the name of the doc root section, which is ""
+    my $section_name = ($section eq "") ? "root" : $section;
     
     my $section_ptr = $doc_obj->_lookup_section ($section);
     return "" unless defined $section_ptr;
 
-    my $proc_mode = $self->{'process_mode'};
-
-    if($proc_mode eq "all" || $proc_mode eq "meta_only" ) {
+    my $debug_out = $self->{'debug_outhandle'};
+    
+    #my $proc_mode = $self->{'process_mode'};
+    #if($proc_mode eq "all" || $proc_mode eq "meta_only" ) {
+    if($metadata_table_sth) { # meta insert statement handle will be undef if not writing meta
+	
 	foreach my $data (@{$section_ptr->{'metadata'}}) {
-	    my $escaped_value = &escape_text($data->[1]);
-	    my $metaval = $data->[0];
-	    # TODO: write out current section's text to collection db's META table
+	    my $meta_name = $data->[0];
+	    my $escaped_meta_value = &escape_text($data->[1]);
+
+	    # Write out the current section's meta to collection db's METADATA table	    
+	    
+	    # for each set of values to write to meta table, execute the prepared statement, filling in the values
+
+	    if($self->{'debug'}) {
+		# just print the statement we were going to execute
+
+		print $debug_out $metadata_table_sth->Statement . "($doc_oid, $section_name, $meta_name, $escaped_meta_value)\n";
+	    }
+	    else {
+	    
+		$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");
+		# Execution failure will print out info anyway: since db connection sets PrintError
+	    }
 	}
     }
-    if($proc_mode eq "all" || $proc_mode eq "text_only" ) {
-	my $section_text = &escape_text($section_ptr->{'text'});
-	# TODO: write out current section's text to collection db's TEXT table
-	
+    
+    #if($proc_mode eq "all" || $proc_mode eq "text_only" ) {
+    if($fulltxt_table_sth) { # fulltxt insert statement handle will be undef if not writing fulltxt
+
+	if($self->{'debug'}) {
+	    # just print the statement we were going to execute, minus the fulltxt value
+	    my $txt_repr = $section_ptr->{'text'} ? "<TXT>" : "NULL";
+	    print $debug_out $fulltxt_table_sth->Statement . "($doc_oid, $section_name, $txt_repr)\n";
+	} else {
+	    my $section_text = &escape_text($section_ptr->{'text'});
+	    
+	    # fulltxt column can be SQL NULL. undef value gets written out as NULL:
+	    # https://stackoverflow.com/questions/12708633/which-one-represents-null-undef-or-empty-string
+		
+	    # Write out the current section's text to collection db's FULLTeXT table
+	    $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");
+	    # Execution failure will print out info anyway: since db connection sets PrintError
+	}
     }
     
     # output all subsections: RECURSIVE CALL
     foreach my $subsection (@{$section_ptr->{'subsection_order'}}) {
-	&recursive_write_meta_and_text($doc_obj, "$section.$subsection");
+	&recursive_write_meta_and_text($doc_obj, $doc_oid, "$section.$subsection", $metadata_table_sth, $fulltxt_table_sth);
     }
 }
@@ -185,6 +288,6 @@
 # BUT what if the table is HUGE? (Think of a collection with millions of docs.) Huge overhead in copying?
 # 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.
-# Unless they do a full rebuild, which will recreate the tab;e from scratch?
-  
+# Unless they do a full rebuild, which will recreate the table from scratch?
+# SOLUTION-> rollback transaction on error, see https://www.effectiveperlprogramming.com/2010/07/set-custom-dbi-error-handlers/
 
 # I'm using perl's open2 like in Z3950Download, as opposed to open3 like in WgetDownload
@@ -216,4 +319,5 @@
     my ($self,$expected) = @_;
 
+    my $out = $self->{'MYSQL_OUT'};
     my $opening_line = <$out>;
     if ($opening_line =~ m/$expected/i) {
@@ -227,4 +331,5 @@
 
     my $found_expected = 0;
+    my $out = $self->{'MYSQL_OUT'};
     while (my $line = <$out>) {
 	print STDERR "$line\n";
@@ -251,5 +356,5 @@
     
     
-    my $launch_cmd = "\"./$mysql_client\" -u $clientuser -p";
+    my $launch_cmd = "\"./$mysql_client\" -u $client_user -p";
     my $childpid = open2(*MYSQL_OUT, *MYSQL_IN, $launch_cmd)
 	or (print STDERR "Done\n" and die "can't open2 pipe to mysql client: $!");
@@ -277,6 +382,7 @@
 	return $self->load_db();
     }    
-    
-    return $conn_open; # 1 if client already quit after pwd fail, 0 if load_db failed (needs to be quit), 1 if load_db succeeded (mysql client still running)
+
+    # return $conn_open;
+    return $conn_success; # 1 if client already quit after pwd fail, 0 if load_db failed (needs to be quit), 1 if load_db succeeded (mysql client still running)
 }
 
@@ -339,5 +445,5 @@
     
     if($self->response_line_contains("Access denied")) {
-	print STDERR "Password not recognised. Got: $opening_line\n";
+	print STDERR "Password not recognised. Got: Access denied.\n";
 	return 0;
     }
@@ -356,4 +462,5 @@
     
     my $db_found = 0;
+    my $out = $self->{'MYSQL_OUT'};
     while (my $line = <$out>) {
 	print STDERR "$line\n";
@@ -374,7 +481,9 @@
 
 	# attempt to load the newly created db
-	if($self->_load_db()) {
+	if($self->_load_db()) { # recursive call!
 	    return 1;
 	}
+	
+	
 	#my $opening_line = <$out>;
 	#if ($opening_line !~ m/Query OK/) {
@@ -437,8 +546,8 @@
     my $self = shift (@_);
     my ($did, $sid, $metaname, $metavalue) = @_;
-    my $tablename = $self->{'colname'}_"metadata";
+    my $tablename = $self->{'colname'}."_metadata";
 
     my $cmd = "INSERT INTO $tablename (did, sid, metaname, metavalue) VALUES\n";
-    $cmd = "('$did', '$sid', '$metaname', '$metavalue');\n";
+    $cmd .= "('$did', '$sid', '$metaname', '$metavalue');\n";
     return $cmd;
 }
@@ -447,8 +556,8 @@
     my $self = shift (@_);
     my ($did, $sid, $fulltext) = @_;
-    my $tablename = $self->{'colname'}_"fulltxt";
+    my $tablename = $self->{'colname'}."_fulltxt";
 
     my $cmd = "INSERT INTO $tablename (did, sid, fulltxt) VALUES\n";
-    $cmd = "('$did', '$sid', '$fulltext');\n";
+    $cmd .= "('$did', '$sid', '$fulltext');\n";
     return $cmd;
 }
@@ -461,4 +570,5 @@
 sub X_open_connection()
 {
+    my $self = shift (@_);
     # connect with pwd
     my $conn_success = $self->send_pwd();
@@ -470,9 +580,221 @@
 	return $self->load_db();
     } else {
-	return $conn_sucess;
+	return $conn_success;
     }
 }
 
 #################
+# Database functions that use the perl DBI module (with the DBD driver module for mysql)
+#################
+
+# THE NEW DB FUNCTIONS
+# NOTE: FULLTEXT is a reserved keyword in (My)SQL. So we can't name a table or any of its columns "fulltext".
+# https://dev.mysql.com/doc/refman/5.5/en/keywords.html
+
+# TODO: Consider AutoCommit status (and Autocommit off allowing commit or rollback for GS coll build cancel) later
+
+sub connect_to_db {
+    my $self= shift (@_);
+    
+    my $db_driver = $self->{'db_driver'};
+    my $db_user = $self->{'client_user'} || "root";
+    my $db_pwd = $self->{'client_pwd'};
+    my $db_host = $self->{'db_host'} || "127.0.0.1";
+    my $db_enc = $self->{'db_encoding'} || "utf8";
+    
+    #my $db_name = $self->{'site_name'};
+    
+    # try connecting to the mysql db, if that fails it will die
+    # so don't bother preparing GreenstoneXMLPlugout by calling superclass' begin()
+
+    # localhost doesn't work for us, but 127.0.0.1 works
+    # https://metacpan.org/pod/DBD::mysql
+    # "The hostname, if not specified or specified as '' or 'localhost', will default to a MySQL server
+    # running on the local machine using the default for the UNIX socket. To connect to a MySQL server
+    # on the local machine via TCP, you must specify the loopback IP address (127.0.0.1) as the host."
+    #my $connect_str = "dbi:$db_driver:database=$db_name;host=$db_host";
+    my $connect_str = "dbi:$db_driver:host=$db_host"; # don't provide db, so we can check the db is there
+    my $dbh = DBI->connect("$connect_str", $db_user, $db_pwd,
+			   {
+			       ShowErrorStatement => 1, # more informative as DBI will append failed SQL stmt to error message
+			       PrintError => 1, # on by default, but being explicit
+			       RaiseError => 0, # off by default, but being explicit
+			       AutoCommit => 1, # on by default, but being explicit
+			   });
+
+    if(!$dbh) {
+	# NOTE, despite handle dbh being undefined, error code will be in DBI->err
+	return 0;	
+    }
+
+    # set encoding https://metacpan.org/pod/DBD::mysql
+    # https://dev.mysql.com/doc/refman/5.7/en/charset.html
+    # https://dev.mysql.com/doc/refman/5.7/en/charset-conversion.html
+    # Setting the encoding at db server level.
+    # Not sure if this command is mysql specific:
+    my $stmt = "set NAMES '" . $db_enc . "'";
+    $dbh->do($stmt) || warn("Unable to set charset encoding at db server level to: " . $db_enc . "\n");
+    
+    # if we're here, then connection succeeded, store handle
+    $self->{'db_handle'} = $dbh;
+    return 1;
+}
+
+sub load_db_and_tables {
+    my $self= shift (@_);
+    my $db_name = $self->{'site_name'}; # one database per GS3 site
+    my $dbh = $self->{'db_handle'};
+    
+    # perl DBI switch database: https://www.perlmonks.org/?node_id=995434
+    # do() returns undef on error.
+    # connection succeeded, try to load our database. If that didn't work, attempt to create db
+    my $success = $dbh->do("use $db_name");
+    
+    if(!$success && $dbh->err == 1049) { # "Unknown database" error has code 1049 (mysql only?) meaning db doesn't exist yet
+	# attempt to create the db and its tables
+	$self->create_db($db_name) || return 0;
+
+	# once more attempt to use db, now that it exists
+	$dbh->do("use $db_name") || return 0;
+	#$dbh->do("use localsite") or die "Error (code" . $dbh->err ."): " . $dbh->errstr . "\n";
+
+	# attempt to create tables in current db
+	$self->create_metadata_table() || return 0;
+	$self->create_fulltext_table() || return 0;	
+
+	$success = 1;
+    }
+    elsif($success) { # database existed and loaded successfully, but
+	# before proceeding check that the current collection's tables exist
+	
+	# attempt to create tables in current db
+	if(!$self->table_exists($self->{'collection_name'} . "metadata")) {
+	    $self->create_metadata_table() || return 0;
+	}
+	if(!$self->table_exists($self->{'collection_name'} .  "fulltxt")) {
+	    $self->create_fulltext_table() || return 0;
+	}
+    }
+    
+    return $success; # could still return 0, if database failed to load with an error code != 1049
+}
+
+# disconnect from db - https://metacpan.org/pod/DBI#disconnect
+# TODO: make sure to have committed or rolled back before disconnect
+# and that you've call finish() on statement handles if any fetch remnants remain
+sub disconnect_from_db {
+    my $self= shift (@_);    
+    my $dbh = $self->{'db_handle'};
+
+    # make sure any active stmt handles are finished
+    # 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."
+    
+    #$meta_sth = $self->{'metadata_prepared_insert_statement_handle'};
+    #$txt_sth = $self->{'fulltxt_prepared_insert_statement_handle'};
+    #$meta_sth->finish() if($meta_sth);
+    #$txt_sth->finish() if($txt_sth);
+    
+    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?
+    return $rc;
+}
+
+sub create_db {
+    my $self= shift (@_);
+    my $db_name = $self->{'site_name'};
+    my $dbh = $self->{'db_handle'};
+    
+    # https://stackoverflow.com/questions/5025768/how-can-i-create-a-mysql-database-from-a-perl-script
+    return $dbh->do("create database $db_name"); # do() will return undef on fail, https://metacpan.org/pod/DBI#do
+}
+
+sub create_metadata_table {
+    my $self= shift (@_);
+    my $dbh = $self->{'db_handle'};
+    
+    my $table_name = $self->{'collection_name'} . "metadata";
+
+    # If using an auto incremented primary key:
+    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));";
+    return $dbh->do($stmt);
+}
+
+# TODO: Investigate: https://dev.mysql.com/doc/search/?d=10&p=1&q=FULLTEXT
+# 12.9.1 Natural Language Full-Text Searches
+# to see whether we have to index the 'fulltxt' column of the 'fulltext' tables
+# or let user edit this file, or add it as another option
+sub create_fulltext_table {
+    my $self= shift (@_);
+    my $dbh = $self->{'db_handle'};
+    
+    my $table_name = $self->{'collection_name'} . "fulltxt";
+
+    # If using an auto incremented primary key:
+    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));";
+    return $dbh->do($stmt);
+
+}
+
+
+# USEFUL: https://metacpan.org/pod/DBI
+# "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."
+
+
+# https://www.guru99.com/insert-into.html
+# and https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html
+#     for inserting multiple rows at once
+# https://www.perlmonks.org/bare/?node_id=316183
+# https://metacpan.org/pod/DBI#do
+# 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
+# https://docstore.mik.ua/orelly/linux/dbi/ch05_05.htm
+
+# https://metacpan.org/pod/DBI#performance
+# '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.'
+sub prepare_insert_metadata_row_stmthandle {
+    my $self = shift (@_);    
+    my ($did, $sid, $metaname, $metavalue) = @_;
+    my $dbh = $self->{'db_handle'};
+    
+    my $tablename = $self->{'colname'}."_metadata";
+
+    #my $stmt = "INSERT INTO $tablename (did, sid, metaname, metavalue) VALUES ('$did', '$sid', '$metaname', '$metavalue');"; # ?, ?, ?, ?
+
+    # using qq{} since we want $tablename placeholder to be filled in
+    # returns Statement Handle object!
+    my $sth = $dbh->prepare(qq{INSERT INTO $tablename (did, sid, metaname, metavalue) VALUES (?, ?, ?, ?)"}) || warn("Could not prepare insert statement for metadata table\n");
+    
+    return $sth;
+}
+
+sub prepare_insert_fulltxt_row_stmthandle {
+    my $self = shift (@_);
+    my ($did, $sid, $fulltext) = @_;
+    my $dbh = $self->{'db_handle'};
+    
+    my $tablename = $self->{'colname'}."_fulltxt";
+
+    #my $stmt = "INSERT INTO $tablename (did, sid, fulltxt) VALUES ('$did', '$sid', '$fulltext');"; ?, ?, ?
+
+    # using qq{} since we want $tablename placeholder to be filled in
+    # returns Statement Handle object!
+    my $sth = $dbh->prepare(qq{INSERT INTO $tablename (did, sid, fulltxt) VALUES (?, ?, ?)"}) || warn("Could not prepare insert statement for fulltxt table\n");
+    
+    return $sth;
+}
+
+# I can get my version of table_exists to work, but it's not so ideal
+# Interesting that MySQL has non-standard command to CREATE TABLE IF NOT EXISTS and DROP TABLE IF EXISTS, 
+# see https://www.perlmonks.org/bare/?node=DBI%20Recipes
+#    The page further has a table_exists function that could work with proper comparison
+# Couldn't get the first solution at https://www.perlmonks.org/bare/?node_id=500050 to work though
+sub table_exists {
+    my ($dbh,$table_name) = @_;
+
+    my @table_list = $dbh->tables;
+    #my $tables_str = @table_list[0];
+    foreach my $table (@table_list) {
+	return 1 if ($table =~ m/$table_name/);
+    }
+    return 0;
+}
 
 1;
