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

1.1       matthew     1: # The LearningOnline Network with CAPA
                      2: # MySQL utility functions
                      3: #
1.10    ! matthew     4: # $Id: lonmysql.pm,v 1.9 2003/03/13 19:08:52 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;
                     34: use Apache::lonnet();
                     35: 
                     36: ######################################################################
                     37: ######################################################################
                     38: 
                     39: =pod 
                     40: 
                     41: =head1 Name
                     42: 
                     43: lonmysql - LONCAPA MySQL utility functions
                     44: 
                     45: =head1 Synopsis
                     46: 
                     47: lonmysql contains utility functions to make accessing the mysql loncapa
                     48: database easier.  
                     49: 
                     50: =head1 Description
                     51: 
                     52: lonmysql does its best to encapsulate all the database/table functions
                     53: and provide a common interface.  The goal, however, is not to provide 
                     54: a complete reimplementation of the DBI interface.  Instead we try to 
                     55: make using mysql as painless as possible.
                     56: 
                     57: Each table has a numeric ID that is a parameter to most lonmysql functions.
                     58: The table id is returned by &create_table.  
                     59: If you lose the table id, it is lost forever.
                     60: The table names in MySQL correspond to 
                     61: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.$table_id.  If the table id 
                     62: is non-numeric, it is assumed to be the full name of a table.  If you pass
                     63: the table id in a form, you MUST ensure that what you send to lonmysql is
                     64: numeric, otherwise you are opening up all the tables in the MySQL database.
                     65: 
                     66: =over 4
                     67: 
                     68: =item Creating a table
                     69: 
                     70: To create a table, you need a description of its structure.  See the entry
                     71: for &create_table for a description of what is needed.
                     72: 
                     73:  $table_id = &create_table({ 
1.9       matthew    74:      id      => 'tableid',      # usually you will use the returned id
                     75:      columns => (
                     76:                  { name => 'id',
                     77:                    type => 'INT',
                     78:                    restrictions => 'NOT NULL',
                     79:                    primary_key => 'yes',
                     80:                    auto_inc    => 'yes'
                     81:                    },
                     82:                  { name => 'verbage',
                     83:                    type => 'TEXT' },
                     84:                  ),
                     85:                        fulltext => [qw/verbage/],
1.3       matthew    86:         });
1.1       matthew    87: 
                     88: The above command will create a table with two columns, 'id' and 'verbage'.
                     89: 
                     90: 'id' will be an integer which is autoincremented and non-null.
                     91: 
                     92: 'verbage' will be of type 'TEXT', which (conceivably) allows any length
                     93: text string to be stored.  Depending on your intentions for this database,
                     94: setting restrictions => 'NOT NULL' may help you avoid storing empty data.
                     95: 
1.3       matthew    96: the fulltext element sets up the 'verbage' column for 'FULLTEXT' searching.
1.1       matthew    97: 
                     98: 
                     99: 
                    100: =item Storing rows
                    101: 
                    102: Storing a row in a table requires calling &store_row($table_id,$data)
                    103: 
                    104: $data is either a hash reference or an array reference.  If it is an array
                    105: reference, the data is passed as is (after being escaped) to the 
                    106: "INSERT INTO <table> VALUES( ... )" SQL command.  If $data is a hash reference,
                    107: the data will be placed into an array in the proper column order for the table
                    108: and then passed to the database.
                    109: 
                    110: An example of inserting into the table created above is:
                    111: 
                    112: &store_row($table_id,[undef,'I am not a crackpot!']);
                    113: 
                    114: or equivalently,
                    115: 
                    116: &store_row($table_id,{ verbage => 'I am not a crackpot!'});
                    117: 
                    118: Since the above table was created with the first column ('id') as 
                    119: autoincrement, providing a value is unnecessary even though the column was
                    120: marked as 'NOT NULL'.
                    121: 
                    122: 
                    123: 
                    124: =item Retrieving rows
                    125: 
                    126: Retrieving rows requires calling get_rows:
                    127: 
                    128: @row = &Apache::lonmysql::get_rows($table_id,$condition)
                    129: 
                    130: This results in the query "SELECT * FROM <table> HAVING $condition".
                    131: 
                    132: @row = &Apache::lonmysql::get_rows($table_id,'id>20'); 
                    133: 
                    134: returns all rows with column 'id' greater than 20.
                    135: 
                    136: =back
                    137: 
                    138: =cut
                    139: 
                    140: ######################################################################
                    141: ######################################################################
                    142: =pod
                    143: 
                    144: =head1 Package Variables
                    145: 
                    146: =over 4
                    147: 
                    148: =cut
                    149: 
                    150: ##################################################
                    151: ##################################################
                    152: 
                    153: =pod
                    154: 
                    155: =item %Tables
                    156: 
                    157: Holds information regarding the currently open connections.  Each key
                    158: in the %Tables hash will be a unique table key.  The value associated 
                    159: with a key is a hash reference.  Most values are initialized when the 
                    160: table is created.
                    161: 
                    162: The following entries are allowed in the hash reference:
                    163: 
                    164: =over 4
                    165: 
