home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / SQLite.pm < prev    next >
Encoding:
Perl POD Document  |  2004-02-14  |  14.5 KB  |  543 lines

  1. # $Id: SQLite.pm,v 1.40 2004/02/14 19:13:51 matt Exp $
  2.  
  3. package DBD::SQLite;
  4. use strict;
  5.  
  6. use DBI;
  7. use vars qw($err $errstr $state $drh $VERSION @ISA);
  8. $VERSION = '0.31';
  9.  
  10. use DynaLoader();
  11. @ISA = ('DynaLoader');
  12.  
  13. __PACKAGE__->bootstrap($VERSION);
  14.  
  15. $drh = undef;
  16.  
  17. sub driver {
  18.     return $drh if $drh;
  19.     my ($class, $attr) = @_;
  20.  
  21.     $class .= "::dr";
  22.  
  23.     $drh = DBI::_new_drh($class, {
  24.         Name        => 'SQLite',
  25.         Version     => $VERSION,
  26.         Attribution => 'DBD::SQLite by Matt Sergeant',
  27.     });
  28.  
  29.     return $drh;
  30. }
  31.  
  32. sub CLONE {
  33.     undef $drh;
  34. }
  35.  
  36. package DBD::SQLite::dr;
  37.  
  38. sub connect {
  39.     my ($drh, $dbname, $user, $auth, $attr) = @_;
  40.  
  41.     my $dbh = DBI::_new_dbh($drh, {
  42.         Name => $dbname,
  43.         });
  44.  
  45.     my $real_dbname = $dbname;
  46.     if ($dbname =~ /=/) {
  47.         foreach my $attrib (split(/;/, $dbname)) {
  48.             my ($k, $v) = split(/=/, $attrib, 2);
  49.             if ($k eq 'dbname') {
  50.                 $real_dbname = $v;
  51.             }
  52.             else {
  53.                 # TODO: add to attribs
  54.             }
  55.         }
  56.     }
  57.     DBD::SQLite::db::_login($dbh, $real_dbname, $user, $auth)
  58.         or return undef;
  59.  
  60.     return $dbh;
  61. }
  62.  
  63. package DBD::SQLite::db;
  64.  
  65. sub prepare {
  66.     my ($dbh, $statement, @attribs) = @_;
  67.  
  68.     my $sth = DBI::_new_sth($dbh, {
  69.         Statement => $statement,
  70.     });
  71.  
  72.     DBD::SQLite::st::_prepare($sth, $statement, @attribs)
  73.         or return undef;
  74.  
  75.     return $sth;
  76. }
  77.  
  78.  
  79. sub table_info {
  80.     my ($dbh, $CatVal, $SchVal, $TblVal, $TypVal) = @_;
  81.     # SQL/CLI (ISO/IEC JTC 1/SC 32 N 0595), 6.63 Tables
  82.     # Based on DBD::Oracle's
  83.     # See also http://www.ch-werner.de/sqliteodbc/html/sqliteodbc_8c.html#a117
  84.  
  85.     my @Where = ();
  86.     my $Sql;
  87.     if (   defined($CatVal) && $CatVal eq '%'
  88.        && defined($SchVal) && $SchVal eq '' 
  89.        && defined($TblVal) && $TblVal eq '')  { # Rule 19a
  90.             $Sql = <<'SQL';
  91. SELECT NULL TABLE_CAT
  92.      , NULL TABLE_SCHEM
  93.      , NULL TABLE_NAME
  94.      , NULL TABLE_TYPE
  95.      , NULL REMARKS
  96. SQL
  97.     }
  98.     elsif (   defined($SchVal) && $SchVal eq '%' 
  99.           && defined($CatVal) && $CatVal eq '' 
  100.           && defined($TblVal) && $TblVal eq '') { # Rule 19b
  101.             $Sql = <<'SQL';
  102. SELECT NULL      TABLE_CAT
  103.      , NULL      TABLE_SCHEM
  104.      , NULL      TABLE_NAME
  105.      , NULL      TABLE_TYPE
  106.      , NULL      REMARKS
  107. SQL
  108.     }
  109.     elsif (    defined($TypVal) && $TypVal eq '%' 
  110.            && defined($CatVal) && $CatVal eq '' 
  111.            && defined($SchVal) && $SchVal eq '' 
  112.            && defined($TblVal) && $TblVal eq '') { # Rule 19c
  113.             $Sql = <<'SQL';
  114. SELECT NULL TABLE_CAT
  115.      , NULL TABLE_SCHEM
  116.      , NULL TABLE_NAME
  117.      , t.tt TABLE_TYPE
  118.      , NULL REMARKS
  119. FROM (
  120.      SELECT 'TABLE' tt                  UNION
  121.      SELECT 'VIEW' tt                   UNION
  122.      SELECT 'LOCAL TEMPORARY' tt
  123. ) t
  124. ORDER BY TABLE_TYPE
  125. SQL
  126.     }
  127.     else {
  128.             $Sql = <<'SQL';
  129. SELECT *
  130. FROM
  131. (
  132. SELECT NULL         TABLE_CAT
  133.      , NULL         TABLE_SCHEM
  134.      , tbl_name     TABLE_NAME
  135.      ,              TABLE_TYPE
  136.      , NULL         REMARKS
  137.      , sql          sqlite_sql
  138. FROM (
  139.     SELECT tbl_name, upper(type) TABLE_TYPE, sql
  140.     FROM sqlite_master
  141.     WHERE type IN ( 'table','view')
  142. UNION ALL
  143.     SELECT tbl_name, 'LOCAL TEMPORARY' TABLE_TYPE, sql
  144.     FROM sqlite_temp_master
  145.     WHERE type IN ( 'table','view')
  146. UNION ALL
  147.     SELECT 'sqlite_master'      tbl_name, 'SYSTEM TABLE' TABLE_TYPE, NULL sql
  148. UNION ALL
  149.     SELECT 'sqlite_temp_master' tbl_name, 'SYSTEM TABLE' TABLE_TYPE, NULL sql
  150. )
  151. )
  152. SQL
  153.             if ( defined $TblVal ) {
  154.                     push @Where, "TABLE_NAME  LIKE '$TblVal'";
  155.             }
  156.             if ( defined $TypVal ) {
  157.                     my $table_type_list;
  158.                     $TypVal =~ s/^\s+//;
  159.                     $TypVal =~ s/\s+$//;
  160.                     my @ttype_list = split (/\s*,\s*/, $TypVal);
  161.                     foreach my $table_type (@ttype_list) {
  162.                             if ($table_type !~ /^'.*'$/) {
  163.                                     $table_type = "'" . $table_type . "'";
  164.                             }
  165.                             $table_type_list = join(", ", @ttype_list);
  166.                     }
  167.                     push @Where, "TABLE_TYPE IN (\U$table_type_list)"
  168.             if $table_type_list;
  169.             }
  170.             $Sql .= ' WHERE ' . join("\n   AND ", @Where ) . "\n" if @Where;
  171.             $Sql .= " ORDER BY TABLE_TYPE, TABLE_SCHEM, TABLE_NAME\n";
  172.     }
  173.     my $sth = $dbh->prepare($Sql) or return undef;
  174.     $sth->execute or return undef;
  175.     $sth;
  176. }
  177.  
  178.  
  179. sub primary_key_info {
  180.     my($dbh, $catalog, $schema, $table) = @_;
  181.  
  182.     my @pk_info;
  183.  
  184.     my $sth_tables = $dbh->table_info($catalog, $schema, $table, '');
  185.  
  186.     # this is a hack but much simpler than using pragma index_list etc
  187.     # also the pragma doesn't list 'INTEGER PRIMARK KEY' autoinc PKs!
  188.     while ( my $row = $sth_tables->fetchrow_hashref ) {
  189.         my $sql = $row->{sqlite_sql} or next;
  190.     next unless $sql =~ /(.*?)\s*PRIMARY\s+KEY\s*(?:\(\s*(.*?)\s*\))?/si;
  191.     my @pk = split /\s*,\s*/, $2 || '';
  192.     unless (@pk) {
  193.         my $prefix = $1;
  194.         $prefix =~ s/.*create\s+table\s+.*?\(//i;
  195.         $prefix = (split /\s*,\s*/, $prefix)[-1];
  196.         @pk = (split /\s+/, $prefix)[0]; # take first word as name
  197.     }
  198.     #warn "GOT PK $row->{TABLE_NAME} (@pk)\n";
  199.     my $key_seq = 0;
  200.     for my $pk_field (@pk) {
  201.         push @pk_info, {
  202.         TABLE_SCHEM => $row->{TABLE_SCHEM},
  203.         TABLE_NAME  => $row->{TABLE_NAME},
  204.         COLUMN_NAME => $pk_field,
  205.         KEY_SEQ => ++$key_seq,
  206.         PK_NAME => 'PRIMARY KEY',
  207.         };
  208.     }
  209.     }
  210.  
  211.     my $sponge = DBI->connect("DBI:Sponge:", '','')
  212.         or return $dbh->DBI::set_err($DBI::err, "DBI::Sponge: $DBI::errstr");
  213.     my @names = qw(TABLE_CAT TABLE_SCHEM TABLE_NAME COLUMN_NAME KEY_SEQ PK_NAME);
  214.     my $sth = $sponge->prepare("column_info $table", {
  215.         rows => [ map { [ @{$_}{@names} ] } @pk_info ],
  216.         NUM_OF_FIELDS => scalar @names,
  217.         NAME => \@names,
  218.     }) or return $dbh->DBI::set_err($sponge->err(), $sponge->errstr());
  219.     return $sth;
  220. }
  221.  
  222. sub type_info_all {
  223.     my ($dbh) = @_;
  224. return; # XXX code just copied from DBD::Oracle, not yet thought about
  225.     my $names = {
  226.     TYPE_NAME    => 0,
  227.     DATA_TYPE    => 1,
  228.     COLUMN_SIZE    => 2,
  229.     LITERAL_PREFIX    => 3,
  230.     LITERAL_SUFFIX    => 4,
  231.     CREATE_PARAMS    => 5,
  232.     NULLABLE    => 6,
  233.     CASE_SENSITIVE    => 7,
  234.     SEARCHABLE    => 8,
  235.     UNSIGNED_ATTRIBUTE    => 9,
  236.     FIXED_PREC_SCALE    =>10,
  237.     AUTO_UNIQUE_VALUE    =>11,
  238.     LOCAL_TYPE_NAME    =>12,
  239.     MINIMUM_SCALE    =>13,
  240.     MAXIMUM_SCALE    =>14,
  241.     SQL_DATA_TYPE    =>15,
  242.     SQL_DATETIME_SUB=>16,
  243.     NUM_PREC_RADIX    =>17,
  244.     };
  245.     my $ti = [
  246.       $names,
  247.       [ 'CHAR', 1, 255, '\'', '\'', 'max length', 1, 1, 3,
  248.     undef, '0', '0', undef, undef, undef, 1, undef, undef
  249.       ],
  250.       [ 'NUMBER', 3, 38, undef, undef, 'precision,scale', 1, '0', 3,
  251.     '0', '0', '0', undef, '0', 38, 3, undef, 10
  252.       ],
  253.       [ 'DOUBLE', 8, 15, undef, undef, undef, 1, '0', 3,
  254.     '0', '0', '0', undef, undef, undef, 8, undef, 10
  255.       ],
  256.       [ 'DATE', 9, 19, '\'', '\'', undef, 1, '0', 3,
  257.     undef, '0', '0', undef, '0', '0', 11, undef, undef
  258.       ],
  259.       [ 'VARCHAR', 12, 1024*1024, '\'', '\'', 'max length', 1, 1, 3,
  260.     undef, '0', '0', undef, undef, undef, 12, undef, undef
  261.       ]
  262.     ];
  263.     return $ti;
  264. }
  265.  
  266.  
  267. 1;
  268. __END__
  269.  
  270. =head1 NAME
  271.  
  272. DBD::SQLite - Self Contained RDBMS in a DBI Driver
  273.  
  274. =head1 SYNOPSIS
  275.  
  276.   use DBI;
  277.   my $dbh = DBI->connect("dbi:SQLite:dbname=dbfile","","");
  278.  
  279. =head1 DESCRIPTION
  280.  
  281. SQLite is a public domain RDBMS database engine that you can find
  282. at http://www.hwaci.com/sw/sqlite/.
  283.  
  284. Rather than ask you to install SQLite first, because SQLite is public
  285. domain, DBD::SQLite includes the entire thing in the distribution. So
  286. in order to get a fast transaction capable RDBMS working for your
  287. perl project you simply have to install this module, and B<nothing>
  288. else.
  289.  
  290. SQLite supports the following features:
  291.  
  292. =over 4
  293.  
  294. =item Implements a large subset of SQL92
  295.  
  296. See http://www.hwaci.com/sw/sqlite/lang.html for details.
  297.  
  298. =item A complete DB in a single disk file
  299.  
  300. Everything for your database is stored in a single disk file, making it
  301. easier to move things around than with DBD::CSV.
  302.  
  303. =item Atomic commit and rollback
  304.  
  305. Yes, DBD::SQLite is small and light, but it supports full transactions!
  306.  
  307. =item Extensible
  308.  
  309. User-defined aggregate or regular functions can be registered with the
  310. SQL parser.
  311.  
  312. =back
  313.  
  314. There's lots more to it, so please refer to the docs on the SQLite web
  315. page, listed above, for SQL details. Also refer to L<DBI> for details
  316. on how to use DBI itself.
  317.  
  318. =head1 CONFORMANCE WITH DBI SPECIFICATION
  319.  
  320. The API works like every DBI module does. Please see L<DBI> for more
  321. details about core features.
  322.  
  323. Currently many statement attributes are not implemented or are
  324. limited by the typeless nature of the SQLite database.
  325.  
  326. =head1 DRIVER PRIVATE ATTRIBUTES
  327.  
  328. =head2 Database Handle Attributes
  329.  
  330. =over 4
  331.  
  332. =item sqlite_version
  333.  
  334. Returns the version of the SQLite library which DBD::SQLite is using, e.g., "2.8.0".
  335.  
  336. =item sqlite_encoding
  337.  
  338. Returns either "UTF-8" or "iso8859" to indicate how the SQLite library was compiled.
  339.  
  340. =item sqlite_handle_binary_nulls
  341.  
  342. Set this attribute to 1 to transparently handle binary nulls in quoted
  343. and returned data.
  344.  
  345. B<NOTE:> This will cause all backslash characters (C<\>) to be doubled
  346. up in all columns regardless of whether or not they contain binary
  347. data or not. This may break your database if you use it from another
  348. application. This does not use the built in sqlite_encode_binary
  349. and sqlite_decode_binary functions, which may be considered a bug.
  350.  
  351. =back
  352.  
  353. =head1 DRIVER PRIVATE METHODS
  354.  
  355. =head2 $dbh->func('last_insert_rowid')
  356.  
  357. This method returns the last inserted rowid. If you specify an INTEGER PRIMARY
  358. KEY as the first column in your table, that is the column that is returned.
  359. Otherwise, it is the hidden ROWID column. See the sqlite docs for details.
  360.  
  361. =head2 $dbh->func( $name, $argc, $func_ref, "create_function" )
  362.  
  363. This method will register a new function which will be useable in SQL
  364. query. The method's parameters are:
  365.  
  366. =over
  367.  
  368. =item $name
  369.  
  370. The name of the function. This is the name of the function as it will
  371. be used from SQL.
  372.  
  373. =item $argc
  374.  
  375. The number of arguments taken by the function. If this number is -1,
  376. the function can take any number of arguments.
  377.  
  378. =item $func_ref
  379.  
  380. This should be a reference to the function's implementation.
  381.  
  382. =back
  383.  
  384. For example, here is how to define a now() function which returns the
  385. current number of seconds since the epoch:
  386.  
  387.     $dbh->func( 'now', 0, sub { return time }, 'create_function' );
  388.  
  389. After this, it could be use from SQL as:
  390.  
  391.     INSERT INTO mytable ( now() );
  392.  
  393. =head2 $dbh->func( $name, $argc, $pkg, 'create_aggregate' )
  394.  
  395. This method will register a new aggregate function which can then used
  396. from SQL. The method's parameters are:
  397.  
  398. =over
  399.  
  400. =item $name
  401.  
  402. The name of the aggregate function, this is the name under which the
  403. function will be available from SQL.
  404.  
  405. =item $argc
  406.  
  407. This is an integer which tells the SQL parser how many arguments the
  408. function takes. If that number is -1, the function can take any number
  409. of arguments.
  410.  
  411. =item $pkg
  412.  
  413. This is the package which implements the aggregator interface.
  414.  
  415. =back
  416.  
  417. The aggregator interface consists of defining three methods:
  418.  
  419. =over
  420.  
  421. =item new()
  422.  
  423. This method will be called once to create an object which should
  424. be used to aggregate the rows in a particular group. The step() and
  425. finalize() methods will be called upon the reference return by
  426. the method.
  427.  
  428. =item step(@_)
  429.  
  430. This method will be called once for each rows in the aggregate.
  431.  
  432. =item finalize()
  433.  
  434. This method will be called once all rows in the aggregate were
  435. processed and it should return the aggregate function's result. When
  436. there is no rows in the aggregate, finalize() will be called right
  437. after new().
  438.  
  439. =back
  440.  
  441. Here is a simple aggregate function which returns the variance
  442. (example adapted from pysqlite):
  443.  
  444.     package variance;
  445.  
  446.     sub new { bless [], shift; }
  447.  
  448.     sub step {
  449.         my ( $self, $value ) = @_;
  450.  
  451.         push @$self, $value;
  452.     }
  453.  
  454.     sub finalize {
  455.         my $self = $_[0];
  456.  
  457.         my $n = @$self;
  458.  
  459.         # Variance is NULL unless there is more than one row
  460.         return undef unless $n || $n == 1;
  461.  
  462.         my $mu = 0;
  463.         foreach my $v ( @$self ) {
  464.             $mu += $v;
  465.         }
  466.         $mu /= $n;
  467.  
  468.         my $sigma = 0;
  469.         foreach my $v ( @$self ) {
  470.             $sigma += ($x - $mu)**2;
  471.         }
  472.         $sigma = $sigma / ($n - 1);
  473.  
  474.         return $sigma;
  475.     }
  476.  
  477.     $dbh->func( "variance", 1, 'variance', "create_aggregate" );
  478.  
  479. The aggregate function can then be used as:
  480.  
  481.     SELECT group_name, variance(score) FROM results
  482.     GROUP BY group_name;
  483.  
  484. =head1 NOTES
  485.  
  486. To access the database from the command line, try using dbish which comes with
  487. the DBI module. Just type:
  488.  
  489.   dbish dbi:SQLite:foo.db
  490.  
  491. On the command line to access the file F<foo.db>.
  492.  
  493. Alternatively you can install SQLite from the link above without conflicting
  494. with DBD::SQLite and use the supplied C<sqlite> command line tool.
  495.  
  496. =head1 PERFORMANCE
  497.  
  498. SQLite is fast, very fast. I recently processed my 72MB log file with it,
  499. inserting the data (400,000+ rows) by using transactions and only committing
  500. every 1000 rows (otherwise the insertion is quite slow), and then performing
  501. queries on the data.
  502.  
  503. Queries like count(*) and avg(bytes) took fractions of a second to return,
  504. but what surprised me most of all was:
  505.  
  506.   SELECT url, count(*) as count FROM access_log
  507.     GROUP BY url
  508.     ORDER BY count desc
  509.     LIMIT 20
  510.  
  511. To discover the top 20 hit URLs on the site (http://axkit.org), and it
  512. returned within 2 seconds. I'm seriously considering switching my log
  513. analysis code to use this little speed demon!
  514.  
  515. Oh yeah, and that was with no indexes on the table, on a 400MHz PIII.
  516.  
  517. For best performance be sure to tune your hdparm settings if you are
  518. using linux. Also you might want to set:
  519.  
  520.   PRAGMA default_synchronous = OFF
  521.  
  522. Which will prevent sqlite from doing fsync's when writing (which
  523. slows down non-transactional writes significantly) at the expense of some
  524. peace of mind. Also try playing with the cache_size pragma.
  525.  
  526. =head1 BUGS
  527.  
  528. Likely to be many, please use http://rt.cpan.org/ for reporting bugs.
  529.  
  530. =head1 AUTHOR
  531.  
  532. Matt Sergeant, matt@sergeant.org
  533.  
  534. Perl extension functions contributed by Francis J. Lacoste
  535. <flacoste@logreport.org> and Wolfgang Sourdeau
  536. <wolfgang@logreport.org>
  537.  
  538. =head1 SEE ALSO
  539.  
  540. L<DBI>.
  541.  
  542. =cut
  543.