Annotation of loncom/interface/lonmysql.pm, revision 1.35

1.1       matthew     1: # The LearningOnline Network with CAPA
                      2: # MySQL utility functions
                      3: #
1.35    ! matthew     4: # $Id: lonmysql.pm,v 1.34 2005/08/24 19:21:05 matthew Exp $
1.1       matthew     5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA 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: # LON-CAPA 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 LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
                     28: ######################################################################
                     29: 
                     30: package Apache::lonmysql;
                     31: 
                     32: use strict;
                     33: use DBI;
1.16      www        34: use POSIX qw(strftime mktime);
1.29      albertel   35: use Apache::lonnet;
1.16      www        36: 
1.21      matthew    37: my $mysqluser;
                     38: my $mysqlpassword;
1.27      matthew    39: my $mysqldatabase;
1.33      matthew    40: my %db_config;
1.21      matthew    41: 
                     42: sub set_mysql_user_and_password {
                     43:     # If we are running under Apache and LONCAPA, use the LON-CAPA 
                     44:     # user and password.  Otherwise...? ? ? ?
1.27      matthew    45:     my ($input_mysqluser,$input_mysqlpassword,$input_mysqldatabase) = @_;
                     46:     if (! defined($mysqldatabase)) {
                     47:         $mysqldatabase = 'loncapa';
                     48:     }
                     49:     if (defined($input_mysqldatabase)) {
                     50:         $mysqldatabase = $input_mysqldatabase;
                     51:     }
1.21      matthew    52:     if (! defined($mysqluser) || ! defined($mysqlpassword)) {
                     53:         if (! eval 'require Apache::lonnet();') {
                     54:             $mysqluser = 'www';
                     55:             $mysqlpassword = $Apache::lonnet::perlvar{'lonSqlAccess'};
                     56:         } else {
1.22      matthew    57:             $mysqluser = '';
1.21      matthew    58:             $mysqlpassword = '';
                     59:         }
                     60:     }
1.27      matthew    61:     if (defined($input_mysqluser)) {
                     62:         $mysqluser = $input_mysqluser;
                     63:     } 
                     64:     if (defined($input_mysqlpassword)) {
                     65:         $mysqlpassword = $input_mysqlpassword;
                     66:     }
1.21      matthew    67: }
1.1       matthew    68: 
                     69: ######################################################################
                     70: ######################################################################
                     71: 
                     72: =pod 
                     73: 
                     74: =head1 Name
                     75: 
                     76: lonmysql - LONCAPA MySQL utility functions
                     77: 
                     78: =head1 Synopsis
                     79: 
                     80: lonmysql contains utility functions to make accessing the mysql loncapa
                     81: database easier.  
                     82: 
                     83: =head1 Description
                     84: 
                     85: lonmysql does its best to encapsulate all the database/table functions
                     86: and provide a common interface.  The goal, however, is not to provide 
                     87: a complete reimplementation of the DBI interface.  Instead we try to 
                     88: make using mysql as painless as possible.
                     89: 
                     90: Each table has a numeric ID that is a parameter to most lonmysql functions.
                     91: The table id is returned by &create_table.  
                     92: If you lose the table id, it is lost forever.
                     93: The table names in MySQL correspond to 
1.29      albertel   94: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.$table_id.  If the table id 
1.1       matthew    95: is non-numeric, it is assumed to be the full name of a table.  If you pass
                     96: the table id in a form, you MUST ensure that what you send to lonmysql is
                     97: numeric, otherwise you are opening up all the tables in the MySQL database.
                     98: 
                     99: =over 4
                    100: 
                    101: =item Creating a table
                    102: 
                    103: To create a table, you need a description of its structure.  See the entry
                    104: for &create_table for a description of what is needed.
                    105: 
                    106:  $table_id = &create_table({ 
1.9       matthew   107:      id      => 'tableid',      # usually you will use the returned id
                    108:      columns => (
                    109:                  { name => 'id',
                    110:                    type => 'INT',
                    111:                    restrictions => 'NOT NULL',
                    112:                    primary_key => 'yes',
                    113:                    auto_inc    => 'yes'
                    114:                    },
                    115:                  { name => 'verbage',
                    116:                    type => 'TEXT' },
                    117:                  ),
                    118:                        fulltext => [qw/verbage/],
1.3       matthew   119:         });
1.1       matthew   120: 
                    121: The above command will create a table with two columns, 'id' and 'verbage'.
                    122: 
                    123: 'id' will be an integer which is autoincremented and non-null.
                    124: 
                    125: 'verbage' will be of type 'TEXT', which (conceivably) allows any length
                    126: text string to be stored.  Depending on your intentions for this database,
                    127: setting restrictions => 'NOT NULL' may help you avoid storing empty data.
                    128: 
1.3       matthew   129: the fulltext element sets up the 'verbage' column for 'FULLTEXT' searching.
1.1       matthew   130: 
                    131: 
                    132: 
                    133: =item Storing rows
                    134: 
                    135: Storing a row in a table requires calling &store_row($table_id,$data)
                    136: 
                    137: $data is either a hash reference or an array reference.  If it is an array
                    138: reference, the data is passed as is (after being escaped) to the 
                    139: "INSERT INTO <table> VALUES( ... )" SQL command.  If $data is a hash reference,
                    140: the data will be placed into an array in the proper column order for the table
                    141: and then passed to the database.
                    142: 
                    143: An example of inserting into the table created above is:
                    144: 
                    145: &store_row($table_id,[undef,'I am not a crackpot!']);
                    146: 
                    147: or equivalently,
                    148: 
                    149: &store_row($table_id,{ verbage => 'I am not a crackpot!'});
                    150: 
                    151: Since the above table was created with the first column ('id') as 
                    152: autoincrement, providing a value is unnecessary even though the column was
                    153: marked as 'NOT NULL'.
                    154: 
                    155: 
                    156: 
                    157: =item Retrieving rows
                    158: 
                    159: Retrieving rows requires calling get_rows:
                    160: 
                    161: @row = &Apache::lonmysql::get_rows($table_id,$condition)
                    162: 
                    163: This results in the query "SELECT * FROM <table> HAVING $condition".
                    164: 
                    165: @row = &Apache::lonmysql::get_rows($table_id,'id>20'); 
                    166: 
                    167: returns all rows with column 'id' greater than 20.
                    168: 
                    169: =back
                    170: 
                    171: =cut
                    172: 
                    173: ######################################################################
                    174: ######################################################################
                    175: =pod
                    176: 
                    177: =head1 Package Variables
                    178: 
                    179: =over 4
                    180: 
                    181: =cut
                    182: 
                    183: ##################################################
                    184: ##################################################
                    185: 
                    186: =pod
                    187: 
                    188: =item %Tables
                    189: 
                    190: Holds information regarding the currently open connections.  Each key
                    191: in the %Tables hash will be a unique table key.  The value associated 
                    192: with a key is a hash reference.  Most values are initialized when the 
                    193: table is created.
                    194: 
                    195: The following entries are allowed in the hash reference:
                    196: 
                    197: =over 4
                    198: 