1.3       matthew   166: =item Name
                    167: 
                    168: Table name.
                    169: 
                    170: =item Type            
                    171: 
                    172: The type of table, typically MyISAM.
                    173: 
                    174: =item Row_format
                    175: 
                    176: Describes how rows should be stored in the table.  DYNAMIC or STATIC.
                    177: 
                    178: =item Create_time
                    179: 
                    180: The date of the tables creation.
                    181: 
                    182: =item Update_time
                    183: 
                    184: The date of the last modification of the table.
                    185: 
                    186: =item Check_time
                    187: 
                    188: Usually NULL. 
                    189: 
                    190: =item Avg_row_length
                    191: 
                    192: The average length of the rows.
                    193: 
                    194: =item Data_length
                    195: 
                    196: The length of the data stored in the table (bytes)
                    197: 
                    198: =item Max_data_length
                    199: 
                    200: The maximum possible size of the table (bytes).
1.1       matthew   201: 
1.3       matthew   202: =item Index_length
1.1       matthew   203: 
1.3       matthew   204: The length of the index for the table (bytes)
1.1       matthew   205: 
1.3       matthew   206: =item Data_free
1.1       matthew   207: 
1.3       matthew   208: I have no idea what this is.
1.1       matthew   209: 
1.3       matthew   210: =item Comment 
1.1       matthew   211: 
1.3       matthew   212: The comment associated with the table.
                    213: 
                    214: =item Rows
                    215: 
                    216: The number of rows in the table.
                    217: 
                    218: =item Auto_increment
                    219: 
                    220: The value of the next auto_increment field.
                    221: 
                    222: =item Create_options
                    223: 
                    224: I have no idea.
                    225: 
                    226: =item Col_order
                    227: 
                    228: an array reference which holds the order of columns in the table.
                    229: 
                    230: =item row_insert_sth 
1.1       matthew   231: 
                    232: The statement handler for row inserts.
                    233: 
1.9       matthew   234: =item row_replace_sth 
                    235: 
                    236: The statement handler for row inserts.
                    237: 
1.1       matthew   238: =back
                    239: 
1.3       matthew   240: Col_order and row_insert_sth are kept internally by lonmysql and are not
                    241: part of the usual MySQL table information.
                    242: 
