package Mysql;
BEGIN { require 5.003 }
require Mysql::Statement;
use vars qw($VERSION $QUIET @ISA @EXPORT);
$QUIET  = $QUIET  = '';
@ISA    = @ISA    = '';
@EXPORT = @EXPORT = '';
$VERSION = $VERSION = "1.17";

$QUIET = 0;

use Carp ();
use DynaLoader ();
use Exporter ();
@ISA = ('Exporter', 'DynaLoader');

# @EXPORT is a relict from old times...
@EXPORT = qw(
        &CHAR_TYPE
        &INT_TYPE
        &REAL_TYPE
	&FIELD_TYPE_DECIMAL
	&FIELD_TYPE_CHAR
 	&FIELD_TYPE_SHORT
	&FIELD_TYPE_LONG
	&FIELD_TYPE_FLOAT
	&FIELD_TYPE_DOUBLE
	&FIELD_TYPE_NULL
	&FIELD_TYPE_TIMESTAMP
	&FIELD_TYPE_LONGLONG
	&FIELD_TYPE_INT24
	&FIELD_TYPE_DATE
	&FIELD_TYPE_TIME
	&FIELD_TYPE_DATETIME
	&FIELD_TYPE_TINY_BLOB
	&FIELD_TYPE_MEDIUM_BLOB
	&FIELD_TYPE_LONG_BLOB
	&FIELD_TYPE_BLOB
	FIELD_TYPE_VAR_STRING
	FIELD_TYPE_STRING
);
@EXPORT_OK = qw(
        ANY_TYPE
        IDENT_TYPE
        IDX_TYPE
        LAST_REAL_TYPE
        NULL_TYPE
        SYSVAR_TYPE
        TEXT_TYPE
	DATE_TYPE
	TIME_TYPE
           );

sub INT_TYPE			{ constant("INT_TYPE", 0) }
sub CHAR_TYPE			{ constant("CHAR_TYPE", 0) }
sub REAL_TYPE			{ constant("REAL_TYPE", 0) }
sub IDENT_TYPE			{ constant("IDENT_TYPE", 0) }
sub IDX_TYPE			{ constant("IDX_TYPE", 0) }
sub TEXT_TYPE			{ constant("TEXT_TYPE", 0) }
sub DATE_TYPE			{ constant("DATE_TYPE", 0) }
sub TIME_TYPE			{ constant("TIME_TYPE", 0) }
sub FIELD_TYPE_DECIMAL		{ constant("FIELD_TYPE_DECIMAL",0) }
sub FIELD_TYPE_CHAR		{ constant("FIELD_TYPE_CHAR",0) }
sub FIELD_TYPE_SHORT		{ constant("FIELD_TYPE_SHORT",0) }
sub FIELD_TYPE_LONG		{ constant("FIELD_TYPE_LONG",0) }
sub FIELD_TYPE_FLOAT		{ constant("FIELD_TYPE_FLOAT",0) }
sub FIELD_TYPE_DOUBLE		{ constant("FIELD_TYPE_DOUBLE",0) }
sub FIELD_TYPE_NULL		{ constant("FIELD_TYPE_NULL",0) }
sub FIELD_TYPE_TIMESTAMP	{ constant("FIELD_TYPE_TIMESTAMP",0) }
sub FIELD_TYPE_LONGLONG		{ constant("FIELD_TYPE_LONGLONG",0) }
sub FIELD_TYPE_INT24		{ constant("FIELD_TYPE_INT24",0) }
sub FIELD_TYPE_DATE		{ constant("FIELD_TYPE_DATE",0) }
sub FIELD_TYPE_TIME		{ constant("FIELD_TYPE_TIME",0) }
sub FIELD_TYPE_DATETIME		{ constant("FIELD_TYPE_DATETIME",0) }
sub FIELD_TYPE_TINY_BLOB	{ constant("FIELD_TYPE_TINY_BLOB",0) }
sub FIELD_TYPE_MEDIUM_BLOB	{ constant("FIELD_TYPE_MEDIUM_BLOB",0) }
sub FIELD_TYPE_LONG_BLOB	{ constant("FIELD_TYPE_LONG_BLOB",0) }
sub FIELD_TYPE_BLOB		{ constant("FIELD_TYPE_BLOB",0) }
sub FIELD_TYPE_VAR_STRING	{ constant("FIELD_TYPE_VAR_STRING",0) }
sub FIELD_TYPE_STRING		{ constant("FIELD_TYPE_STRING",0) }