1.3       matthew   199: =item Name
                    200: 
                    201: Table name.
                    202: 
                    203: =item Type            
                    204: 
                    205: The type of table, typically MyISAM.
                    206: 
                    207: =item Row_format
                    208: 
                    209: Describes how rows should be stored in the table.  DYNAMIC or STATIC.
                    210: 
                    211: =item Create_time
                    212: 
                    213: The date of the tables creation.
                    214: 
                    215: =item Update_time
                    216: 
                    217: The date of the last modification of the table.
                    218: 
                    219: =item Check_time
                    220: 
                    221: Usually NULL. 
                    222: 
                    223: =item Avg_row_length
                    224: 
                    225: The average length of the rows.
                    226: 
                    227: =item Data_length
                    228: 
                    229: The length of the data stored in the table (bytes)
                    230: 
                    231: =item Max_data_length
                    232: 
                    233: The maximum possible size of the table (bytes).
1.1       matthew   234: 
1.3       matthew   235: =item Index_length
1.1       matthew   236: 
1.3       matthew   237: The length of the index for the table (bytes)
1.1       matthew   238: 
1.3       matthew   239: =item Data_free
1.1       matthew   240: 
1.3       matthew   241: I have no idea what this is.
1.1       matthew   242: 
1.3       matthew   243: =item Comment 
1.1       matthew   244: 
1.3       matthew   245: The comment associated with the table.
                    246: 
                    247: =item Rows
                    248: 
                    249: The number of rows in the table.
                    250: 
                    251: =item Auto_increment
                    252: 
                    253: The value of the next auto_increment field.
                    254: 
                    255: =item Create_options
                    256: 
                    257: I have no idea.
                    258: 
                    259: =item Col_order
                    260: 
                    261: an array reference which holds the order of columns in the table.
                    262: 
                    263: =item row_insert_sth 
1.1       matthew   264: 
                    265: The statement handler for row inserts.
                    266: 
1.9       matthew   267: =item row_replace_sth 
                    268: 
                    269: The statement handler for row inserts.
                    270: 
1.1       matthew   271: =back
                    272: 
1.3       matthew   273: Col_order and row_insert_sth are kept internally by lonmysql and are not
                    274: part of the usual MySQL table information.
                    275: 