1.1       matthew   243: =cut
                    244: 
                    245: ##################################################
                    246: ##################################################
                    247: my %Tables;
                    248: 
                    249: ##################################################
                    250: ##################################################
                    251: =pod
                    252: 
                    253: =item $errorstring
                    254: 
                    255: Holds the last error.
                    256: 
                    257: =cut
                    258: ##################################################
                    259: ##################################################
                    260: my $errorstring;
                    261: 
                    262: ##################################################
                    263: ##################################################
                    264: =pod
                    265: 
                    266: =item $debugstring
                    267: 
                    268: Describes current events within the package.
                    269: 
                    270: =cut
                    271: ##################################################
                    272: ##################################################
                    273: my $debugstring;
                    274: 
                    275: ##################################################
                    276: ##################################################
                    277: 
                    278: =pod
                    279: 
                    280: =item $dbh
                    281: 
                    282: The database handler; The actual connection to MySQL via the perl DBI.
                    283: 
                    284: =cut
                    285: 
                    286: ##################################################
                    287: ##################################################
                    288: my $dbh;
                    289: 
                    290: ##################################################
                    291: ##################################################
                    292: 
                    293: # End of global variable declarations
                    294: 
                    295: =pod
                    296: 
                    297: =back
                    298: 
                    299: =cut
                    300: 
                    301: ######################################################################
                    302: ######################################################################
                    303: 
                    304: =pod
                    305: 
                    306: =head1 Internals
                    307: 
                    308: =over 4
                    309: 
                    310: =cut
                    311: 
                    312: ######################################################################
                    313: ######################################################################
                    314: 
                    315: =pod
                    316: 
                    317: =item &connect_to_db()
                    318: 
                    319: Inputs: none.  
                    320: 
                    321: Returns: undef on error, 1 on success.
                    322: 
                    323: Checks to make sure the database has been connected to.  If not, the
                    324: connection is established.  
                    325: 
                    326: =cut
                    327: 
                    328: ###############################
                    329: sub connect_to_db { 
                    330:     return 1 if ($dbh);
                    331:     if (! ($dbh = DBI->connect("DBI:mysql:loncapa","www",
                    332:                                $Apache::lonnet::perlvar{'lonSqlAccess'},
                    333:                                { RaiseError=>0,PrintError=>0}))) {
                    334:         $debugstring = "Unable to connect to loncapa database.";    
1.7       matthew   335:         if (! defined($dbh)) {
                    336:             $debugstring = "Unable to connect to loncapa database.";
                    337:             $errorstring = "dbh was undefined.";
                    338:         } elsif ($dbh->err) {
1.1       matthew   339:             $errorstring = "Connection error: ".$dbh->errstr;
                    340:         }
                    341:         return undef;
                    342:     }
                    343:     $debugstring = "Successfully connected to loncapa database.";    
                    344:     return 1;
                    345: }
                    346: 
                    347: ###############################
                    348: 
                    349: =pod
                    350: 
                    351: =item &disconnect_from_db()
                    352: 
                    353: Inputs: none.
                    354: 
                    355: Returns: Always returns 1.
                    356: 
                    357: Severs the connection to the mysql database.
                    358: 
                    359: =cut
                    360: 
                    361: ###############################
                    362: sub disconnect_from_db { 
                    363:     foreach (keys(%Tables)) {
                    364:         # Supposedly, having statement handlers running around after the
                    365:         # database connection has been lost will cause trouble.  So we 
                    366:         # kill them off just to be sure.
                    367:         if (exists($Tables{$_}->{'row_insert_sth'})) {
                    368:             delete($Tables{$_}->{'row_insert_sth'});
                    369:         }
1.9       matthew   370:         if (exists($Tables{$_}->{'row_replace_sth'})) {
                    371:             delete($Tables{$_}->{'row_replace_sth'});
                    372:         }
1.1       matthew   373:     }
                    374:     $dbh->disconnect if ($dbh);
                    375:     $debugstring = "Disconnected from database.";
                    376:     $dbh = undef;
                    377:     return 1;
                    378: }
                    379: 
                    380: ###############################
                    381: 
                    382: =pod
                    383: 
1.2       matthew   384: =item &number_of_rows()
1.1       matthew   385: 
1.2       matthew   386: Input: table identifier
                    387: 
1.3       matthew   388: Returns: the number of rows in the given table, undef on error.
1.1       matthew   389: 
                    390: =cut
                    391: 
                    392: ###############################
1.2       matthew   393: sub number_of_rows { 
                    394:     my ($table_id) = @_;
1.3       matthew   395:     return undef if (! defined(&connect_to_db()));
                    396:     return undef if (! defined(&update_table_info($table_id)));
                    397:     return $Tables{&translate_id($table_id)}->{'Rows'};
1.10    ! matthew   398: }
        !           399: ###############################
        !           400: 
        !           401: =pod
        !           402: 
        !           403: =item &get_dbh()
        !           404: 
        !           405: Input: nothing
        !           406: 
        !           407: Returns: the database handler, or undef on error.
        !           408: 
        !           409: This routine allows the programmer to gain access to the database handler.
        !           410: Be careful.
        !           411: 
        !           412: =cut
        !           413: 
        !           414: ###############################
        !           415: sub get_dbh { 
        !           416:     return undef if (! defined(&connect_to_db()));
        !           417:     return $dbh;
1.1       matthew   418: }
                    419: 
                    420: ###############################
                    421: 
                    422: =pod
                    423: 
                    424: =item &get_error()
                    425: 
                    426: Inputs: none.
                    427: 
                    428: Returns: The last error reported.
                    429: 
                    430: =cut
                    431: 
                    432: ###############################
                    433: sub get_error {
                    434:     return $errorstring;
                    435: }
                    436: 
                    437: ###############################
                    438: 
                    439: =pod
                    440: 
                    441: =item &get_debug()
                    442: 
                    443: Inputs: none.
                    444: 
                    445: Returns: A string describing the internal state of the lonmysql package.
                    446: 
                    447: =cut
                    448: 
                    449: ###############################
                    450: sub get_debug {
                    451:     return $debugstring;
                    452: }
                    453: 
                    454: ###############################
                    455: 
                    456: =pod
                    457: 