sub host     { return shift->{'HOST'} }
sub sock     { return shift->{'SOCK'} }
sub database { return shift->{'DATABASE'} }
sub user     { return shift->{'USER'} }

sub quote   {
    my $self = shift;
    my $str = shift;
    return 'NULL' unless defined $str;
    my $trunc = shift;
    substr($str,$trunc) = '' if defined $trunc and $trunc > 0 and length($str) > $trunc;
    $str =~ s/([\\\'])/\\$1/g;
    $str =~ s/\n/\\n/g;
    $str =~ s/\000/\\0/g;
    "'$str'";
}

sub AUTOLOAD {
    my $meth = $AUTOLOAD;
    $meth =~ s/^.*:://;
    $meth =~ s/_//g;
    $meth = lc($meth);

    TRY: {
      if (defined &$meth) {
          *$meth = \&{$meth};
          return &$meth(@_);
      } elsif ($meth =~ s/(.*)type$/uc($1)."_TYPE"/e) {
          # Try to determine the type that was requested by
          # translating inttype to INT_TYPE Not that I consider it
          # good style to write inttype, but we once allowed it,
          # so...
          redo TRY;
      }
      }
    Carp::croak("$AUTOLOAD: Not defined in Mysql and not autoloadable (last try $meth)");

}

bootstrap Mysql;

1;
__END__

=head1 NAME

Mysql - Perl interface to the MySQL database

=head1 SYNOPSIS

  use Msql;

  $dbh = Msql->connect;
  $dbh = Msql->connect($host);
  $dbh = Msql->connect($host, $database);

  $dbh->selectdb($database);

  @arr = $dbh->listdbs;
  @arr = $dbh->listtables;

  $quoted_string = $dbh->quote($unquoted_string);
  $error_message = $dbh->errmsg;

  $sth = $dbh->listfields($table);
  $sth = $dbh->query($sql_statement);

  @arr = $sth->fetchrow;
  @arr = $sth->fetchcol($colnum);
  %hash = $sth->fetchhash;

  $sth->dataseek($row_number);

  $sth->as_string;

=head1 DESCRIPTION

This package is designed as close as possible to its C API
counterpart. The manual that comes with MySQL describes most things you
need. Due to popular demand it was decided though, that this interface
does not use StudlyCaps (see below).

The version you have selected is an adaption still under development,
please consult the file "Changes" in your distribution. 

Internally you are dealing with the two classes C<Mysql> and
C<Mysql::Statement>. You will never see the latter, because you reach
it through a statement handle returned by a query or a listfields
statement. The only class you name explicitly is Mysql. It offers you
the connect command:

  $dbh = Mysql->connect;
  $dbh = Mysql->connect($host);
  $dbh = Mysql->connect($host, $database);

This connects you with the desired host/database. With no argument or
with an empty string as the first argument it connects to the UNIX
socket (usually /tmp/mysql.sock), which has a much better performance than
the TCP counterpart. A database name as the second argument selects
the chosen database within the connection. The return value is a
database handle if the connect succeeds, otherwise the return value is
undef.

You will need this handle to gain further access to the
database. Issue multiple C<Connect> statements -- no problem.

$dbh->selectdb($database);

If you have not chosen a database with the C<connect> command, or if
you want to change the connection to a different database using a
database handle you have got from a previous C<connect>, then use
selectdb.

  $sth = $dbh->listfields($table);
  $sth = $dbh->query($sql_statement);

These two work rather similar as descibed in the MySQL manual. They
return a statement handle which lets you further explore what the
server has to tell you. On error the return value is undef. The object
returned by listfields will not know about the size of the table, so a
numrows() on it will return the string "N/A";

  @arr = $dbh->listdbs();
  @arr = $dbh->listtables;

An array is returned that contains the requested names without any
further information.

  @arr = $sth->fetchrow;

returns an array of the values of the next row fetched from the
server. Similar does

  %hash = $sth->fetchhash;

return a complete hash. The keys in this hash are the column names of
the table, the values are the table values. Be aware, that when you
have a table with two identical column names, you will not be able to
use this method without trashing one column. In such a case, you
should use the fetchrow method.

  @arr = $sth->fetchcol($colnum);

returns an array of the values of each row for column $colnum.  Note that
this reads the entire table and leaves the row offset at the end of the
table; be sure to use $sth->dataseek() to reset it if you want to
re-examine the table.

  $sth->dataseek($row_number);

lets you specify a certain offset of the data associated with the
statement handle. The next fetchrow will then return the appropriate
row (first row being 0).

=head2 No close statement

Whenever the scalar that holds a database or statement handle looses
its value, Mysql chooses the appropriate action (frees the result or
closes the database connection). So if you want to free the result or
close the connection, choose to do one of the following:

=over 4

=item undef the handle

=item use the handle for another purpose

=item let the handle run out of scope

=item exit the program.

=back

=head2 Error messages

A method in the Mysql class is -E<gt>errmsg(), which returns the
current error message for the used connection.

=head2 The C<-w> switch

With Mysql the C<-w> switch is your friend! If you call your perl
program with the C<-w> switch you get the warnings from -E<gt>errmsg on
STDERR. This is a handy method to get the error messages from the msql
server without coding it into your program.

If you want to know in greater detail what's going on, set the
environment variables that are described in David's manual. David's
debugging aid is excellent, there's nothing to be added.

If you want to use the C<-w> switch but do not want to see the error
messages from the msql daemon, you can set the variable $Mysql::QUIET
to some true value, and they will be supressed.

=head2 -E<gt>quote($str [, $length])

returns the argument enclosed in single ticks ('') with any special
character escaped according to the needs of the API. Currently this
means, any single tick within the string is escaped with a backslash
and backslashes are doubled. ASCII 0 is replaced with \0 and newline
with \n for better readability.

If you pass undefined values to the quote method, it returns the
string C<NULL>.

If a second parameter is passed to C<quote>, the result is truncated
to that many characters.

=head2 NULL fields

NULL fields in tables are returned to perl as undefined values.

=head1 Metadata

Now lets reconsider the above methods with regard to metadata.

=head2 Database Handle

As said above you get a database handle with

  $dbh = Mysql->connect($host,$database,$password,$user);

The database handle knows about the socket, the host, and the database
it is connected to.

You get at the all values, expect the password, with the methods

  $scalar = $dbh->sock;
  $scalar = $dbh->host;
  $scalar = $dbh->database;
  $scalar = $dbh->user;

database returns undef if you have connected without or with only one
argument.

=head2 Statement Handle

Two constructor methods return a statement handle:

  $sth = $dbh->listfields($table);
  $sth = $dbh->query($sql_statement);

$sth knows about all metadata that are provided by the API:

  $scalar  = $sth->numrows;    
  $scalar  = $sth->numfields;  
  $scalar  = $sth->affected_rows   number of rows in database affected by query
  $scalar  = $sth->insert_id	the unique id given to a auto_increment field.
  $string  = $sth->info()	more info from some queries (ALTER TABLE...)
  $arrref  = $sth->table;       the names of the tables of each column
  $arrref  = $sth->name;        the names of the columns
  $arrref  = $sth->type;        the type of each column, defined in mysql.h
		                and accessible via &Mysql::CHAR_TYPE,
		                &Mysql::INT_TYPE, &Mysql::REAL_TYPE,
  $arrref  = $sth->is_not_null; array of boolean
  $arrref  = $sth->is_pri_key;  array of boolean
  $arrref  = $sth->is_num;	array of boolean
  $arrref  = $sth->is_blob;	array of boolean
  $arrref  = $sth->length;      array of the length of each field in bytes

The six last methods return an array in array context and an array
reference (see L<perlref> and L<perlldsc> for details) when called in
a scalar context. The scalar context is useful, if you need only the
name of one column, e.g.

    $name_of_third_column = $sth->name->[2]

which is equivalent to

    @all_column_names = $sth->name;
    $name_of_third_column = $all_column_names[2];

=head2 @EXPORT

For historical reasons the constants CHAR_TYPE, INT_TYPE, and
REAL_TYPE are in @EXPORT instead of @EXPORT_OK. This means, that you
always have them imported into your namespace. I consider it a bug,
but not such a serious one, that I intend to break old programs by
moving them into EXPORT_OK.

=head2 Connecting to a different port

The MySQL API allows you to interface to a different port than the
default that is compiled into your copy. To use this feature you have
to set the environment variable MSQL_TCP_PORT. You can do so at any
time in your program with the command

    $ENV{'MYSQL_TCP_PORT'} = 1234; # or 1112 or 1113 or 4333 or 4334

Any subsequent connect() will establish a connection to the specified
port.

For connect()s to the UNIX socket of the local machine use
MYSQL_UNIX_PORT instead.

=head2 Displaying whole tables in one go

A handy method to show the complete contents of a statement handle is
the as_string method. This works similar to the msql monitor with a
few exceptions:

=over 2

=item the width of a column

is calculated by examining the width of all entries in that column

=item control characters

are mapped into their backslashed octal representation

=item backslashes

are doubled (C<\\ instead of \>)

=item numeric values

are adjusted right (both integer and floating point values)

=back

The differences are illustrated by the following table:

Input to mysql (a real carriage return here replaced with ^M):

    CREATE TABLE demo (
      first_field CHAR(10),
      second_field INT
    ) \g

    INSERT INTO demo VALUES ('new
    line',2)\g
    INSERT INTO demo VALUES ('back\\slash',1)\g
    INSERT INTO demo VALUES ('cr^Mcrnl
    nl',3)\g

Output of mysql:

     +-------------+--------------+
     | first_field | second_field |
     +-------------+--------------+
     | new
    line    | 2            |
     | back\slash  | 1            |
    crnlr
    nl  | 3            |
     +-------------+--------------+

Output of pmsql:

    +----------------+------------+
    |first_field     |second_field|
    +----------------+------------+
    |new\012line     |           2|
    |back\\slash     |           1|
    |cr\015crnl\012nl|           3|
    +----------------+------------+


=head2 Version information

The version of MysqlPerl is always stored in $Mysql::VERSION as it is
perl standard.

The MySQL API implements methods to access some internal configuration
parameters: gethostinfo, getserverinfo, and getprotoinfo.  All three
are available both as class methods or via a database handle. But
under no circumstances they are associated with a database handle. All
three return global variables that reflect the B<last> connect()
command within the current program. This means, that all three return
empty strings or zero I<before> the first call to connect().

=head2 Administration

shutdown, createdb, dropdb, reloadacls are all accessible via a
database handle and implement the corresponding methods to what
msqladmin does.

The MySQL engine does not permit that these commands are invoked by
users that doesn't have the right privileges so please make sure
to check the return and error code when you issue one of them.

=head2 StudlyCaps

Real Perl Programmers (C) usually don't like to type I<ListTables> but
prefer I<list_tables> or I<listtables>. The MySQL API uses StudlyCaps
everywhere and so did early versions of MysqlPerl. Beginning with
$VERSION 1.06 all methods are internally in lowercase, but may be
written however you please. Case is ignored and you may use the
underline to improve readability.

The price for using different method names is neglectible. Any method
name you use that can be transformed into a known one, will only be
defined once within a program and will remain an alias until the
program terminates. So feel free to run fetch_row or connecT or
ListDBs as in your old programs. These, of course, will continue to
work.

=head1 PREREQUISITES

MySQL is a libmysqlclient.a library written by Michael Widenius
This was originally inspired by MySQL.

To use the adaptor you definitely have to install this library first.

=head1 AUTHOR

andreas koenig L<koenig@franz.ww.TU-Berlin.DE>
Patched and enchanted from mSQLperl by Monty (mysql@tcx.se).

=head1 BUGS

mysql does not support Tim Bunce's Database Interface DBI (yet :')

This specific version of the Mysql adaptor is a kind of a hack to
be able to use old Msql scripts. See the file "Changes" in your
distribution.

=cut