1.1       matthew   276: =cut
                    277: 
                    278: ##################################################
                    279: ##################################################
                    280: my %Tables;
                    281: 
                    282: ##################################################
                    283: ##################################################
                    284: =pod
                    285: 
                    286: =item $errorstring
                    287: 
                    288: Holds the last error.
                    289: 
                    290: =cut
                    291: ##################################################
                    292: ##################################################
                    293: my $errorstring;
                    294: 
                    295: ##################################################
                    296: ##################################################
                    297: =pod
                    298: 
                    299: =item $debugstring
                    300: 
                    301: Describes current events within the package.
                    302: 
                    303: =cut
                    304: ##################################################
                    305: ##################################################
                    306: my $debugstring;
                    307: 
                    308: ##################################################
                    309: ##################################################
                    310: 
                    311: =pod
                    312: 
                    313: =item $dbh
                    314: 
                    315: The database handler; The actual connection to MySQL via the perl DBI.
                    316: 
                    317: =cut
                    318: 
                    319: ##################################################
                    320: ##################################################
                    321: my $dbh;
                    322: 
                    323: ##################################################
                    324: ##################################################
                    325: 
                    326: # End of global variable declarations
                    327: 
                    328: =pod
                    329: 
                    330: =back
                    331: 
                    332: =cut
                    333: 
                    334: ######################################################################
                    335: ######################################################################
                    336: 
                    337: =pod
                    338: 
                    339: =head1 Internals
                    340: 
                    341: =over 4
                    342: 
                    343: =cut
                    344: 
                    345: ######################################################################
                    346: ######################################################################
                    347: 
                    348: =pod
                    349: 
                    350: =item &connect_to_db()
                    351: 
                    352: Inputs: none.  
                    353: 
                    354: Returns: undef on error, 1 on success.
                    355: 
                    356: Checks to make sure the database has been connected to.  If not, the
                    357: connection is established.  
                    358: 
                    359: =cut
                    360: 
                    361: ###############################
                    362: sub connect_to_db { 
                    363:     return 1 if ($dbh);
1.21      matthew   364:     if (! defined($mysqluser) || ! defined($mysqlpassword)) {
                    365:         &set_mysql_user_and_password();
                    366:     }
1.27      matthew   367:     if (! ($dbh = DBI->connect("DBI:mysql:$mysqldatabase",$mysqluser,$mysqlpassword,
1.1       matthew   368:                                { RaiseError=>0,PrintError=>0}))) {
                    369:         $debugstring = "Unable to connect to loncapa database.";    
1.7       matthew   370:         if (! defined($dbh)) {
                    371:             $debugstring = "Unable to connect to loncapa database.";
                    372:             $errorstring = "dbh was undefined.";
                    373:         } elsif ($dbh->err) {
1.1       matthew   374:             $errorstring = "Connection error: ".$dbh->errstr;
                    375:         }
                    376:         return undef;
                    377:     }
                    378:     $debugstring = "Successfully connected to loncapa database.";    
1.33      matthew   379:     # Determine DB configuration
                    380:     undef(%db_config);
                    381:     my $sth = $dbh->prepare("SHOW VARIABLES");
                    382:     $sth->execute();
                    383:     if ($sth->err()) {
                    384:         $debugstring = "Unable to retrieve db config variables";
                    385:         return undef;
                    386:     }
                    387:     foreach my $row (@{$sth->fetchall_arrayref}) {
                    388:         $db_config{$row->[0]} = $row->[1];
                    389:     }
1.34      matthew   390:     #&Apache::lonnet::logthis("MySQL configuration variables");
                    391:     #while (my ($k,$v) = each(%db_config)) {
                    392:     #    &Apache::lonnet::logthis("    '$k' => '$v'");
                    393:     #}
1.33      matthew   394:     #
1.13      matthew   395:     return 1;
                    396: }
                    397: 
                    398: ###############################
                    399: 
                    400: =pod
                    401: 
                    402: =item &verify_sql_connection()
                    403: 
                    404: Inputs: none.
                    405: 
                    406: Returns: 0 (failure) or 1 (success)
                    407: 
                    408: Checks to make sure the database can be connected to.  It does not
                    409: initialize anything in the lonmysql package.
                    410: 
                    411: =cut
                    412: 
                    413: ###############################
                    414: sub verify_sql_connection {
1.21      matthew   415:     if (! defined($mysqluser) || ! defined($mysqlpassword)) {
                    416:         &set_mysql_user_and_password();
                    417:     }
1.13      matthew   418:     my $connection;
1.21      matthew   419:     if (! ($connection = DBI->connect("DBI:mysql:loncapa",
                    420:                                       $mysqluser,$mysqlpassword,
1.13      matthew   421:                                       { RaiseError=>0,PrintError=>0}))) {
                    422:         return 0;
                    423:     }
                    424:     undef($connection);
1.1       matthew   425:     return 1;
                    426: }
                    427: 
                    428: ###############################
                    429: 
                    430: =pod
                    431: 
                    432: =item &disconnect_from_db()
                    433: 
                    434: Inputs: none.
                    435: 
                    436: Returns: Always returns 1.
                    437: 
                    438: Severs the connection to the mysql database.
                    439: 
                    440: =cut
                    441: 
                    442: ###############################
                    443: sub disconnect_from_db { 
                    444:     foreach (keys(%Tables)) {
                    445:         # Supposedly, having statement handlers running around after the
                    446:         # database connection has been lost will cause trouble.  So we 
                    447:         # kill them off just to be sure.
                    448:         if (exists($Tables{$_}->{'row_insert_sth'})) {
                    449:             delete($Tables{$_}->{'row_insert_sth'});
                    450:         }
1.9       matthew   451:         if (exists($Tables{$_}->{'row_replace_sth'})) {
                    452:             delete($Tables{$_}->{'row_replace_sth'});
                    453:         }
1.1       matthew   454:     }
                    455:     $dbh->disconnect if ($dbh);
                    456:     $debugstring = "Disconnected from database.";
                    457:     $dbh = undef;
                    458:     return 1;
                    459: }
                    460: 
                    461: ###############################
                    462: 
                    463: =pod
                    464: 
1.2       matthew   465: =item &number_of_rows()
1.1       matthew   466: 
1.2       matthew   467: Input: table identifier
                    468: 
1.3       matthew   469: Returns: the number of rows in the given table, undef on error.
1.1       matthew   470: 
                    471: =cut
                    472: 
                    473: ###############################
1.2       matthew   474: sub number_of_rows { 
                    475:     my ($table_id) = @_;
1.3       matthew   476:     return undef if (! defined(&connect_to_db()));
                    477:     return undef if (! defined(&update_table_info($table_id)));
                    478:     return $Tables{&translate_id($table_id)}->{'Rows'};
1.10      matthew   479: }
                    480: ###############################
                    481: 
                    482: =pod
                    483: 
                    484: =item &get_dbh()
                    485: 
                    486: Input: nothing
                    487: 
                    488: Returns: the database handler, or undef on error.
                    489: 
                    490: This routine allows the programmer to gain access to the database handler.
                    491: Be careful.
                    492: 
                    493: =cut
                    494: 
                    495: ###############################
                    496: sub get_dbh { 
                    497:     return undef if (! defined(&connect_to_db()));
                    498:     return $dbh;
1.1       matthew   499: }
                    500: 
                    501: ###############################
                    502: 
                    503: =pod
                    504: 
                    505: =item &get_error()
                    506: 
                    507: Inputs: none.
                    508: 
                    509: Returns: The last error reported.
                    510: 
                    511: =cut
                    512: 
                    513: ###############################
                    514: sub get_error {
                    515:     return $errorstring;
                    516: }
                    517: 
                    518: ###############################
                    519: 
                    520: =pod
                    521: 
                    522: =item &get_debug()
                    523: 
                    524: Inputs: none.
                    525: 
                    526: Returns: A string describing the internal state of the lonmysql package.
                    527: 
                    528: =cut
                    529: 
                    530: ###############################
                    531: sub get_debug {
                    532:     return $debugstring;
                    533: }
                    534: 
                    535: ###############################
                    536: 
                    537: =pod
                    538: 
1.8       matthew   539: =item &update_table_info()
1.1       matthew   540: 
                    541: Inputs: table id
                    542: 
1.3       matthew   543: Returns: undef on error, 1 on success.
1.1       matthew   544: 
1.3       matthew   545: &update_table_info updates the %Tables hash with current information about
                    546: the given table.  
                    547: 
                    548: The default MySQL table status fields are:
1.1       matthew   549: 
                    550:    Name             Type            Row_format
                    551:    Max_data_length  Index_length    Data_free
                    552:    Create_time      Update_time     Check_time
                    553:    Avg_row_length   Data_length     Comment 
                    554:    Rows             Auto_increment  Create_options
                    555: 
