# Our beloved Emacs will give us -*- perl -*- mode :-) # # $Id: dbd.pm.in,v 1.1.1.1.2.7 1999/05/23 11:46:56 joe Exp $ # # Copyright (c) 1994,1995,1996,1997 Alligator Descartes, Tim Bunce # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. package DBD::mysql; use strict; use vars qw(@ISA $VERSION $err $errstr $drh); use DBI (); use DynaLoader(); use Carp (); @ISA = qw(DynaLoader); $VERSION = '2.0400'; bootstrap DBD::mysql $VERSION; $err = 0; # holds error code for DBI::err $errstr = ""; # holds error string for DBI::errstr $drh = undef; # holds driver handle once initialised sub driver{ return $drh if $drh; my($class, $attr) = @_; $class .= "::dr"; # not a 'my' since we use it above to prevent multiple drivers $drh = DBI::_new_drh($class, { 'Name' => 'mysql', 'Version' => $VERSION, 'Err' => \$DBD::mysql::err, 'Errstr' => \$DBD::mysql::errstr, 'Attribution' => 'DBD::mysql by Jochen Wiedmann' }); $drh; } sub _OdbcParse($$$) { my($class, $dsn, $hash, $args) = @_; my($var, $val); if (!defined($dsn)) { return; } while (length($dsn)) { if ($dsn =~ /([^:;]*)[:;](.*)/) { $val = $1; $dsn = $2; } else { $val = $dsn; $dsn = ''; } if ($val =~ /([^=]*)=(.*)/) { $var = $1; $val = $2; if ($var eq 'hostname' || $var eq 'host') { $hash->{'host'} = $val; } elsif ($var eq 'db' || $var eq 'dbname') { $hash->{'database'} = $val; } else { $hash->{$var} = $val; } } else { foreach $var (@$args) { if (!defined($hash->{$var})) { $hash->{$var} = $val; last; } } } } } sub _OdbcParseHost ($$) { my($class, $dsn) = @_; my($hash) = {}; $class->_OdbcParse($dsn, $hash, ['host', 'port']); ($hash->{'host'}, $hash->{'port'}); } sub AUTOLOAD { my ($meth) = $DBD::mysql::AUTOLOAD; my ($smeth) = $meth; $smeth =~ s/(.*)\:\://; my $val = constant($smeth, @_ ? $_[0] : 0); if ($! == 0) { eval "sub $meth { $val }"; return $val; } Carp::croak "$meth: Not defined"; } 1; package DBD::mysql::dr; # ====== DRIVER ====== use strict; sub connect { my($drh, $dsn, $username, $password, $attrhash) = @_; my($port); my($cWarn); # Avoid warnings for undefined values $username ||= ''; $password ||= ''; # create a 'blank' dbh my($this, $privateAttrHash); $privateAttrHash = { 'Name' => $dsn, 'user' => $username, 'password' => $password }; DBD::mysql->_OdbcParse($dsn, $privateAttrHash, ['database', 'host', 'port']); if (!defined($this = DBI::_new_dbh($drh, {}, $privateAttrHash))) { return undef; } # Call msqlConnect func in mSQL.xs file # and populate internal handle data. DBD::mysql::db::_login($this, $dsn, $username, $password) or $this = undef; $this; } sub data_sources { my($self) = shift; my(@dsn) = $self->func('', '_ListDBs'); my($i); for ($i = 0; $i < @dsn; $i++) { $dsn[$i] = "DBI:mysql:$dsn[$i]"; } @dsn; } sub admin { my($drh) = shift; my($command) = shift; my($dbname) = ($command eq 'createdb' || $command eq 'dropdb') ? shift : ''; my($host, $port) = DBD::mysql->_OdbcParseHost(shift(@_) || ''); my($user) = shift || ''; my($password) = shift || ''; $drh->func(undef, $command, $dbname || '', $host || '', $port || '', $user, $password, '_admin_internal'); } package DBD::mysql::db; # ====== DATABASE ====== use strict; %DBD::mysql::db::db2ANSI = ("INT" => "INTEGER", "CHAR" => "CHAR", "REAL" => "REAL", "IDENT" => "DECIMAL" ); ### ANSI datatype mapping to mSQL datatypes %DBD::mysql::db::ANSI2db = ("CHAR" => "CHAR", "VARCHAR" => "CHAR", "LONGVARCHAR" => "CHAR", "NUMERIC" => "INTEGER", "DECIMAL" => "INTEGER", "BIT" => "INTEGER", "TINYINT" => "INTEGER", "SMALLINT" => "INTEGER", "INTEGER" => "INTEGER", "BIGINT" => "INTEGER", "REAL" => "REAL", "FLOAT" => "REAL", "DOUBLE" => "REAL", "BINARY" => "CHAR", "VARBINARY" => "CHAR", "LONGVARBINARY" => "CHAR", "DATE" => "CHAR", "TIME" => "CHAR", "TIMESTAMP" => "CHAR" ); sub prepare { my($dbh, $statement, $attribs)= @_; # create a 'blank' dbh my $sth = DBI::_new_sth($dbh, {'Statement' => $statement}); # Populate internal handle data. if (!DBD::mysql::st::_prepare($sth, $statement, $attribs)) { $sth = undef; } $sth; } sub db2ANSI { my $self = shift; my $type = shift; return $DBD::mysql::db::db2ANSI{"$type"}; } sub ANSI2db { my $self = shift; my $type = shift; return $DBD::mysql::db::ANSI2db{"$type"}; } sub admin { my($dbh) = shift; my($command) = shift; my($dbname) = ($command eq 'createdb' || $command eq 'dropdb') ? shift : ''; $dbh->{'Driver'}->func($dbh, $command, $dbname, '', '', '', '_admin_internal'); } sub _SelectDB ($$) { die "_SelectDB is removed from this module; use DBI->connect instead."; } { my $names = ['TABLE_CAT', 'TABLE_SCHEM', 'TABLE_NAME', 'TABLE_TYPE', 'REMARKS']; sub table_info ($) { my $dbh = shift; my @tables = map { [ undef, undef, $_, 'TABLE', undef ] } $dbh->func('_ListTables'); my $dbh2; if (!($dbh2 = $dbh->{'~dbd_driver~_sponge_dbh'})) { $dbh2 = $dbh->{'~dbd_driver~_sponge_dbh'} = DBI->connect("DBI:Sponge:"); if (!$dbh2) { DBI::set_err($dbh, 1, $DBI::errstr); return undef; } } my $sth = $dbh2->prepare("LISTTABLES", { 'rows' => \@tables, 'NAMES' => $names }); if (!$sth) { DBI::set_err($sth, $dbh2->err(), $dbh2->errstr()); } $sth; } } package DBD::mysql::st; # ====== STATEMENT ====== use strict; 1; __END__ =head1 NAME DBD::mSQL / DBD::mysql - mSQL and mysql drivers for the Perl5 Database Interface (DBI) =head1 SYNOPSIS use DBI; $driver = "mSQL"; # or "mSQL1"; $dsn = "DBI:$driver:database=$database;host=$hostname"; $dbh = DBI->connect($dsn, undef, undef); or $driver = "mysql"; $dsn = "DBI:$driver:database=$database;host=$hostname;port=$port"; $dbh = DBI->connect($dsn, $user, $password); $drh = DBI->install_driver("mysql"); @databases = $drh->func($host, $port, '_ListDBs'); @tables = $dbh->func( '_ListTables' ); $sth = $dbh->prepare("SELECT * FROM foo WHERE bla"); or $sth = $dbh->prepare("LISTFIELDS $table"); or $sth = $dbh->prepare("LISTINDEX $table $index"); $sth->execute; $numRows = $sth->rows; $numFields = $sth->{'NUM_OF_FIELDS'}; $sth->finish; $rc = $drh->func('createdb', $database, $host, $user, $password, 'admin'); $rc = $drh->func('dropdb', $database, $host, $user, $password, 'admin'); $rc = $drh->func('shutdown', $host, $user, $password, 'admin'); $rc = $drh->func('reload', $host, $user, $password, 'admin'); $rc = $dbh->func('createdb', $database, 'admin'); $rc = $dbh->func('dropdb', $database, 'admin'); $rc = $dbh->func('shutdown', 'admin'); $rc = $dbh->func('reload', 'admin'); =head1 EXPERIMENTAL SOFTWARE This package contains experimental software and should *not* be used in a production environment. We are following the Linux convention and treat the "even" releases (1.18xx as of this writing, perhaps 1.20xx, 1.22xx, ... in the future) as stable. Only bug or portability fixes will go into these releases. The "odd" releases (1.19xx as of this writing, perhaps 1.21xx, 1.23xx in the future) will be used for testing new features or other serious code changes. =head1 DESCRIPTION B and B are the Perl5 Database Interface drivers for the mysql, mSQL 1.I and mSQL 2.I databases. The drivers are part of the I package. In other words: DBD::mSQL and DBD::mysql are an interface between the Perl programming language and the mSQL or mysql programming API that come with the mSQL any mysql relational database management systems. Most functions provided by the respective programming API's are supported. Some rarely used functions are missing, mainly because noone ever requested them. :-) In what follows we first discuss the use of DBD::mysql and DBD::mSQL, because this is what you will need the most. For installation, see the sections on L, L, L and L below. See L for a simple example below. From perl you activate the interface with the statement use DBI; After that you can connect to multiple mSQL or MySQL database servers and send multiple queries to any of them via a simple object oriented interface. Two types of objects are available: database handles and statement handles. Perl returns a database handle to the connect method like so: $dbh = DBI->connect("DBI:mSQL:database=$db;host=$host", undef, undef, {RaiseError => 1}); or $dbh = DBI->connect("DBI:mysql:database=$db;host=$host", $user, $password, {RaiseError => 1}); Once you have connected to a database, you can can execute SQL statements with: my $query = sprintf("INSERT INTO foo VALUES (%d, %s)", $number, $dbh->quote("name")); $dbh->do($query); See L for details on the quote and do methods. An alternative approach is $dbh->do("INSERT INTO foo VALUES (?, ?)", undef, $number, $name); in which case the quote method is executed automatically. See also the bind_param method in L. See L below for more details on database handles. If you want to retrieve results, you need to create a so-called statement handle with: $sth = $dbh->prepare("SELECT * FROM $table"); $sth->execute(); This statement handle can be used for multiple things. First of all you can retreive a row of data: my $row = $sth->fetchow_hashref(); If your table has columns ID and NAME, then $row will be hash ref with keys ID and NAME. See L below for more details on statement handles. But now for a more formal approach: =head2 Class Methods =over 4 =item B use DBI; $driver = "mSQL"; # or "mSQL1" $dsn = "DBI:$driver:$database"; $dsn = "DBI:$driver:database=$database;host=$hostname"; $dbh = DBI->connect($dsn, undef, undef); or $dsn = "DBI:mysql:$database"; $dsn = "DBI:mysql:database=$database;host=$hostname"; $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port"; $dbh = DBI->connect($dsn, $user, $password); A C must always be specified. =over 8 =item host =item port The hostname, if not specified or specified as '', will default to an mysql or mSQL daemon running on the local machine on the default port for the UNIX socket. Should the mysql or mSQL daemon be running on a non-standard port number, you may explicitly state the port number to connect to in the C argument, by concatenating the I and I together separated by a colon ( C<:> ) character or by using the C argument. This doesn't work for mSQL 2: You have to create an alternative config file and load it using the msql_configfile attribute, see below. =item msql_configfile By default mSQL 2 loads its port settings and similar things from the file InstDir/msql.conf. This option allows you to specify another attribute, as in DBI->connect("DBI:mSQL:test;msql_configfile=msql_test.conf"); If the filename is not absolute, mSQL will search in certain other locations, see the documentation of the msqlLoadConfigFile() function in the mSQL manual for details. =item mysql_compression As of MySQL 3.22.3, a new feature is supported: If your DSN contains the option "mysql_compression=1", then the communication between client and server will be compressed. =item mysql_read_default_file =item mysql_read_default_group These options can be used to read a config file like /etc/my.cnf or ~/.my.cnf. By default MySQL's C client library doesn't use any config files unlike the client programs (mysql, mysqladmin, ...) that do, but outside of the C client library. Thus you need to explicitly request reading a config file, as in $dsn = "DBI:mysql:test;mysql_read_default_file=/home/joe/my.cnf"; $dbh = DBI->connect($dsn, $user, $password) The option mysql_read_default_group can be used to specify the default group in the config file: Usually this is the I group, but see the following example: [perl] host=perlhost [client] host=localhost If you read this config file, then you'll be typically connected to I. However, by using $dsn = "DBI:mysql:test;mysql_read_default_group=perl;" . "mysql_read_default_file=/home/joe/my.cnf"; $dbh = DBI->connect($dsn, $user, $password); you'll be connected to I. See the (missing :-) documentation of the C function mysql_options() for details. =item mysql_socket As of MySQL 3.21.15, it is possible to choose the Unix socket that is used for connecting to the server. This is done, for example, with mysql_socket=/dev/mysql Usually there's no need for this option, unless you are using another location for the socket than that built into the client. =back =back =head2 Private MetaData Methods =over 4 =item B my $drh = DBI->install_driver("mysql"); @dbs = $drh->func("$hostname:$port", '_ListDBs'); @dbs = $drh->func($hostname, $port, '_ListDBs'); @dbs = $dbh->func('_ListDBs'); Returns a list of all databases managed by the mysql daemon or mSQL daemon running on C<$hostname>, port C<$port>. This method is rarely needed for databases running on C: You should use the portable method @dbs = DBI->data_sources("mysql"); or @dbs = DBI->data_sources("mSQL"); whenever possible. It is a design problem of this method, that there's no way of supplying a host name or port number to C, that's the only reason why we still support C. :-( =item B *WARNING*: This method is obsolete due to DBI's $dbh->table_info(). @tables = $dbh->func('_ListTables'); Once connected to the desired database on the desired mysql or mSQL mSQL daemon with the Cconnect()> method, we may extract a list of the tables that have been created within that database. C returns an array containing the names of all the tables present within the selected database. If no tables have been created, an empty list is returned. @tables = $dbh->func( '_ListTables' ); foreach $table ( @tables ) { print "Table: $table\n"; } =head2 Server Administration =over 4 =item admin $rc = $drh->func("createdb", $dbname, [host, user, password,], 'admin'); $rc = $drh->func("dropdb", $dbname, [host, user, password,], 'admin'); $rc = $drh->func("shutdown", [host, user, password,], 'admin'); $rc = $drh->func("reload", [host, user, password,], 'admin'); or $rc = $dbh->func("createdb", $dbname, 'admin'); $rc = $dbh->func("dropdb", $dbname, 'admin'); $rc = $dbh->func("shutdown", 'admin'); $rc = $dbh->func("reload", 'admin'); For server administration you need a server connection. For obtaining this connection you have two options: Either use a driver handle (drh) and supply the appropriate arguments (host, defaults localhost, user, defaults to '' and password, defaults to ''). A driver handle can be obtained with $drh = DBI->install_driver('mysql'); Otherwise reuse the existing connection of a database handle (dbh). There's only one function available for administrative purposes, comparable to the m(y)sqladmin programs. The command being execute depends on the first argument: =over 8 =item createdb Creates the database $dbname. Equivalent to "m(y)sqladmin create $dbname". =item dropdb Drops the database $dbname. Equivalent to "m(y)sqladmin drop $dbname". It should be noted that database deletion is I in any way. Nor is it undo-able from DBI. Once you issue the dropDB() method, the database will be gone! These method should be used at your own risk. =item shutdown Silently shuts down the database engine. (Without prompting!) Equivalent to "m(y)sqladmin shutdown". =item reload Reloads the servers configuration files and/or tables. This can be particularly important if you modify access privileges or create new users. =back =back =head1 DATABASE HANDLES The DBD::mysql driver supports the following attributes of database handles (read only): $infoString = $dbh->{'info'}; $threadId = $dbh->{'thread_id'}; $insertId = $dbh->{'mysql_insertid'} These correspond to mysql_info(), mysql_thread_id() and mysql_insertid(), respectively. =head1 STATEMENT HANDLES The statement handles of DBD::mysql and DBD::mSQL support a number of attributes. You access these by using, for example, my $numFields = $sth->{'NUM_OF_FIELDS'}; Note, that most attributes are valid only after a successfull I. An C value will returned in that case. The most important exception is the C attribute: This forces the driver to use mysql_use_result rather than mysql_store_result. The former is faster and less memory consuming, but tends to block other processes. (That's why mysql_store_result is the default.) To set the C attribute, use either of the following: my $sth = $dbh->prepare("QUERY", { "mysql_use_result" => 1}); or my $sth = $dbh->prepare("QUERY"); $sth->{"mysql_use_result"} = 1; Column dependent attributes, for example I, the column names, are returned as a reference to an array. The array indices are corresponding to the indices of the arrays returned by I and similar methods. For example the following code will print a header of table names together with all rows: my $sth = $dbh->prepare("SELECT * FROM $table"); if (!$sth) { die "Error:" . $dbh->errstr . "\n"; } if (!$sth->execute) { die "Error:" . $sth->errstr . "\n"; } my $names = $sth->{'NAME'}; my $numFields = $sth->{'NUM_OF_FIELDS'}; for (my $i = 0; $i < $numFields; $i++) { printf("%s%s", $$names[$i], $i ? "," : ""); } print "\n"; while (my $ref = $sth->fetchrow_arrayref) { for (my $i = 0; $i < $numFields; $i++) { printf("%s%s", $$ref[$i], $i ? "," : ""); } print "\n"; } For portable applications you should restrict yourself to attributes with capitalized or mixed case names. Lower case attribute names are private to DBD::mSQL and DBD::mysql. The attribute list includes: =over 4 =item ChopBlanks this attribute determines whether a I will chop preceding and trailing blanks off the column values. Chopping blanks does not have impact on the I attribute. =item insertid MySQL has the ability to choose unique key values automatically. If this happened, the new ID will be stored in this attribute. This attribute is not valid for DBD::mSQL. An alternative way for accessing this attribute is via $dbh->{'mysql_insertid'}. (Note we are using the $dbh in this case!) =item is_blob Reference to an array of boolean values; TRUE indicates, that the respective column is a blob. This attribute is valid for MySQL only. =item is_key Reference to an array of boolean values; TRUE indicates, that the respective column is a key. This is valid for MySQL only. =item is_num Reference to an array of boolean values; TRUE indicates, that the respective column contains numeric values. =item is_pri_key Reference to an array of boolean values; TRUE indicates, that the respective column is a primary key. This is only valid for MySQL and mSQL 1.0.x: mSQL 2.x uses indices. =item is_not_null A reference to an array of boolean values; FALSE indicates that this column may contain NULL's. You should better use the I attribute above which is a DBI standard. =item length =item max_length A reference to an array of maximum column sizes. The I is the maximum physically present in the result table, I gives the theoretically possible maximum. I is valid for MySQL only. =item NAME A reference to an array of column names. =item NULLABLE A reference to an array of boolean values; TRUE indicates that this column may contain NULL's. =item NUM_OF_FIELDS Number of fields returned by a I