source: subversion/trunk/roundcubemail/program/lib/MDB2/Driver/sqlite.php @ 3227

Last change on this file since 3227 was 3227, checked in by alec, 3 years ago
  • Add support for MDB2's 'sqlsrv' driver (#1486395)
File size: 38.8 KB
Line 
1<?php
2// vim: set et ts=4 sw=4 fdm=marker:
3// +----------------------------------------------------------------------+
4// | PHP versions 4 and 5                                                 |
5// +----------------------------------------------------------------------+
6// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
7// | Stig. S. Bakken, Lukas Smith                                         |
8// | All rights reserved.                                                 |
9// +----------------------------------------------------------------------+
10// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
11// | API as well as database abstraction for PHP applications.            |
12// | This LICENSE is in the BSD license style.                            |
13// |                                                                      |
14// | Redistribution and use in source and binary forms, with or without   |
15// | modification, are permitted provided that the following conditions   |
16// | are met:                                                             |
17// |                                                                      |
18// | Redistributions of source code must retain the above copyright       |
19// | notice, this list of conditions and the following disclaimer.        |
20// |                                                                      |
21// | Redistributions in binary form must reproduce the above copyright    |
22// | notice, this list of conditions and the following disclaimer in the  |
23// | documentation and/or other materials provided with the distribution. |
24// |                                                                      |
25// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
26// | Lukas Smith nor the names of his contributors may be used to endorse |
27// | or promote products derived from this software without specific prior|
28// | written permission.                                                  |
29// |                                                                      |
30// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
31// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
32// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
33// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
34// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
35// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
36// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
37// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
38// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
39// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
40// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
41// | POSSIBILITY OF SUCH DAMAGE.                                          |
42// +----------------------------------------------------------------------+
43// | Author: Lukas Smith <smith@pooteeweet.org>                           |
44// +----------------------------------------------------------------------+
45//
46// $Id: sqlite.php 292715 2009-12-28 14:06:34Z quipo $
47//
48
49/**
50 * MDB2 SQLite driver
51 *
52 * @package MDB2
53 * @category Database
54 * @author  Lukas Smith <smith@pooteeweet.org>
55 */
56class MDB2_Driver_sqlite extends MDB2_Driver_Common
57{
58    // {{{ properties
59    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);
60
61    var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
62
63    var $_lasterror = '';
64
65    var $fix_assoc_fields_names = false;
66
67    // }}}
68    // {{{ constructor
69
70    /**
71     * Constructor
72     */
73    function __construct()
74    {
75        parent::__construct();
76
77        $this->phptype = 'sqlite';
78        $this->dbsyntax = 'sqlite';
79
80        $this->supported['sequences'] = 'emulated';
81        $this->supported['indexes'] = true;
82        $this->supported['affected_rows'] = true;
83        $this->supported['summary_functions'] = true;
84        $this->supported['order_by_text'] = true;
85        $this->supported['current_id'] = 'emulated';
86        $this->supported['limit_queries'] = true;
87        $this->supported['LOBs'] = true;
88        $this->supported['replace'] = true;
89        $this->supported['transactions'] = true;
90        $this->supported['savepoints'] = false;
91        $this->supported['sub_selects'] = true;
92        $this->supported['triggers'] = true;
93        $this->supported['auto_increment'] = true;
94        $this->supported['primary_key'] = false; // requires alter table implementation
95        $this->supported['result_introspection'] = false; // not implemented
96        $this->supported['prepared_statements'] = 'emulated';
97        $this->supported['identifier_quoting'] = true;
98        $this->supported['pattern_escaping'] = false;
99        $this->supported['new_link'] = false;
100
101        $this->options['DBA_username'] = false;
102        $this->options['DBA_password'] = false;
103        $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off';
104        $this->options['fixed_float'] = 0;
105        $this->options['database_path'] = '';
106        $this->options['database_extension'] = '';
107        $this->options['server_version'] = '';
108        $this->options['max_identifiers_length'] = 128; //no real limit
109    }
110
111    // }}}
112    // {{{ errorInfo()
113
114    /**
115     * This method is used to collect information about an error
116     *
117     * @param integer $error
118     * @return array
119     * @access public
120     */
121    function errorInfo($error = null)
122    {
123        $native_code = null;
124        if ($this->connection) {
125            $native_code = @sqlite_last_error($this->connection);
126        }
127        $native_msg = $this->_lasterror
128            ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code);
129           
130        // PHP 5.2+ prepends the function name to $php_errormsg, so we need
131        // this hack to work around it, per bug #9599.
132        $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg);
133
134        if (null === $error) {
135            static $error_regexps;
136            if (empty($error_regexps)) {
137                $error_regexps = array(
138                    '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE,
139                    '/^no such index:/' => MDB2_ERROR_NOT_FOUND,
140                    '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS,
141                    '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT,
142                    '/is not unique/' => MDB2_ERROR_CONSTRAINT,
143                    '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT,
144                    '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,
145                    '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,
146                    '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,
147                    '/no column named/' => MDB2_ERROR_NOSUCHFIELD,
148                    '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,
149                    '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,
150                    '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,
151                 );
152            }
153            foreach ($error_regexps as $regexp => $code) {
154                if (preg_match($regexp, $native_msg)) {
155                    $error = $code;
156                    break;
157                }
158            }
159        }
160        return array($error, $native_code, $native_msg);
161    }
162
163    // }}}
164    // {{{ escape()
165
166    /**
167     * Quotes a string so it can be safely used in a query. It will quote
168     * the text so it can safely be used within a query.
169     *
170     * @param   string  the input string to quote
171     * @param   bool    escape wildcards
172     *
173     * @return  string  quoted string
174     *
175     * @access  public
176     */
177    function escape($text, $escape_wildcards = false)
178    {
179        $text = @sqlite_escape_string($text);
180        return $text;
181    }
182
183    // }}}
184    // {{{ beginTransaction()
185
186    /**
187     * Start a transaction or set a savepoint.
188     *
189     * @param   string  name of a savepoint to set
190     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
191     *
192     * @access  public
193     */
194    function beginTransaction($savepoint = null)
195    {
196        $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
197        if (null !== $savepoint) {
198            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
199                'savepoints are not supported', __FUNCTION__);
200        }
201        if ($this->in_transaction) {
202            return MDB2_OK;  //nothing to do
203        }
204        if (!$this->destructor_registered && $this->opened_persistent) {
205            $this->destructor_registered = true;
206            register_shutdown_function('MDB2_closeOpenTransactions');
207        }
208        $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name'];
209        $result =& $this->_doQuery($query, true);
210        if (PEAR::isError($result)) {
211            return $result;
212        }
213        $this->in_transaction = true;
214        return MDB2_OK;
215    }
216
217    // }}}
218    // {{{ commit()
219
220    /**
221     * Commit the database changes done during a transaction that is in
222     * progress or release a savepoint. This function may only be called when
223     * auto-committing is disabled, otherwise it will fail. Therefore, a new
224     * transaction is implicitly started after committing the pending changes.
225     *
226     * @param   string  name of a savepoint to release
227     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
228     *
229     * @access  public
230     */
231    function commit($savepoint = null)
232    {
233        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
234        if (!$this->in_transaction) {
235            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
236                'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
237        }
238        if (null !== $savepoint) {
239            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
240                'savepoints are not supported', __FUNCTION__);
241        }
242
243        $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];
244        $result =& $this->_doQuery($query, true);
245        if (PEAR::isError($result)) {
246            return $result;
247        }
248        $this->in_transaction = false;
249        return MDB2_OK;
250    }
251
252    // }}}
253    // {{{
254
255    /**
256     * Cancel any database changes done during a transaction or since a specific
257     * savepoint that is in progress. This function may only be called when
258     * auto-committing is disabled, otherwise it will fail. Therefore, a new
259     * transaction is implicitly started after canceling the pending changes.
260     *
261     * @param   string  name of a savepoint to rollback to
262     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
263     *
264     * @access  public
265     */
266    function rollback($savepoint = null)
267    {
268        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
269        if (!$this->in_transaction) {
270            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
271                'rollback cannot be done changes are auto committed', __FUNCTION__);
272        }
273        if (null !== $savepoint) {
274            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
275                'savepoints are not supported', __FUNCTION__);
276        }
277
278        $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];
279        $result =& $this->_doQuery($query, true);
280        if (PEAR::isError($result)) {
281            return $result;
282        }
283        $this->in_transaction = false;
284        return MDB2_OK;
285    }
286
287    // }}}
288    // {{{ function setTransactionIsolation()
289
290    /**
291     * Set the transacton isolation level.
292     *
293     * @param   string  standard isolation level
294     *                  READ UNCOMMITTED (allows dirty reads)
295     *                  READ COMMITTED (prevents dirty reads)
296     *                  REPEATABLE READ (prevents nonrepeatable reads)
297     *                  SERIALIZABLE (prevents phantom reads)
298     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
299     *
300     * @access  public
301     * @since   2.1.1
302     */
303    function setTransactionIsolation($isolation)
304    {
305        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
306        switch ($isolation) {
307        case 'READ UNCOMMITTED':
308            $isolation = 0;
309            break;
310        case 'READ COMMITTED':
311        case 'REPEATABLE READ':
312        case 'SERIALIZABLE':
313            $isolation = 1;
314            break;
315        default:
316            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
317                'isolation level is not supported: '.$isolation, __FUNCTION__);
318        }
319
320        $query = "PRAGMA read_uncommitted=$isolation";
321        return $this->_doQuery($query, true);
322    }
323
324    // }}}
325    // {{{ getDatabaseFile()
326
327    /**
328     * Builds the string with path+dbname+extension
329     *
330     * @return string full database path+file
331     * @access protected
332     */
333    function _getDatabaseFile($database_name)
334    {
335        if ($database_name === '' || $database_name === ':memory:') {
336            return $database_name;
337        }
338        return $this->options['database_path'].$database_name.$this->options['database_extension'];
339    }
340
341    // }}}
342    // {{{ connect()
343
344    /**
345     * Connect to the database
346     *
347     * @return true on success, MDB2 Error Object on failure
348     **/
349    function connect()
350    {
351        $database_file = $this->_getDatabaseFile($this->database_name);
352        if (is_resource($this->connection)) {
353            //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
354            if (MDB2::areEquals($this->connected_dsn, $this->dsn)
355                && $this->connected_database_name == $database_file
356                && $this->opened_persistent == $this->options['persistent']
357            ) {
358                return MDB2_OK;
359            }
360            $this->disconnect(false);
361        }
362
363        if (!PEAR::loadExtension($this->phptype)) {
364            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
365                'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
366        }
367
368        if (empty($this->database_name)) {
369            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
370            'unable to establish a connection', __FUNCTION__);
371        }
372
373        if ($database_file !== ':memory:') {
374            if (!file_exists($database_file)) {
375                if (!touch($database_file)) {
376                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
377                        'Could not create database file', __FUNCTION__);
378                }
379                if (!isset($this->dsn['mode'])
380                    || !is_numeric($this->dsn['mode'])
381                ) {
382                    $mode = 0644;
383                } else {
384                    $mode = octdec($this->dsn['mode']);
385                }
386                if (!chmod($database_file, $mode)) {
387                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
388                        'Could not be chmodded database file', __FUNCTION__);
389                }
390                if (!file_exists($database_file)) {
391                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
392                        'Could not be found database file', __FUNCTION__);
393                }
394            }
395            if (!is_file($database_file)) {
396                return $this->raiseError(MDB2_ERROR_INVALID, null, null,
397                        'Database is a directory name', __FUNCTION__);
398            }
399            if (!is_readable($database_file)) {
400                return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,
401                        'Could not read database file', __FUNCTION__);
402            }
403        }
404
405        $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');
406        $php_errormsg = '';
407        if (version_compare('5.1.0', PHP_VERSION, '>')) {
408            @ini_set('track_errors', true);
409            $connection = @$connect_function($database_file);
410            @ini_restore('track_errors');
411        } else {
412            $connection = @$connect_function($database_file, 0666, $php_errormsg);
413        }
414        $this->_lasterror = $php_errormsg;
415        if (!$connection) {
416            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
417            'unable to establish a connection', __FUNCTION__);
418        }
419
420        if ($this->fix_assoc_fields_names ||
421            $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES)
422        {
423            @sqlite_query("PRAGMA short_column_names = 1", $connection);
424            $this->fix_assoc_fields_names = true;
425        }
426
427        $this->connection = $connection;
428        $this->connected_dsn = $this->dsn;
429        $this->connected_database_name = $database_file;
430        $this->opened_persistent = $this->getoption('persistent');
431        $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
432
433        return MDB2_OK;
434    }
435
436    // }}}
437    // {{{ databaseExists()
438
439    /**
440     * check if given database name is exists?
441     *
442     * @param string $name    name of the database that should be checked
443     *
444     * @return mixed true/false on success, a MDB2 error on failure
445     * @access public
446     */
447    function databaseExists($name)
448    {
449        $database_file = $this->_getDatabaseFile($name);
450        $result = file_exists($database_file);
451        return $result;
452    }
453
454    // }}}
455    // {{{ disconnect()
456
457    /**
458     * Log out and disconnect from the database.
459     *
460     * @param  boolean $force if the disconnect should be forced even if the
461     *                        connection is opened persistently
462     * @return mixed true on success, false if not connected and error
463     *                object on error
464     * @access public
465     */
466    function disconnect($force = true)
467    {
468        if (is_resource($this->connection)) {
469            if ($this->in_transaction) {
470                $dsn = $this->dsn;
471                $database_name = $this->database_name;
472                $persistent = $this->options['persistent'];
473                $this->dsn = $this->connected_dsn;
474                $this->database_name = $this->connected_database_name;
475                $this->options['persistent'] = $this->opened_persistent;
476                $this->rollback();
477                $this->dsn = $dsn;
478                $this->database_name = $database_name;
479                $this->options['persistent'] = $persistent;
480            }
481
482            if (!$this->opened_persistent || $force) {
483                @sqlite_close($this->connection);
484            }
485        } else {
486            return false;
487        }
488        return parent::disconnect($force);
489    }
490
491    // }}}
492    // {{{ _doQuery()
493
494    /**
495     * Execute a query
496     * @param string $query  query
497     * @param boolean $is_manip  if the query is a manipulation query
498     * @param resource $connection
499     * @param string $database_name
500     * @return result or error object
501     * @access protected
502     */
503    function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
504    {
505        $this->last_query = $query;
506        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
507        if ($result) {
508            if (PEAR::isError($result)) {
509                return $result;
510            }
511            $query = $result;
512        }
513        if ($this->options['disable_query']) {
514            $result = $is_manip ? 0 : null;
515            return $result;
516        }
517
518        if (null === $connection) {
519            $connection = $this->getConnection();
520            if (PEAR::isError($connection)) {
521                return $connection;
522            }
523        }
524
525        $function = $this->options['result_buffering']
526            ? 'sqlite_query' : 'sqlite_unbuffered_query';
527        $php_errormsg = '';
528        if (version_compare('5.1.0', PHP_VERSION, '>')) {
529            @ini_set('track_errors', true);
530            do {
531                $result = @$function($query.';', $connection);
532            } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
533            @ini_restore('track_errors');
534        } else {
535            do {
536                $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg);
537            } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
538        }
539        $this->_lasterror = $php_errormsg;
540
541        if (!$result) {
542            $err =& $this->raiseError(null, null, null,
543                'Could not execute statement', __FUNCTION__);
544            return $err;
545        }
546
547        $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
548        return $result;
549    }
550
551    // }}}
552    // {{{ _affectedRows()
553
554    /**
555     * Returns the number of rows affected
556     *
557     * @param resource $result
558     * @param resource $connection
559     * @return mixed MDB2 Error Object or the number of rows affected
560     * @access private
561     */
562    function _affectedRows($connection, $result = null)
563    {
564        if (null === $connection) {
565            $connection = $this->getConnection();
566            if (PEAR::isError($connection)) {
567                return $connection;
568            }
569        }
570        return @sqlite_changes($connection);
571    }
572
573    // }}}
574    // {{{ _modifyQuery()
575
576    /**
577     * Changes a query string for various DBMS specific reasons
578     *
579     * @param string $query  query to modify
580     * @param boolean $is_manip  if it is a DML query
581     * @param integer $limit  limit the number of rows
582     * @param integer $offset  start reading from given offset
583     * @return string modified query
584     * @access protected
585     */
586    function _modifyQuery($query, $is_manip, $limit, $offset)
587    {
588        if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
589            if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
590                $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
591                                      'DELETE FROM \1 WHERE 1=1', $query);
592            }
593        }
594        if ($limit > 0
595            && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
596        ) {
597            $query = rtrim($query);
598            if (substr($query, -1) == ';') {
599                $query = substr($query, 0, -1);
600            }
601            if ($is_manip) {
602                $query.= " LIMIT $limit";
603            } else {
604                $query.= " LIMIT $offset,$limit";
605            }
606        }
607        return $query;
608    }
609
610    // }}}
611    // {{{ getServerVersion()
612
613    /**
614     * return version information about the server
615     *
616     * @param bool   $native  determines if the raw version string should be returned
617     * @return mixed array/string with version information or MDB2 error object
618     * @access public
619     */
620    function getServerVersion($native = false)
621    {
622        $server_info = false;
623        if ($this->connected_server_info) {
624            $server_info = $this->connected_server_info;
625        } elseif ($this->options['server_version']) {
626            $server_info = $this->options['server_version'];
627        } elseif (function_exists('sqlite_libversion')) {
628            $server_info = @sqlite_libversion();
629        }
630        if (!$server_info) {
631            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
632                'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__);
633        }
634        // cache server_info
635        $this->connected_server_info = $server_info;
636        if (!$native) {
637            $tmp = explode('.', $server_info, 3);
638            $server_info = array(
639                'major' => isset($tmp[0]) ? $tmp[0] : null,
640                'minor' => isset($tmp[1]) ? $tmp[1] : null,
641                'patch' => isset($tmp[2]) ? $tmp[2] : null,
642                'extra' => null,
643                'native' => $server_info,
644            );
645        }
646        return $server_info;
647    }
648
649    // }}}
650    // {{{ replace()
651
652    /**
653     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
654     * query, except that if there is already a row in the table with the same
655     * key field values, the old row is deleted before the new row is inserted.
656     *
657     * The REPLACE type of query does not make part of the SQL standards. Since
658     * practically only SQLite implements it natively, this type of query is
659     * emulated through this method for other DBMS using standard types of
660     * queries inside a transaction to assure the atomicity of the operation.
661     *
662     * @access public
663     *
664     * @param string $table name of the table on which the REPLACE query will
665     *  be executed.
666     * @param array $fields associative array that describes the fields and the
667     *  values that will be inserted or updated in the specified table. The
668     *  indexes of the array are the names of all the fields of the table. The
669     *  values of the array are also associative arrays that describe the
670     *  values and other properties of the table fields.
671     *
672     *  Here follows a list of field properties that need to be specified:
673     *
674     *    value:
675     *          Value to be assigned to the specified field. This value may be
676     *          of specified in database independent type format as this
677     *          function can perform the necessary datatype conversions.
678     *
679     *    Default:
680     *          this property is required unless the Null property
681     *          is set to 1.
682     *
683     *    type
684     *          Name of the type of the field. Currently, all types Metabase
685     *          are supported except for clob and blob.
686     *
687     *    Default: no type conversion
688     *
689     *    null
690     *          Boolean property that indicates that the value for this field
691     *          should be set to null.
692     *
693     *          The default value for fields missing in INSERT queries may be
694     *          specified the definition of a table. Often, the default value
695     *          is already null, but since the REPLACE may be emulated using
696     *          an UPDATE query, make sure that all fields of the table are
697     *          listed in this function argument array.
698     *
699     *    Default: 0
700     *
701     *    key
702     *          Boolean property that indicates that this field should be
703     *          handled as a primary key or at least as part of the compound
704     *          unique index of the table that will determine the row that will
705     *          updated if it exists or inserted a new row otherwise.
706     *
707     *          This function will fail if no key field is specified or if the
708     *          value of a key field is set to null because fields that are
709     *          part of unique index they may not be null.
710     *
711     *    Default: 0
712     *
713     * @return mixed MDB2_OK on success, a MDB2 error on failure
714     */
715    function replace($table, $fields)
716    {
717        $count = count($fields);
718        $query = $values = '';
719        $keys = $colnum = 0;
720        for (reset($fields); $colnum < $count; next($fields), $colnum++) {
721            $name = key($fields);
722            if ($colnum > 0) {
723                $query .= ',';
724                $values.= ',';
725            }
726            $query.= $this->quoteIdentifier($name, true);
727            if (isset($fields[$name]['null']) && $fields[$name]['null']) {
728                $value = 'NULL';
729            } else {
730                $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
731                $value = $this->quote($fields[$name]['value'], $type);
732                if (PEAR::isError($value)) {
733                    return $value;
734                }
735            }
736            $values.= $value;
737            if (isset($fields[$name]['key']) && $fields[$name]['key']) {
738                if ($value === 'NULL') {
739                    return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
740                        'key value '.$name.' may not be NULL', __FUNCTION__);
741                }
742                $keys++;
743            }
744        }
745        if ($keys == 0) {
746            return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
747                'not specified which fields are keys', __FUNCTION__);
748        }
749
750        $connection = $this->getConnection();
751        if (PEAR::isError($connection)) {
752            return $connection;
753        }
754
755        $table = $this->quoteIdentifier($table, true);
756        $query = "REPLACE INTO $table ($query) VALUES ($values)";
757        $result =& $this->_doQuery($query, true, $connection);
758        if (PEAR::isError($result)) {
759            return $result;
760        }
761        return $this->_affectedRows($connection, $result);
762    }
763
764    // }}}
765    // {{{ nextID()
766
767    /**
768     * Returns the next free id of a sequence
769     *
770     * @param string $seq_name name of the sequence
771     * @param boolean $ondemand when true the sequence is
772     *                          automatic created, if it
773     *                          not exists
774     *
775     * @return mixed MDB2 Error Object or id
776     * @access public
777     */
778    function nextID($seq_name, $ondemand = true)
779    {
780        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
781        $seqcol_name = $this->options['seqcol_name'];
782        $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
783        $this->pushErrorHandling(PEAR_ERROR_RETURN);
784        $this->expectError(MDB2_ERROR_NOSUCHTABLE);
785        $result =& $this->_doQuery($query, true);
786        $this->popExpect();
787        $this->popErrorHandling();
788        if (PEAR::isError($result)) {
789            if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
790                $this->loadModule('Manager', null, true);
791                $result = $this->manager->createSequence($seq_name);
792                if (PEAR::isError($result)) {
793                    return $this->raiseError($result, null, null,
794                        'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
795                } else {
796                    return $this->nextID($seq_name, false);
797                }
798            }
799            return $result;
800        }
801        $value = $this->lastInsertID();
802        if (is_numeric($value)) {
803            $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
804            $result =& $this->_doQuery($query, true);
805            if (PEAR::isError($result)) {
806                $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
807            }
808        }
809        return $value;
810    }
811
812    // }}}
813    // {{{ lastInsertID()
814
815    /**
816     * Returns the autoincrement ID if supported or $id or fetches the current
817     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
818     *
819     * @param string $table name of the table into which a new row was inserted
820     * @param string $field name of the field into which a new row was inserted
821     * @return mixed MDB2 Error Object or id
822     * @access public
823     */
824    function lastInsertID($table = null, $field = null)
825    {
826        $connection = $this->getConnection();
827        if (PEAR::isError($connection)) {
828            return $connection;
829        }
830        $value = @sqlite_last_insert_rowid($connection);
831        if (!$value) {
832            return $this->raiseError(null, null, null,
833                'Could not get last insert ID', __FUNCTION__);
834        }
835        return $value;
836    }
837
838    // }}}
839    // {{{ currID()
840
841    /**
842     * Returns the current id of a sequence
843     *
844     * @param string $seq_name name of the sequence
845     * @return mixed MDB2 Error Object or id
846     * @access public
847     */
848    function currID($seq_name)
849    {
850        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
851        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
852        $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
853        return $this->queryOne($query, 'integer');
854    }
855}
856
857/**
858 * MDB2 SQLite result driver
859 *
860 * @package MDB2
861 * @category Database
862 * @author  Lukas Smith <smith@pooteeweet.org>
863 */
864class MDB2_Result_sqlite extends MDB2_Result_Common
865{
866    // }}}
867    // {{{ fetchRow()
868
869    /**
870     * Fetch a row and insert the data into an existing array.
871     *
872     * @param int       $fetchmode  how the array data should be indexed
873     * @param int    $rownum    number of the row where the data can be found
874     * @return int data array on success, a MDB2 error on failure
875     * @access public
876     */
877    function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
878    {
879        if (null !== $rownum) {
880            $seek = $this->seek($rownum);
881            if (PEAR::isError($seek)) {
882                return $seek;
883            }
884        }
885        if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
886            $fetchmode = $this->db->fetchmode;
887        }
888        if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
889            $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC);
890            if (is_array($row)
891                && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
892            ) {
893                $row = array_change_key_case($row, $this->db->options['field_case']);
894            }
895        } else {
896           $row = @sqlite_fetch_array($this->result, SQLITE_NUM);
897        }
898        if (!$row) {
899            if (false === $this->result) {
900                $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
901                    'resultset has already been freed', __FUNCTION__);
902                return $err;
903            }
904            $null = null;
905            return $null;
906        }
907        $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
908        $rtrim = false;
909        if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
910            if (empty($this->types)) {
911                $mode += MDB2_PORTABILITY_RTRIM;
912            } else {
913                $rtrim = true;
914            }
915        }
916        if ($mode) {
917            $this->db->_fixResultArrayValues($row, $mode);
918        }
919        if (!empty($this->types)) {
920            $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
921        }
922        if (!empty($this->values)) {
923            $this->_assignBindColumns($row);
924        }
925        if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
926            $object_class = $this->db->options['fetch_class'];
927            if ($object_class == 'stdClass') {
928                $row = (object) $row;
929            } else {
930                $rowObj = new $object_class($row);
931                $row = $rowObj;
932            }
933        }
934        ++$this->rownum;
935        return $row;
936    }
937
938    // }}}
939    // {{{ _getColumnNames()
940
941    /**
942     * Retrieve the names of columns returned by the DBMS in a query result.
943     *
944     * @return  mixed   Array variable that holds the names of columns as keys
945     *                  or an MDB2 error on failure.
946     *                  Some DBMS may not return any columns when the result set
947     *                  does not contain any rows.
948     * @access private
949     */
950    function _getColumnNames()
951    {
952        $columns = array();
953        $numcols = $this->numCols();
954        if (PEAR::isError($numcols)) {
955            return $numcols;
956        }
957        for ($column = 0; $column < $numcols; $column++) {
958            $column_name = @sqlite_field_name($this->result, $column);
959            $columns[$column_name] = $column;
960        }
961        if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
962            $columns = array_change_key_case($columns, $this->db->options['field_case']);
963        }
964        return $columns;
965    }
966
967    // }}}
968    // {{{ numCols()
969
970    /**
971     * Count the number of columns returned by the DBMS in a query result.
972     *
973     * @access public
974     * @return mixed integer value with the number of columns, a MDB2 error
975     *                       on failure
976     */
977    function numCols()
978    {
979        $cols = @sqlite_num_fields($this->result);
980        if (null === $cols) {
981            if (false === $this->result) {
982                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
983                    'resultset has already been freed', __FUNCTION__);
984            }
985            if (null === $this->result) {
986                return count($this->types);
987            }
988            return $this->db->raiseError(null, null, null,
989                'Could not get column count', __FUNCTION__);
990        }
991        return $cols;
992    }
993}
994
995/**
996 * MDB2 SQLite buffered result driver
997 *
998 * @package MDB2
999 * @category Database
1000 * @author  Lukas Smith <smith@pooteeweet.org>
1001 */
1002class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite
1003{
1004    // {{{ seek()
1005
1006    /**
1007     * Seek to a specific row in a result set
1008     *
1009     * @param int    $rownum    number of the row where the data can be found
1010     * @return mixed MDB2_OK on success, a MDB2 error on failure
1011     * @access public
1012     */
1013    function seek($rownum = 0)
1014    {
1015        if (!@sqlite_seek($this->result, $rownum)) {
1016            if (false === $this->result) {
1017                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1018                    'resultset has already been freed', __FUNCTION__);
1019            }
1020            if (null === $this->result) {
1021                return MDB2_OK;
1022            }
1023            return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
1024                'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
1025        }
1026        $this->rownum = $rownum - 1;
1027        return MDB2_OK;
1028    }
1029
1030    // }}}
1031    // {{{ valid()
1032
1033    /**
1034     * Check if the end of the result set has been reached
1035     *
1036     * @return mixed true or false on sucess, a MDB2 error on failure
1037     * @access public
1038     */
1039    function valid()
1040    {
1041        $numrows = $this->numRows();
1042        if (PEAR::isError($numrows)) {
1043            return $numrows;
1044        }
1045        return $this->rownum < ($numrows - 1);
1046    }
1047
1048    // }}}
1049    // {{{ numRows()
1050
1051    /**
1052     * Returns the number of rows in a result object
1053     *
1054     * @return mixed MDB2 Error Object or the number of rows
1055     * @access public
1056     */
1057    function numRows()
1058    {
1059        $rows = @sqlite_num_rows($this->result);
1060        if (null === $rows) {
1061            if (false === $this->result) {
1062                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1063                    'resultset has already been freed', __FUNCTION__);
1064            }
1065            if (null === $this->result) {
1066                return 0;
1067            }
1068            return $this->db->raiseError(null, null, null,
1069                'Could not get row count', __FUNCTION__);
1070        }
1071        return $rows;
1072    }
1073}
1074
1075/**
1076 * MDB2 SQLite statement driver
1077 *
1078 * @package MDB2
1079 * @category Database
1080 * @author  Lukas Smith <smith@pooteeweet.org>
1081 */
1082class MDB2_Statement_sqlite extends MDB2_Statement_Common
1083{
1084
1085}
1086?>
Note: See TracBrowser for help on using the repository browser.