1.3       matthew   556: Additionally, "Col_order" is updated as well.
                    557: 
1.1       matthew   558: =cut
                    559: 
                    560: ###############################
1.3       matthew   561: sub update_table_info { 
1.1       matthew   562:     my ($table_id) = @_;
1.3       matthew   563:     return undef if (! defined(&connect_to_db()));
                    564:     my $table_status = &check_table($table_id);
                    565:     return undef if (! defined($table_status));
                    566:     if (! $table_status) {
                    567:         $errorstring = "table $table_id does not exist.";
                    568:         return undef;
                    569:     }
1.1       matthew   570:     my $tablename = &translate_id($table_id);
1.3       matthew   571:     #
                    572:     # Get MySQLs table status information.
                    573:     #
1.1       matthew   574:     my $db_command = "SHOW TABLE STATUS FROM loncapa LIKE '$tablename'";
                    575:     my $sth = $dbh->prepare($db_command);
                    576:     $sth->execute();
                    577:     if ($sth->err) {
                    578:         $errorstring = "$dbh ATTEMPTED:\n".$db_command."\nRESULTING ERROR:\n".
                    579:             $sth->errstr;
1.3       matthew   580:         &disconnect_from_db();
1.1       matthew   581:         return undef;
                    582:     }
1.35    ! matthew   583:     my @column_name = @{$sth->{NAME}};
1.1       matthew   584:     #
                    585:     my @info=$sth->fetchrow_array;
                    586:     for (my $i=0;$i<= $#info ; $i++) {
1.35    ! matthew   587:         if ($column_name[$i] =~ /^(Create_|Update_|Check_)time$/) {
        !           588:             $Tables{$tablename}->{$column_name[$i]}= 
1.25      matthew   589:                 &unsqltime($info[$i]);
                    590:         } else {
1.35    ! matthew   591:             $Tables{$tablename}->{$column_name[$i]}= $info[$i];
1.25      matthew   592:         }
1.3       matthew   593:     }
                    594:     #
                    595:     # Determine the column order
                    596:     #
                    597:     $db_command = "DESCRIBE $tablename";
1.5       matthew   598:     $sth = $dbh->prepare($db_command);
1.3       matthew   599:     $sth->execute();
                    600:     if ($sth->err) {
                    601:         $errorstring = "$dbh ATTEMPTED:\n".$db_command."\nRESULTING ERROR:\n".
                    602:             $sth->errstr;
                    603:         &disconnect_from_db();
                    604:         return undef;
                    605:     }
                    606:     my $aref=$sth->fetchall_arrayref;
                    607:     $Tables{$tablename}->{'Col_order'}=[]; # Clear values.
                    608:     # The values we want are the 'Field' entries, the first column.
                    609:     for (my $i=0;$i< @$aref ; $i++) {
                    610:         push @{$Tables{$tablename}->{'Col_order'}},$aref->[$i]->[0];
1.1       matthew   611:     }
                    612:     #
                    613:     $debugstring = "Retrieved table info for $tablename";
1.3       matthew   614:     return 1;
1.1       matthew   615: }
1.25      matthew   616: 
                    617: ###############################
                    618: 
                    619: =pod
                    620: 
                    621: =item &table_information()
                    622: 
                    623: Inputs: table id
                    624: 
                    625: Returns: hash with the table status
                    626: 
                    627: =cut
                    628: 
                    629: ###############################
                    630: sub table_information {
                    631:     my $table_id=shift;
                    632:     if (&update_table_info($table_id)) {
                    633: 	return %{$Tables{$table_id}};
                    634:     } else {
                    635: 	return ();
                    636:     }
                    637: }
                    638: 
1.18      www       639: ###############################
                    640: 
                    641: =pod
                    642: 
                    643: =item &col_order()
                    644: 
                    645: Inputs: table id
1.1       matthew   646: 
1.18      www       647: Returns: array with column order
                    648: 
                    649: =cut
                    650: 
1.25      matthew   651: ###############################
1.18      www       652: sub col_order {
                    653:     my $table_id=shift;
                    654:     if (&update_table_info($table_id)) {
                    655: 	return @{$Tables{$table_id}->{'Col_order'}};
                    656:     } else {
                    657: 	return ();
                    658:     }
                    659: }
1.21      matthew   660: 
1.1       matthew   661: ###############################
                    662: 
                    663: =pod
                    664: 
1.8       matthew   665: =item &create_table()
1.1       matthew   666: 
                    667: Inputs: 
1.21      matthew   668:     table description, see &build_table_creation_request
                    669: Returns:
                    670:     undef on error, table id on success.
                    671: 
                    672: =cut
                    673: 
                    674: ###############################
                    675: sub create_table {
                    676:     return undef if (!defined(&connect_to_db($dbh)));
                    677:     my ($table_des)=@_;
1.24      matthew   678:     my ($request,$table_id) = &build_table_creation_request($table_des);
1.21      matthew   679:     #
                    680:     # Execute the request to create the table
                    681:     #############################################
                    682:     my $count = $dbh->do($request);
                    683:     if (! defined($count)) {
                    684:         $errorstring = "$dbh ATTEMPTED:\n".$request."\nRESULTING ERROR:\n".
                    685:             $dbh->errstr();
                    686:         return undef;
                    687:     }
                    688:     my $tablename = &translate_id($table_id);
                    689:     delete($Tables{$tablename}) if (exists($Tables{$tablename}));
                    690:     return undef if (! defined(&update_table_info($table_id)));
                    691:     $debugstring = "Created table $tablename at time ".time.
                    692:         " with request\n$request";
                    693:     return $table_id;
                    694: }
1.1       matthew   695: 
1.21      matthew   696: ###############################
                    697: 
                    698: =pod
                    699: 
                    700: =item build_table_creation_request
                    701: 
                    702: Input: table description