1.8       matthew   458: =item &update_table_info()
1.1       matthew   459: 
                    460: Inputs: table id
                    461: 
1.3       matthew   462: Returns: undef on error, 1 on success.
1.1       matthew   463: 
1.3       matthew   464: &update_table_info updates the %Tables hash with current information about
                    465: the given table.  
                    466: 
                    467: The default MySQL table status fields are:
1.1       matthew   468: 
                    469:    Name             Type            Row_format
                    470:    Max_data_length  Index_length    Data_free
                    471:    Create_time      Update_time     Check_time
                    472:    Avg_row_length   Data_length     Comment 
                    473:    Rows             Auto_increment  Create_options
                    474: 
1.3       matthew   475: Additionally, "Col_order" is updated as well.
                    476: 
1.1       matthew   477: =cut
                    478: 
                    479: ###############################
1.3       matthew   480: sub update_table_info { 
1.1       matthew   481:     my ($table_id) = @_;
1.3       matthew   482:     return undef if (! defined(&connect_to_db()));
                    483:     my $table_status = &check_table($table_id);
                    484:     return undef if (! defined($table_status));
                    485:     if (! $table_status) {
                    486:         $errorstring = "table $table_id does not exist.";
                    487:         return undef;
                    488:     }
1.1       matthew   489:     my $tablename = &translate_id($table_id);
1.3       matthew   490:     #
                    491:     # Get MySQLs table status information.
                    492:     #
1.1       matthew   493:     my @tabledesc = qw/
                    494:         Name Type Row_format Rows Avg_row_length Data_length
                    495:             Max_data_length Index_length Data_free Auto_increment 
                    496:                 Create_time Update_time Check_time Create_options Comment /;
                    497:     my $db_command = "SHOW TABLE STATUS FROM loncapa LIKE '$tablename'";
                    498:     my $sth = $dbh->prepare($db_command);
                    499:     $sth->execute();
                    500:     if ($sth->err) {
                    501:         $errorstring = "$dbh ATTEMPTED:\n".$db_command."\nRESULTING ERROR:\n".
                    502:             $sth->errstr;
1.3       matthew   503:         &disconnect_from_db();
1.1       matthew   504:         return undef;
                    505:     }
                    506:     #
                    507:     my @info=$sth->fetchrow_array;
                    508:     for (my $i=0;$i<= $#info ; $i++) {
1.3       matthew   509:         $Tables{$tablename}->{$tabledesc[$i]}= $info[$i];
                    510:     }
                    511:     #
                    512:     # Determine the column order
                    513:     #
                    514:     $db_command = "DESCRIBE $tablename";
1.5       matthew   515:     $sth = $dbh->prepare($db_command);
1.3       matthew   516:     $sth->execute();
                    517:     if ($sth->err) {
                    518:         $errorstring = "$dbh ATTEMPTED:\n".$db_command."\nRESULTING ERROR:\n".
                    519:             $sth->errstr;
                    520:         &disconnect_from_db();
                    521:         return undef;
                    522:     }
                    523:     my $aref=$sth->fetchall_arrayref;
                    524:     $Tables{$tablename}->{'Col_order'}=[]; # Clear values.
                    525:     # The values we want are the 'Field' entries, the first column.
                    526:     for (my $i=0;$i< @$aref ; $i++) {
                    527:         push @{$Tables{$tablename}->{'Col_order'}},$aref->[$i]->[0];
1.1       matthew   528:     }
                    529:     #
                    530:     $debugstring = "Retrieved table info for $tablename";
1.3       matthew   531:     return 1;
1.1       matthew   532: }
                    533: 
                    534: ###############################
                    535: 
                    536: =pod
                    537: 