1.1       matthew   703: 
                    704:     table description = {
                    705:         permanent  => 'yes' or 'no',
1.8       matthew   706:         columns => [
                    707:                     { name         => 'colA',
                    708:                       type         => mysql type,
                    709:                       restrictions => 'NOT NULL' or empty,
                    710:                       primary_key  => 'yes' or empty,
                    711:                       auto_inc     => 'yes' or empty,
                    712:                   },
                    713:                     { name => 'colB',
                    714:                       ...
                    715:                   },
                    716:                     { name => 'colC',
                    717:                       ...
                    718:                   },
                    719:         ],
1.9       matthew   720:         'PRIMARY KEY' => (index_col_name,...),
1.11      matthew   721:          KEY => [{ name => 'idx_name', 
                    722:                   columns => (col1,col2,..),},],
                    723:          INDEX => [{ name => 'idx_name', 
                    724:                     columns => (col1,col2,..),},],
                    725:          UNIQUE => [{ index => 'yes',
1.9       matthew   726:                      name => 'idx_name',
1.11      matthew   727:                      columns => (col1,col2,..),},],
                    728:          FULLTEXT => [{ index => 'yes',
1.9       matthew   729:                        name => 'idx_name',
1.11      matthew   730:                        columns => (col1,col2,..),},],
1.9       matthew   731: 
1.1       matthew   732:     }
                    733: 
1.21      matthew   734: Returns: scalar string containing mysql commands to create the table
1.1       matthew   735: 
                    736: =cut
                    737: 
                    738: ###############################
1.21      matthew   739: sub build_table_creation_request {
1.1       matthew   740:     my ($table_des)=@_;
                    741:     #
                    742:     # Build request to create table
                    743:     ##################################
                    744:     my @Columns;
                    745:     my $col_des;
1.9       matthew   746:     my $table_id;
                    747:     if (exists($table_des->{'id'})) {
                    748:         $table_id = $table_des->{'id'};
                    749:     } else {
                    750:         $table_id = &get_new_table_id();
                    751:     }
1.3       matthew   752:     my $tablename = &translate_id($table_id);
1.1       matthew   753:     my $request = "CREATE TABLE IF NOT EXISTS ".$tablename." ";
1.8       matthew   754:     foreach my $coldata (@{$table_des->{'columns'}}) {
                    755:         my $column = $coldata->{'name'};
                    756:         next if (! defined($column));
1.1       matthew   757:         $col_des = '';
1.3       matthew   758:         if (lc($coldata->{'type'}) =~ /(enum|set)/) { # 'enum' or 'set'
1.1       matthew   759:             $col_des.=$column." ".$coldata->{'type'}."('".
                    760:                 join("', '",@{$coldata->{'values'}})."')";
                    761:         } else {
                    762:             $col_des.=$column." ".$coldata->{'type'};
                    763:             if (exists($coldata->{'size'})) {
                    764:                 $col_des.="(".$coldata->{'size'}.")";
                    765:             }
                    766:         }
                    767:         # Modifiers
                    768:         if (exists($coldata->{'restrictions'})){
                    769:             $col_des.=" ".$coldata->{'restrictions'};
                    770:         }
                    771:         if (exists($coldata->{'default'})) {
                    772:             $col_des.=" DEFAULT '".$coldata->{'default'}."'";
                    773:         }
1.3       matthew   774:         $col_des.=' AUTO_INCREMENT' if (exists($coldata->{'auto_inc'}) &&
                    775:                                         ($coldata->{'auto_inc'} eq 'yes'));
                    776:         $col_des.=' PRIMARY KEY'    if (exists($coldata->{'primary_key'}) &&
                    777:                                         ($coldata->{'primary_key'} eq 'yes'));
1.1       matthew   778:     } continue {
                    779:         # skip blank items.
                    780:         push (@Columns,$col_des) if ($col_des ne '');
                    781:     }
1.9       matthew   782:     if (exists($table_des->{'PRIMARY KEY'})) {
                    783:         push (@Columns,'PRIMARY KEY ('.join(',',@{$table_des->{'PRIMARY KEY'}})
                    784:               .')');
                    785:     }
1.11      matthew   786:     #
                    787:     foreach my $indextype ('KEY','INDEX') {
                    788:         next if (!exists($table_des->{$indextype}));
                    789:         foreach my $indexdescription (@{$table_des->{$indextype}}) {
                    790:             my $text = $indextype.' ';
                    791:             if (exists($indexdescription->{'name'})) {
                    792:                 $text .=$indexdescription->{'name'};
1.9       matthew   793:             }
1.11      matthew   794:             $text .= ' ('.join(',',@{$indexdescription->{'columns'}}).')';
1.9       matthew   795:             push (@Columns,$text);
                    796:         }
                    797:     }
1.11      matthew   798:     #
                    799:     foreach my $indextype ('UNIQUE','FULLTEXT') {
                    800:         next if (! exists($table_des->{$indextype}));
                    801:         foreach my $indexdescription (@{$table_des->{$indextype}}) {
                    802:             my $text = $indextype.' ';
                    803:             if (exists($indexdescription->{'index'}) &&
                    804:                 $indexdescription->{'index'} eq 'yes') {
1.9       matthew   805:                 $text .= 'INDEX ';
                    806:             }
1.11      matthew   807:             if (exists($indexdescription->{'name'})) {
                    808:                 $text .=$indexdescription->{'name'};
1.9       matthew   809:             }
1.11      matthew   810:             $text .= ' ('.join(',',@{$indexdescription->{'columns'}}).')';
1.9       matthew   811:             push (@Columns,$text);
                    812:         }
1.3       matthew   813:     }
1.11      matthew   814:     #
1.1       matthew   815:     $request .= "(".join(", ",@Columns).") ";
                    816:     unless($table_des->{'permanent'} eq 'yes') {
                    817:         $request.="COMMENT = 'temporary' ";
                    818:     } 
                    819:     $request .= "TYPE=MYISAM";
1.24      matthew   820:     return $request,$table_id;
1.1       matthew   821: }
                    822: 
                    823: ###############################
                    824: 
                    825: =pod
                    826: 