1.8       matthew   538: =item &create_table()
1.1       matthew   539: 
                    540: Inputs: 
                    541:     table description
                    542: 
                    543: Input formats:
                    544: 
                    545:     table description = {
                    546:         permanent  => 'yes' or 'no',
1.8       matthew   547:         columns => [
                    548:                     { name         => 'colA',
                    549:                       type         => mysql type,
                    550:                       restrictions => 'NOT NULL' or empty,
                    551:                       primary_key  => 'yes' or empty,
                    552:                       auto_inc     => 'yes' or empty,
                    553:                   },
                    554:                     { name => 'colB',
                    555:                       ...
                    556:                   },
                    557:                     { name => 'colC',
                    558:                       ...
                    559:                   },
                    560:         ],
1.9       matthew   561:         'PRIMARY KEY' => (index_col_name,...),
                    562:          KEY => { name => 'idx_name', 
                    563:                   columns => (col1,col2,..),},
                    564:          INDEX => { name => 'idx_name', 
                    565:                     columns => (col1,col2,..),},
                    566:          UNIQUE => { index => 'yes',
                    567:                      name => 'idx_name',
                    568:                      columns => (col1,col2,..),},
                    569:          FULLTEXT => { index => 'yes',
                    570:                        name => 'idx_name',
                    571:                        columns => (col1,col2,..),},
                    572: 
1.1       matthew   573:     }
                    574: 
                    575: Returns:
                    576:     undef on error, table id on success.
                    577: 
                    578: =cut
                    579: 
                    580: ###############################
                    581: sub create_table {
1.3       matthew   582:     return undef if (!defined(&connect_to_db($dbh)));
1.1       matthew   583:     my ($table_des)=@_;
                    584:     #
                    585:     # Build request to create table
                    586:     ##################################
                    587:     my @Columns;
                    588:     my $col_des;
1.9       matthew   589:     my $table_id;
                    590:     if (exists($table_des->{'id'})) {
                    591:         $table_id = $table_des->{'id'};
                    592:     } else {
                    593:         $table_id = &get_new_table_id();
                    594:     }
1.3       matthew   595:     my $tablename = &translate_id($table_id);
1.1       matthew   596:     my $request = "CREATE TABLE IF NOT EXISTS ".$tablename." ";
1.8       matthew   597:     foreach my $coldata (@{$table_des->{'columns'}}) {
                    598:         my $column = $coldata->{'name'};
                    599:         next if (! defined($column));
1.1       matthew   600:         $col_des = '';
1.3       matthew   601:         if (lc($coldata->{'type'}) =~ /(enum|set)/) { # 'enum' or 'set'
1.1       matthew   602:             $col_des.=$column." ".$coldata->{'type'}."('".
                    603:                 join("', '",@{$coldata->{'values'}})."')";
                    604:         } else {
                    605:             $col_des.=$column." ".$coldata->{'type'};
                    606:             if (exists($coldata->{'size'})) {
                    607:                 $col_des.="(".$coldata->{'size'}.")";
                    608:             }
                    609:         }
                    610:         # Modifiers
                    611:         if (exists($coldata->{'restrictions'})){
                    612:             $col_des.=" ".$coldata->{'restrictions'};
                    613:         }
                    614:         if (exists($coldata->{'default'})) {
                    615:             $col_des.=" DEFAULT '".$coldata->{'default'}."'";
                    616:         }
1.3       matthew   617:         $col_des.=' AUTO_INCREMENT' if (exists($coldata->{'auto_inc'}) &&
                    618:                                         ($coldata->{'auto_inc'} eq 'yes'));
                    619:         $col_des.=' PRIMARY KEY'    if (exists($coldata->{'primary_key'}) &&
                    620:                                         ($coldata->{'primary_key'} eq 'yes'));
1.1       matthew   621:     } continue {
                    622:         # skip blank items.
                    623:         push (@Columns,$col_des) if ($col_des ne '');
                    624:     }
1.9       matthew   625:     if (exists($table_des->{'PRIMARY KEY'})) {
                    626:         push (@Columns,'PRIMARY KEY ('.join(',',@{$table_des->{'PRIMARY KEY'}})
                    627:               .')');
                    628:     }
                    629:     foreach ('KEY','INDEX') {
                    630:         if (exists($table_des->{$_})) {
                    631:             my $text = $_.' ';
                    632:             if (exists($table_des->{$_}->{'name'})) {
                    633:                 $text .=$table_des->{$_}->{'name'};
                    634:             }
                    635:             $text .= ' ('.join(',',@{$table_des->{$_}->{'columns'}}).')';
                    636:             push (@Columns,$text);
                    637:         }
                    638:     }
                    639:     foreach ('UNIQUE','FULLTEXT') {
                    640:         if (exists($table_des->{$_})) {
                    641:             my $text = $_.' ';
                    642:             if (exists($table_des->{$_}->{'index'}) &&
                    643:                 $table_des->{$_}->{'index'} eq 'yes') {
                    644:                 $text .= 'INDEX ';
                    645:             }
                    646:             if (exists($table_des->{$_}->{'name'})) {
                    647:                 $text .=$table_des->{$_}->{'name'};
                    648:             }
                    649:             $text .= ' ('.join(',',@{$table_des->{$_}->{'columns'}}).')';
                    650:             push (@Columns,$text);
                    651:         }
1.3       matthew   652:     }
1.1       matthew   653:     $request .= "(".join(", ",@Columns).") ";
                    654:     unless($table_des->{'permanent'} eq 'yes') {
                    655:         $request.="COMMENT = 'temporary' ";
                    656:     } 
                    657:     $request .= "TYPE=MYISAM";
                    658:     #
                    659:     # Execute the request to create the table
                    660:     #############################################
                    661:     my $count = $dbh->do($request);
                    662:     if (! defined($count)) {
1.3       matthew   663:         $errorstring = "$dbh ATTEMPTED:\n".$request."\nRESULTING ERROR:\n";
1.1       matthew   664:         return undef;
                    665:     }
                    666:     #
                    667:     # Set up the internal bookkeeping
                    668:     #############################################
                    669:     delete($Tables{$tablename}) if (exists($Tables{$tablename}));
1.3       matthew   670:     return undef if (! defined(&update_table_info($table_id)));
                    671:     $debugstring = "Created table $tablename at time ".time.
1.1       matthew   672:         " with request\n$request";
1.3       matthew   673:     return $table_id;
1.1       matthew   674: }
                    675: 
                    676: ###############################
                    677: 
                    678: =pod
                    679: 
1.8       matthew   680: =item &get_new_table_id()
1.1       matthew   681: 
                    682: Used internally to prevent table name collisions.
                    683: 
                    684: =cut
                    685: 
                    686: ###############################
                    687: sub get_new_table_id {
                    688:     my $newid = 0;
                    689:     my @tables = &tables_in_db();
                    690:     foreach (@tables) {
                    691:         if (/^$ENV{'user.name'}_$ENV{'user.domain'}_(\d+)$/) {
                    692:             $newid = $1 if ($1 > $newid);
                    693:         }
                    694:     }
                    695:     return ++$newid;
                    696: }
                    697: 
                    698: ###############################
                    699: 
                    700: =pod
                    701: 
1.8       matthew   702: =item &get_rows()
1.1       matthew   703: 
                    704: Inputs: $table_id,$condition
                    705: 
                    706: Returns: undef on error, an array ref to (array of) results on success.
                    707: 
1.2       matthew   708: Internally, this function does a 'SELECT * FROM table WHERE $condition'.
1.1       matthew   709: $condition = 'id>0' will result in all rows where column 'id' has a value
                    710: greater than 0 being returned.
                    711: 
                    712: =cut
                    713: 
                    714: ###############################
                    715: sub get_rows {
                    716:     my ($table_id,$condition) = @_;
1.3       matthew   717:     return undef if (! defined(&connect_to_db()));
                    718:     my $table_status = &check_table($table_id);
                    719:     return undef if (! defined($table_status));
                    720:     if (! $table_status) {
                    721:         $errorstring = "table $table_id does not exist.";
                    722:         return undef;
                    723:     }
1.1       matthew   724:     my $tablename = &translate_id($table_id);
1.9       matthew   725:     my $request;
                    726:     if (defined($condition) && $condition ne '') {
                    727:         $request = 'SELECT * FROM '.$tablename.' WHERE '.$condition;
                    728:     } else {
                    729:         $request = 'SELECT * FROM '.$tablename;
                    730:         $condition = 'no condition';
                    731:     }
1.1       matthew   732:     my $sth=$dbh->prepare($request);
                    733:     $sth->execute();
                    734:     if ($sth->err) {
                    735:         $errorstring = "$dbh ATTEMPTED:\n".$request."\nRESULTING ERROR:\n".
                    736:             $sth->errstr;
                    737:         $debugstring = "Failed to get rows matching $condition";
                    738:         return undef;
                    739:     }
                    740:     $debugstring = "Got rows matching $condition";
                    741:     my @Results = @{$sth->fetchall_arrayref};
                    742:     return @Results;
                    743: }
                    744: 
                    745: ###############################
                    746: 
                    747: =pod
                    748: 