1.8       matthew   827: =item &get_new_table_id()
1.1       matthew   828: 
                    829: Used internally to prevent table name collisions.
                    830: 
                    831: =cut
                    832: 
                    833: ###############################
                    834: sub get_new_table_id {
                    835:     my $newid = 0;
                    836:     my @tables = &tables_in_db();
                    837:     foreach (@tables) {
1.29      albertel  838:         if (/^$env{'user.name'}_$env{'user.domain'}_(\d+)$/) {
1.1       matthew   839:             $newid = $1 if ($1 > $newid);
                    840:         }
                    841:     }
                    842:     return ++$newid;
                    843: }
                    844: 
                    845: ###############################
                    846: 
                    847: =pod
                    848: 
1.8       matthew   849: =item &get_rows()
1.1       matthew   850: 
                    851: Inputs: $table_id,$condition
                    852: 
                    853: Returns: undef on error, an array ref to (array of) results on success.
                    854: 
1.2       matthew   855: Internally, this function does a 'SELECT * FROM table WHERE $condition'.
1.1       matthew   856: $condition = 'id>0' will result in all rows where column 'id' has a value
                    857: greater than 0 being returned.
                    858: 
                    859: =cut
                    860: 
                    861: ###############################
                    862: sub get_rows {
                    863:     my ($table_id,$condition) = @_;
1.3       matthew   864:     return undef if (! defined(&connect_to_db()));
                    865:     my $table_status = &check_table($table_id);
                    866:     return undef if (! defined($table_status));
                    867:     if (! $table_status) {
                    868:         $errorstring = "table $table_id does not exist.";
                    869:         return undef;
                    870:     }
1.1       matthew   871:     my $tablename = &translate_id($table_id);
1.9       matthew   872:     my $request;
                    873:     if (defined($condition) && $condition ne '') {
                    874:         $request = 'SELECT * FROM '.$tablename.' WHERE '.$condition;
                    875:     } else {
                    876:         $request = 'SELECT * FROM '.$tablename;
                    877:         $condition = 'no condition';
                    878:     }
1.1       matthew   879:     my $sth=$dbh->prepare($request);
                    880:     $sth->execute();
                    881:     if ($sth->err) {
                    882:         $errorstring = "$dbh ATTEMPTED:\n".$request."\nRESULTING ERROR:\n".
                    883:             $sth->errstr;
                    884:         $debugstring = "Failed to get rows matching $condition";
                    885:         return undef;
                    886:     }
                    887:     $debugstring = "Got rows matching $condition";
                    888:     my @Results = @{$sth->fetchall_arrayref};
                    889:     return @Results;
                    890: }
                    891: 
                    892: ###############################
                    893: 
                    894: =pod
                    895: 
1.8       matthew   896: =item &store_row()
1.1       matthew   897: 
                    898: Inputs: table id, row data
                    899: 
                    900: returns undef on error, 1 on success.
                    901: 
                    902: =cut
                    903: 
                    904: ###############################
                    905: sub store_row {
                    906:     my ($table_id,$rowdata) = @_;
1.3       matthew   907:     # 
                    908:     return undef if (! defined(&connect_to_db()));
                    909:     my $table_status = &check_table($table_id);
                    910:     return undef if (! defined($table_status));
                    911:     if (! $table_status) {
                    912:         $errorstring = "table $table_id does not exist.";
                    913:         return undef;
                    914:     }
                    915:     #
1.1       matthew   916:     my $tablename = &translate_id($table_id);
1.3       matthew   917:     #
1.1       matthew   918:     my $sth;
1.3       matthew   919:     if (exists($Tables{$tablename}->{'row_insert_sth'})) {
                    920:         $sth = $Tables{$tablename}->{'row_insert_sth'};
1.1       matthew   921:     } else {
1.3       matthew   922:         # Build the insert statement handler
                    923:         return undef if (! defined(&update_table_info($table_id)));
1.1       matthew   924:         my $insert_request = 'INSERT INTO '.$tablename.' VALUES(';
1.3       matthew   925:         foreach (@{$Tables{$tablename}->{'Col_order'}}) {
1.1       matthew   926:             $insert_request.="?,";
                    927:         }
                    928:         chop $insert_request;
                    929:         $insert_request.=")";
                    930:         $sth=$dbh->prepare($insert_request);
1.3       matthew   931:         $Tables{$tablename}->{'row_insert_sth'}=$sth;
1.1       matthew   932:     }
                    933:     my @Parameters; 
                    934:     if (ref($rowdata) eq 'ARRAY') {
                    935:         @Parameters = @$rowdata;
                    936:     } elsif (ref($rowdata) eq 'HASH') {
1.3       matthew   937:         foreach (@{$Tables{$tablename}->{'Col_order'}}) {
1.6       matthew   938:             push(@Parameters,$rowdata->{$_});
1.1       matthew   939:         }
                    940:     } 
                    941:     $sth->execute(@Parameters);
                    942:     if ($sth->err) {
                    943:         $errorstring = "$dbh ATTEMPTED insert @Parameters RESULTING ERROR:\n".
                    944:             $sth->errstr;
                    945:         return undef;
                    946:     }
                    947:     $debugstring = "Stored row.";    
                    948:     return 1;
                    949: }
                    950: 