1.8       matthew   749: =item &store_row()
1.1       matthew   750: 
                    751: Inputs: table id, row data
                    752: 
                    753: returns undef on error, 1 on success.
                    754: 
                    755: =cut
                    756: 
                    757: ###############################
                    758: sub store_row {
                    759:     my ($table_id,$rowdata) = @_;
1.3       matthew   760:     # 
                    761:     return undef if (! defined(&connect_to_db()));
                    762:     my $table_status = &check_table($table_id);
                    763:     return undef if (! defined($table_status));
                    764:     if (! $table_status) {
                    765:         $errorstring = "table $table_id does not exist.";
                    766:         return undef;
                    767:     }
                    768:     #
1.1       matthew   769:     my $tablename = &translate_id($table_id);
1.3       matthew   770:     #
1.1       matthew   771:     my $sth;
1.3       matthew   772:     if (exists($Tables{$tablename}->{'row_insert_sth'})) {
                    773:         $sth = $Tables{$tablename}->{'row_insert_sth'};
1.1       matthew   774:     } else {
1.3       matthew   775:         # Build the insert statement handler
                    776:         return undef if (! defined(&update_table_info($table_id)));
1.1       matthew   777:         my $insert_request = 'INSERT INTO '.$tablename.' VALUES(';
1.3       matthew   778:         foreach (@{$Tables{$tablename}->{'Col_order'}}) {
1.1       matthew   779:             $insert_request.="?,";
                    780:         }
                    781:         chop $insert_request;
                    782:         $insert_request.=")";
                    783:         $sth=$dbh->prepare($insert_request);
1.3       matthew   784:         $Tables{$tablename}->{'row_insert_sth'}=$sth;
1.1       matthew   785:     }
                    786:     my @Parameters; 
                    787:     if (ref($rowdata) eq 'ARRAY') {
                    788:         @Parameters = @$rowdata;
                    789:     } elsif (ref($rowdata) eq 'HASH') {
1.3       matthew   790:         foreach (@{$Tables{$tablename}->{'Col_order'}}) {
1.6       matthew   791:             push(@Parameters,$rowdata->{$_});
1.1       matthew   792:         }
                    793:     } 
                    794:     $sth->execute(@Parameters);
                    795:     if ($sth->err) {
                    796:         $errorstring = "$dbh ATTEMPTED insert @Parameters RESULTING ERROR:\n".
                    797:             $sth->errstr;
                    798:         return undef;
                    799:     }
                    800:     $debugstring = "Stored row.";    
                    801:     return 1;
                    802: }
                    803: 
1.9       matthew   804: ###############################
                    805: 
                    806: =pod
                    807: 
                    808: =item &replace_row()
                    809: 
                    810: Inputs: table id, row data
                    811: 
                    812: returns undef on error, 1 on success.
                    813: 
                    814: Acts like &store_row() but uses the 'REPLACE' command instead of 'INSERT'.
                    815: 
                    816: =cut
                    817: 
                    818: ###############################
                    819: sub replace_row {
                    820:     my ($table_id,$rowdata) = @_;
                    821:     # 
                    822:     return undef if (! defined(&connect_to_db()));
                    823:     my $table_status = &check_table($table_id);
                    824:     return undef if (! defined($table_status));
                    825:     if (! $table_status) {
                    826:         $errorstring = "table $table_id does not exist.";
                    827:         return undef;
                    828:     }
                    829:     #
                    830:     my $tablename = &translate_id($table_id);
                    831:     #
                    832:     my $sth;
                    833:     if (exists($Tables{$tablename}->{'row_replace_sth'})) {
                    834:         $sth = $Tables{$tablename}->{'row_replace_sth'};
                    835:     } else {
                    836:         # Build the insert statement handler
                    837:         return undef if (! defined(&update_table_info($table_id)));
                    838:         my $replace_request = 'REPLACE INTO '.$tablename.' VALUES(';
                    839:         foreach (@{$Tables{$tablename}->{'Col_order'}}) {
                    840:             $replace_request.="?,";
                    841:         }
                    842:         chop $replace_request;
                    843:         $replace_request.=")";
                    844:         $sth=$dbh->prepare($replace_request);
                    845:         $Tables{$tablename}->{'row_replace_sth'}=$sth;
                    846:     }
                    847:     my @Parameters; 
                    848:     if (ref($rowdata) eq 'ARRAY') {
                    849:         @Parameters = @$rowdata;
                    850:     } elsif (ref($rowdata) eq 'HASH') {
                    851:         foreach (@{$Tables{$tablename}->{'Col_order'}}) {
                    852:             push(@Parameters,$rowdata->{$_});
                    853:         }
                    854:     } 
                    855:     $sth->execute(@Parameters);
                    856:     if ($sth->err) {
                    857:         $errorstring = "$dbh ATTEMPTED replace @Parameters RESULTING ERROR:\n".
                    858:             $sth->errstr;
                    859:         return undef;
                    860:     }
                    861:     $debugstring = "Stored row.";    
                    862:     return 1;
                    863: }
                    864: 
1.1       matthew   865: ###########################################
                    866: 
                    867: =pod
                    868: 
1.8       matthew   869: =item &tables_in_db()
1.1       matthew   870: 
                    871: Returns a list containing the names of all the tables in the database.
                    872: Returns undef on error.
                    873: 
                    874: =cut
                    875: 
                    876: ###########################################
                    877: sub tables_in_db {
1.3       matthew   878:     return undef if (!defined(&connect_to_db()));
1.5       matthew   879:     my $sth=$dbh->prepare('SHOW TABLES');
1.1       matthew   880:     $sth->execute();
                    881:     if ($sth->err) {
1.3       matthew   882:         $errorstring = "$dbh ATTEMPTED:\n".'SHOW TABLES'.
                    883:             "\nRESULTING ERROR:\n".$sth->errstr;
1.1       matthew   884:         return undef;
                    885:     }
                    886:     my $aref = $sth->fetchall_arrayref;
                    887:     my @table_list=();
                    888:     foreach (@$aref) {
                    889:         push @table_list,$_->[0];
                    890:     }
                    891:     $debugstring = "Got list of tables in DB: @table_list";
                    892:     return @table_list;
                    893: }
                    894: 
                    895: ###########################################
                    896: 
                    897: =pod
                    898: 
1.8       matthew   899: =item &translate_id()
1.1       matthew   900: 
                    901: Used internally to translate a numeric table id into a MySQL table name.
                    902: If the input $id contains non-numeric characters it is assumed to have 
                    903: already been translated.
                    904: 
                    905: Checks are NOT performed to see if the table actually exists.
                    906: 
                    907: =cut
                    908: 
                    909: ###########################################
                    910: sub translate_id {
                    911:     my $id = shift;
                    912:     # id should be a digit.  If it is not a digit we assume the given id
                    913:     # is complete and does not need to be translated.
                    914:     return $id if ($id =~ /\D/);  
                    915:     return $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.$id;
                    916: }
                    917: 
                    918: ###########################################
                    919: 
                    920: =pod
                    921: 
1.8       matthew   922: =item &check_table()
                    923: 
                    924: Input: table id
1.1       matthew   925: 
                    926: Checks to see if the requested table exists.  Returns 0 (no), 1 (yes), or 
                    927: undef (error).
                    928: 
                    929: =cut
                    930: 
                    931: ###########################################
                    932: sub check_table {
                    933:     my $table_id = shift;
1.3       matthew   934:     return undef if (!defined(&connect_to_db()));
                    935:     #
1.1       matthew   936:     $table_id = &translate_id($table_id);
                    937:     my @Table_list = &tables_in_db();
                    938:     my $result = 0;
                    939:     foreach (@Table_list) {
1.9       matthew   940:         if ($_ eq $table_id) {
1.1       matthew   941:             $result = 1;
                    942:             last;
                    943:         }
                    944:     }
                    945:     # If it does not exist, make sure we do not have it listed in %Tables
                    946:     delete($Tables{$table_id}) if ((! $result) && exists($Tables{$table_id}));
                    947:     $debugstring = "check_table returned $result for $table_id";
                    948:     return $result;
                    949: }
                    950: 
1.5       matthew   951: ###########################################
                    952: 
                    953: =pod
                    954: 
1.8       matthew   955: =item &remove_from_table()
                    956: 
                    957: Input: $table_id, $column, $value
                    958: 
                    959: Returns: the number of rows deleted.  undef on error.
1.5       matthew   960: 
                    961: Executes a "delete from $tableid where $column like binary '$value'".
                    962: 
                    963: =cut
                    964: 
                    965: ###########################################
                    966: sub remove_from_table {
                    967:     my ($table_id,$column,$value) = @_;
                    968:     return undef if (!defined(&connect_to_db()));
                    969:     #
                    970:     $table_id = &translate_id($table_id);
                    971:     my $command = 'DELETE FROM '.$table_id.' WHERE '.$dbh->quote($column).
                    972:         " LIKE BINARY ".$dbh->quote($value);
                    973:     my $sth = $dbh->prepare($command); 
                    974:     $sth->execute();
                    975:     if ($sth->err) {
                    976:         $errorstring = "ERROR on execution of ".$command."\n".$sth->errstr;
                    977:         return undef;
                    978:     }
                    979:     my $rows = $sth->rows;
                    980:     return $rows;
                    981: }
                    982: 
                    983: 
1.1       matthew   984: 1;
                    985: 
                    986: __END__;
1.5       matthew   987: 
                    988: =pod
                    989: 
                    990: =back
                    991: 
                    992: =cut

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