1.23      matthew   951: 
                    952: ###############################
                    953: 
                    954: =pod
                    955: 
                    956: =item &bulk_store_rows()
                    957: 
                    958: Inputs: table id, [columns],[[row data1].[row data2],...]
                    959: 
                    960: returns undef on error, 1 on success.
                    961: 
                    962: =cut
                    963: 
                    964: ###############################
                    965: sub bulk_store_rows {
                    966:     my ($table_id,$columns,$rows) = @_;
                    967:     # 
                    968:     return undef if (! defined(&connect_to_db()));
                    969:     my $dbh = &get_dbh();
                    970:     return undef if (! defined($dbh));
                    971:     my $table_status = &check_table($table_id);
                    972:     return undef if (! defined($table_status));
                    973:     if (! $table_status) {
                    974:         $errorstring = "table $table_id does not exist.";
                    975:         return undef;
                    976:     }
                    977:     #
                    978:     my $tablename = &translate_id($table_id);
                    979:     #
                    980:     my $request = 'INSERT IGNORE INTO '.$tablename.' ';
                    981:     if (defined($columns) && ref($columns) eq 'ARRAY') {
                    982:         $request .= join(',',@$columns).' ';
                    983:     }
                    984:     if (! defined($rows) || ref($rows) ne 'ARRAY') {
                    985:         $errorstring = "no input rows given.";
                    986:         return undef;
                    987:     }
                    988:     $request .= 'VALUES ';
                    989:     foreach my $row (@$rows) {
                    990:         # avoid doing row stuff here...
                    991:         $request .= '('.join(',',@$row).'),';
                    992:     }
                    993:     $request =~ s/,$//;
1.32      matthew   994:     # $debugstring = "Executed ".$/.$request; # commented out - this is big
1.23      matthew   995:     $dbh->do($request);
                    996:     if ($dbh->err) {
                    997:         $errorstring = 'Attempted '.$/.$request.$/.'Got error '.$dbh->errstr();
                    998:         return undef;
                    999:     }
                   1000:     return 1;
                   1001: }
                   1002: 
                   1003: 
1.9       matthew  1004: ###############################
                   1005: 
                   1006: =pod
                   1007: 
                   1008: =item &replace_row()
                   1009: 
                   1010: Inputs: table id, row data
                   1011: 
                   1012: returns undef on error, 1 on success.
                   1013: 
                   1014: Acts like &store_row() but uses the 'REPLACE' command instead of 'INSERT'.
                   1015: 
                   1016: =cut
                   1017: 
                   1018: ###############################
                   1019: sub replace_row {
                   1020:     my ($table_id,$rowdata) = @_;
                   1021:     # 
                   1022:     return undef if (! defined(&connect_to_db()));
                   1023:     my $table_status = &check_table($table_id);
                   1024:     return undef if (! defined($table_status));
                   1025:     if (! $table_status) {
                   1026:         $errorstring = "table $table_id does not exist.";
                   1027:         return undef;
                   1028:     }
                   1029:     #
                   1030:     my $tablename = &translate_id($table_id);
                   1031:     #
                   1032:     my $sth;
                   1033:     if (exists($Tables{$tablename}->{'row_replace_sth'})) {
                   1034:         $sth = $Tables{$tablename}->{'row_replace_sth'};
                   1035:     } else {
                   1036:         # Build the insert statement handler
                   1037:         return undef if (! defined(&update_table_info($table_id)));
                   1038:         my $replace_request = 'REPLACE INTO '.$tablename.' VALUES(';
                   1039:         foreach (@{$Tables{$tablename}->{'Col_order'}}) {
                   1040:             $replace_request.="?,";
                   1041:         }
                   1042:         chop $replace_request;
                   1043:         $replace_request.=")";
                   1044:         $sth=$dbh->prepare($replace_request);
                   1045:         $Tables{$tablename}->{'row_replace_sth'}=$sth;
                   1046:     }
                   1047:     my @Parameters; 
                   1048:     if (ref($rowdata) eq 'ARRAY') {
                   1049:         @Parameters = @$rowdata;
                   1050:     } elsif (ref($rowdata) eq 'HASH') {
                   1051:         foreach (@{$Tables{$tablename}->{'Col_order'}}) {
                   1052:             push(@Parameters,$rowdata->{$_});
                   1053:         }
                   1054:     } 
                   1055:     $sth->execute(@Parameters);
                   1056:     if ($sth->err) {
                   1057:         $errorstring = "$dbh ATTEMPTED replace @Parameters RESULTING ERROR:\n".
                   1058:             $sth->errstr;
                   1059:         return undef;
                   1060:     }
                   1061:     $debugstring = "Stored row.";    
                   1062:     return 1;
                   1063: }
                   1064: 
1.1       matthew  1065: ###########################################
                   1066: 
                   1067: =pod
                   1068: 
1.8       matthew  1069: =item &tables_in_db()
1.1       matthew  1070: 
                   1071: Returns a list containing the names of all the tables in the database.
                   1072: Returns undef on error.
                   1073: 
                   1074: =cut
                   1075: 
                   1076: ###########################################
                   1077: sub tables_in_db {
1.3       matthew  1078:     return undef if (!defined(&connect_to_db()));
1.5       matthew  1079:     my $sth=$dbh->prepare('SHOW TABLES');
1.1       matthew  1080:     $sth->execute();
1.19      matthew  1081:     $sth->execute();
                   1082:     my $aref = $sth->fetchall_arrayref;
                   1083:     if ($sth->err()) {
                   1084:         $errorstring = 
                   1085:             "$dbh ATTEMPTED:\n".'fetchall_arrayref after SHOW TABLES'.
1.3       matthew  1086:             "\nRESULTING ERROR:\n".$sth->errstr;
1.1       matthew  1087:         return undef;
                   1088:     }
1.19      matthew  1089:     my @table_list;
1.1       matthew  1090:     foreach (@$aref) {
1.19      matthew  1091:         push(@table_list,$_->[0]);
1.1       matthew  1092:     }
1.19      matthew  1093:     $debugstring = "Got list of tables in DB: ".join(',',@table_list);
                   1094:     return(@table_list);
1.1       matthew  1095: }
                   1096: 
                   1097: ###########################################
                   1098: 
                   1099: =pod
                   1100: 
1.8       matthew  1101: =item &translate_id()
1.1       matthew  1102: 
                   1103: Used internally to translate a numeric table id into a MySQL table name.
                   1104: If the input $id contains non-numeric characters it is assumed to have 
                   1105: already been translated.
                   1106: 
                   1107: Checks are NOT performed to see if the table actually exists.
                   1108: 
                   1109: =cut
                   1110: 
                   1111: ###########################################
                   1112: sub translate_id {
                   1113:     my $id = shift;
                   1114:     # id should be a digit.  If it is not a digit we assume the given id
                   1115:     # is complete and does not need to be translated.
                   1116:     return $id if ($id =~ /\D/);  
1.29      albertel 1117:     return $env{'user.name'}.'_'.$env{'user.domain'}.'_'.$id;
1.1       matthew  1118: }
                   1119: 
                   1120: ###########################################
                   1121: 
                   1122: =pod
                   1123: 
1.8       matthew  1124: =item &check_table()
                   1125: 
                   1126: Input: table id
1.1       matthew  1127: 
                   1128: Checks to see if the requested table exists.  Returns 0 (no), 1 (yes), or 
                   1129: undef (error).
                   1130: 
                   1131: =cut
                   1132: 
                   1133: ###########################################
                   1134: sub check_table {
                   1135:     my $table_id = shift;
1.3       matthew  1136:     return undef if (!defined(&connect_to_db()));
                   1137:     #
1.1       matthew  1138:     $table_id = &translate_id($table_id);
                   1139:     my @Table_list = &tables_in_db();
                   1140:     my $result = 0;
                   1141:     foreach (@Table_list) {
1.9       matthew  1142:         if ($_ eq $table_id) {
1.1       matthew  1143:             $result = 1;
                   1144:             last;
                   1145:         }
                   1146:     }
                   1147:     # If it does not exist, make sure we do not have it listed in %Tables
                   1148:     delete($Tables{$table_id}) if ((! $result) && exists($Tables{$table_id}));
                   1149:     $debugstring = "check_table returned $result for $table_id";
                   1150:     return $result;
                   1151: }
                   1152: 
1.5       matthew  1153: ###########################################
                   1154: 
                   1155: =pod
                   1156: 
1.8       matthew  1157: =item &remove_from_table()
                   1158: 
                   1159: Input: $table_id, $column, $value
                   1160: 
                   1161: Returns: the number of rows deleted.  undef on error.
1.5       matthew  1162: 
                   1163: Executes a "delete from $tableid where $column like binary '$value'".
                   1164: 
                   1165: =cut
                   1166: 
                   1167: ###########################################
                   1168: sub remove_from_table {
                   1169:     my ($table_id,$column,$value) = @_;
                   1170:     return undef if (!defined(&connect_to_db()));
                   1171:     #
                   1172:     $table_id = &translate_id($table_id);
1.17      www      1173:     my $command = 'DELETE FROM '.$table_id.' WHERE '.$column.
1.5       matthew  1174:         " LIKE BINARY ".$dbh->quote($value);
                   1175:     my $sth = $dbh->prepare($command); 
1.17      www      1176:     unless ($sth->execute()) {
1.5       matthew  1177:         $errorstring = "ERROR on execution of ".$command."\n".$sth->errstr;
                   1178:         return undef;
                   1179:     }
1.12      matthew  1180:     $debugstring = $command;
1.5       matthew  1181:     my $rows = $sth->rows;
                   1182:     return $rows;
                   1183: }
                   1184: 
1.14      matthew  1185: ###########################################
                   1186: 
                   1187: =pod
                   1188: 
                   1189: =item drop_table($table_id)
                   1190: 
                   1191: Issues a 'drop table if exists' command
                   1192: 
                   1193: =cut
                   1194: 
                   1195: ###########################################
                   1196: 
                   1197: sub drop_table {
                   1198:     my ($table_id) = @_;
                   1199:     return undef if (!defined(&connect_to_db()));
                   1200:     #
                   1201:     $table_id = &translate_id($table_id);
                   1202:     my $command = 'DROP TABLE IF EXISTS '.$table_id;
                   1203:     my $sth = $dbh->prepare($command); 
                   1204:     $sth->execute();
                   1205:     if ($sth->err) {
                   1206:         $errorstring = "ERROR on execution of ".$command."\n".$sth->errstr;
                   1207:         return undef;
                   1208:     }
                   1209:     $debugstring = $command;
1.15      matthew  1210:     delete($Tables{$table_id}); # remove any knowledge of the table
1.14      matthew  1211:     return 1; # if we got here there was no error, so return a 'true' value
                   1212: }
1.16      www      1213: 
1.26      matthew  1214: ##########################################
1.16      www      1215: 
1.26      matthew  1216: =pod
                   1217: 
                   1218: =item fix_table_name 
                   1219: 
                   1220: Fixes a table name so that it will work with MySQL.
                   1221: 
                   1222: =cut
                   1223: 
                   1224: ##########################################
                   1225: sub fix_table_name {
                   1226:     my ($name) = @_;
1.28      matthew  1227:     $name =~ s/^(\d+[eE]\d+)/_$1/;
1.26      matthew  1228:     return $name;
                   1229: }
1.16      www      1230: 
                   1231: 
                   1232: # ---------------------------- convert 'time' format into a datetime sql format
                   1233: sub sqltime {
                   1234:     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
                   1235: 	localtime(&unsqltime($_[0]));
                   1236:     $mon++; $year+=1900;
                   1237:     return "$year-$mon-$mday $hour:$min:$sec";
                   1238: }
                   1239: 
                   1240: sub maketime {
                   1241:     my %th=@_;
                   1242:     return POSIX::mktime(($th{'seconds'},$th{'minutes'},$th{'hours'},
                   1243:                           $th{'day'},$th{'month'}-1,
                   1244:                           $th{'year'}-1900,0,0,$th{'dlsav'}));
                   1245: }
                   1246: 
                   1247: 
                   1248: #########################################
                   1249: #
                   1250: # Retro-fixing of un-backward-compatible time format
                   1251: 
                   1252: sub unsqltime {
                   1253:     my $timestamp=shift;
                   1254:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
                   1255:         $timestamp=&maketime('year'=>$1,'month'=>$2,'day'=>$3,
                   1256:                              'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
                   1257:     }
                   1258:     return $timestamp;
                   1259: }
                   1260: 
1.5       matthew  1261: 
1.1       matthew  1262: 1;
                   1263: 
                   1264: __END__;
1.5       matthew  1265: 
                   1266: =pod
                   1267: 
                   1268: =back
                   1269: 
                   1270: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>