Subversion-Projekte lars-tiefland.niewerth

Revision

Revision 7 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
// vim: set et ts=4 sw=4 fdm=marker:
3
// +----------------------------------------------------------------------+
4
// | PHP versions 4 and 5                                                 |
5
// +----------------------------------------------------------------------+
6
// | Copyright (c) 1998-2006 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: mysql.php,v 1.170 2006/10/31 18:46:43 lsmith Exp $
47
//
48
 
49
/**
50
 * MDB2 MySQL driver
51
 *
52
 * @package MDB2
53
 * @category Database
54
 * @author  Lukas Smith <smith@pooteeweet.org>
55
 */
56
class MDB2_Driver_mysql extends MDB2_Driver_Common
57
{
58
    // {{{ properties
59
    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\');
60
 
61
    var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`');
62
 
63
    var $sql_comments = array(
64
        array('start' => '-- ', 'end' => "\n", 'escape' => false),
65
        array('start' => '#', 'end' => "\n", 'escape' => false),
66
        array('start' => '/*', 'end' => '*/', 'escape' => false),
67
    );
68
 
69
    var $start_transaction = false;
70
 
71
    var $varchar_max_length = 255;
72
    // }}}
73
    // {{{ constructor
74
 
75
    /**
76
     * Constructor
77
     */
78
    function __construct()
79
    {
80
        parent::__construct();
81
 
82
        $this->phptype = 'mysql';
83
        $this->dbsyntax = 'mysql';
84
 
85
        $this->supported['sequences'] = 'emulated';
86
        $this->supported['indexes'] = true;
87
        $this->supported['affected_rows'] = true;
88
        $this->supported['transactions'] = false;
89
        $this->supported['savepoints'] = false;
90
        $this->supported['summary_functions'] = true;
91
        $this->supported['order_by_text'] = true;
92
        $this->supported['current_id'] = 'emulated';
93
        $this->supported['limit_queries'] = true;
94
        $this->supported['LOBs'] = true;
95
        $this->supported['replace'] = true;
96
        $this->supported['sub_selects'] = 'emulated';
97
        $this->supported['auto_increment'] = true;
98
        $this->supported['primary_key'] = true;
99
        $this->supported['result_introspection'] = true;
100
        $this->supported['prepared_statements'] = 'emulated';
101
        $this->supported['identifier_quoting'] = true;
102
        $this->supported['pattern_escaping'] = true;
103
        $this->supported['new_link'] = true;
104
 
105
        $this->options['default_table_type'] = '';
106
    }
107
 
108
    // }}}
109
    // {{{ errorInfo()
110
 
111
    /**
112
     * This method is used to collect information about an error
113
     *
114
     * @param integer $error
115
     * @return array
116
     * @access public
117
     */
118
    function errorInfo($error = null)
119
    {
120
        if ($this->connection) {
121
            $native_code = @mysql_errno($this->connection);
122
            $native_msg  = @mysql_error($this->connection);
123
        } else {
124
            $native_code = @mysql_errno();
125
            $native_msg  = @mysql_error();
126
        }
127
        if (is_null($error)) {
128
            static $ecode_map;
129
            if (empty($ecode_map)) {
130
                $ecode_map = array(
131
                    1004 => MDB2_ERROR_CANNOT_CREATE,
132
                    1005 => MDB2_ERROR_CANNOT_CREATE,
133
                    1006 => MDB2_ERROR_CANNOT_CREATE,
134
                    1007 => MDB2_ERROR_ALREADY_EXISTS,
135
                    1008 => MDB2_ERROR_CANNOT_DROP,
136
                    1022 => MDB2_ERROR_ALREADY_EXISTS,
137
                    1044 => MDB2_ERROR_ACCESS_VIOLATION,
138
                    1046 => MDB2_ERROR_NODBSELECTED,
139
                    1048 => MDB2_ERROR_CONSTRAINT,
140
                    1049 => MDB2_ERROR_NOSUCHDB,
141
                    1050 => MDB2_ERROR_ALREADY_EXISTS,
142
                    1051 => MDB2_ERROR_NOSUCHTABLE,
143
                    1054 => MDB2_ERROR_NOSUCHFIELD,
144
                    1061 => MDB2_ERROR_ALREADY_EXISTS,
145
                    1062 => MDB2_ERROR_ALREADY_EXISTS,
146
                    1064 => MDB2_ERROR_SYNTAX,
147
                    1091 => MDB2_ERROR_NOT_FOUND,
148
                    1100 => MDB2_ERROR_NOT_LOCKED,
149
                    1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
150
                    1142 => MDB2_ERROR_ACCESS_VIOLATION,
151
                    1146 => MDB2_ERROR_NOSUCHTABLE,
152
                    1216 => MDB2_ERROR_CONSTRAINT,
153
                    1217 => MDB2_ERROR_CONSTRAINT,
154
                );
155
            }
156
            if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
157
                $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
158
                $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
159
                $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
160
            } else {
161
                // Doing this in case mode changes during runtime.
162
                $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
163
                $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
164
                $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
165
            }
166
            if (isset($ecode_map[$native_code])) {
167
                $error = $ecode_map[$native_code];
168
            }
169
        }
170
        return array($error, $native_code, $native_msg);
171
    }
172
 
173
    // }}}
174
    // {{{ escape()
175
 
176
    /**
177
     * Quotes a string so it can be safely used in a query. It will quote
178
     * the text so it can safely be used within a query.
179
     *
180
     * @param   string  the input string to quote
181
     * @param   bool    escape wildcards
182
     *
183
     * @return  string  quoted string
184
     *
185
     * @access  public
186
     */
187
    function escape($text, $escape_wildcards = false)
188
    {
189
        if ($escape_wildcards) {
190
            $text = $this->escapePattern($text);
191
        }
192
        $connection = $this->getConnection();
193
        if (PEAR::isError($connection)) {
194
            return $connection;
195
        }
196
        $text = @mysql_real_escape_string($text, $connection);
197
        return $text;
198
    }
199
 
200
    // }}}
201
    // {{{
202
 
203
    /**
204
     * Start a transaction or set a savepoint.
205
     *
206
     * @param   string  name of a savepoint to set
207
     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
208
     *
209
     * @access  public
210
     */
211
    function beginTransaction($savepoint = null)
212
    {
213
        $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
214
        if (!is_null($savepoint)) {
215
            if (!$this->supports('savepoints')) {
216
                return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
217
                    'savepoints are not supported', __FUNCTION__);
218
            }
219
            if (!$this->in_transaction) {
220
                return $this->raiseError(MDB2_ERROR_INVALID, null, null,
221
                    'savepoint cannot be released when changes are auto committed', __FUNCTION__);
222
            }
223
            $query = 'SAVEPOINT '.$savepoint;
224
            return $this->_doQuery($query, true);
225
        } elseif ($this->in_transaction) {
226
            return MDB2_OK;  //nothing to do
227
        }
228
        if (!$this->destructor_registered && $this->opened_persistent) {
229
            $this->destructor_registered = true;
230
            register_shutdown_function('MDB2_closeOpenTransactions');
231
        }
232
        $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 1';
233
        $result =& $this->_doQuery($query, true);
234
        if (PEAR::isError($result)) {
235
            return $result;
236
        }
237
        $this->in_transaction = true;
238
        return MDB2_OK;
239
    }
240
 
241
    // }}}
242
    // {{{ commit()
243
 
244
    /**
245
     * Commit the database changes done during a transaction that is in
246
     * progress or release a savepoint. This function may only be called when
247
     * auto-committing is disabled, otherwise it will fail. Therefore, a new
248
     * transaction is implicitly started after committing the pending changes.
249
     *
250
     * @param   string  name of a savepoint to release
251
     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
252
     *
253
     * @access  public
254
     */
255
    function commit($savepoint = null)
256
    {
257
        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
258
        if (!$this->in_transaction) {
259
            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
260
                'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
261
        }
262
        if (!is_null($savepoint)) {
263
            if (!$this->supports('savepoints')) {
264
                return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
265
                    'savepoints are not supported', __FUNCTION__);
266
            }
267
            $server_info = $this->getServerVersion();
268
            if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
269
                return MDB2_OK;
270
            }
271
            $query = 'RELEASE SAVEPOINT '.$savepoint;
272
            return $this->_doQuery($query, true);
273
        }
274
 
275
        if (!$this->supports('transactions')) {
276
            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
277
                'transactions are not supported', __FUNCTION__);
278
        }
279
 
280
        $result =& $this->_doQuery('COMMIT', true);
281
        if (PEAR::isError($result)) {
282
            return $result;
283
        }
284
        if (!$this->start_transaction) {
285
            $query = 'SET AUTOCOMMIT = 0';
286
            $result =& $this->_doQuery($query, true);
287
            if (PEAR::isError($result)) {
288
                return $result;
289
            }
290
        }
291
        $this->in_transaction = false;
292
        return MDB2_OK;
293
    }
294
 
295
    // }}}
296
    // {{{ rollback()
297
 
298
    /**
299
     * Cancel any database changes done during a transaction or since a specific
300
     * savepoint that is in progress. This function may only be called when
301
     * auto-committing is disabled, otherwise it will fail. Therefore, a new
302
     * transaction is implicitly started after canceling the pending changes.
303
     *
304
     * @param   string  name of a savepoint to rollback to
305
     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
306
     *
307
     * @access  public
308
     */
309
    function rollback($savepoint = null)
310
    {
311
        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
312
        if (!$this->in_transaction) {
313
            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
314
                'rollback cannot be done changes are auto committed', __FUNCTION__);
315
        }
316
        if (!is_null($savepoint)) {
317
            if (!$this->supports('savepoints')) {
318
                return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
319
                    'savepoints are not supported', __FUNCTION__);
320
            }
321
            $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
322
            return $this->_doQuery($query, true);
323
        }
324
 
325
        $query = 'ROLLBACK';
326
        $result =& $this->_doQuery($query, true);
327
        if (PEAR::isError($result)) {
328
            return $result;
329
        }
330
        if (!$this->start_transaction) {
331
            $query = 'SET AUTOCOMMIT = 0';
332
            $result =& $this->_doQuery($query, true);
333
            if (PEAR::isError($result)) {
334
                return $result;
335
            }
336
        }
337
        $this->in_transaction = false;
338
        return MDB2_OK;
339
    }
340
 
341
    // }}}
342
    // {{{ function setTransactionIsolation()
343
 
344
    /**
345
     * Set the transacton isolation level.
346
     *
347
     * @param   string  standard isolation level
348
     *                  READ UNCOMMITTED (allows dirty reads)
349
     *                  READ COMMITTED (prevents dirty reads)
350
     *                  REPEATABLE READ (prevents nonrepeatable reads)
351
     *                  SERIALIZABLE (prevents phantom reads)
352
     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
353
     *
354
     * @access  public
355
     * @since   2.1.1
356
     */
357
    function setTransactionIsolation($isolation)
358
    {
359
        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
360
        if (!$this->supports('transactions')) {
361
            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
362
                'transactions are not supported', __FUNCTION__);
363
        }
364
        switch ($isolation) {
365
        case 'READ UNCOMMITTED':
366
        case 'READ COMMITTED':
367
        case 'REPEATABLE READ':
368
        case 'SERIALIZABLE':
369
            break;
370
        default:
371
            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
372
                'isolation level is not supported: '.$isolation, __FUNCTION__);
373
        }
374
 
375
        $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
376
        return $this->_doQuery($query, true);
377
    }
378
 
379
    // }}}
380
    // {{{ connect()
381
 
382
    /**
383
     * Connect to the database
384
     *
385
     * @return true on success, MDB2 Error Object on failure
386
     */
387
    function connect()
388
    {
389
        if (is_resource($this->connection)) {
390
            if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
391
                && $this->opened_persistent == $this->options['persistent']
392
            ) {
393
                return MDB2_OK;
394
            }
395
            $this->disconnect(false);
396
        }
397
 
398
        if (!PEAR::loadExtension($this->phptype)) {
399
            return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
400
                'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
401
        }
402
 
403
        $params = array();
404
        if ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix') {
405
            $params[0] = ':' . $this->dsn['socket'];
406
        } else {
407
            $params[0] = $this->dsn['hostspec'] ? $this->dsn['hostspec']
408
                         : 'localhost';
409
            if ($this->dsn['port']) {
410
                $params[0].= ':' . $this->dsn['port'];
411
            }
412
        }
413
        $params[] = $this->dsn['username'] ? $this->dsn['username'] : null;
414
        $params[] = $this->dsn['password'] ? $this->dsn['password'] : null;
415
        if (!$this->options['persistent']) {
416
            if (isset($this->dsn['new_link'])
417
                && ($this->dsn['new_link'] == 'true' || $this->dsn['new_link'] === true)
418
            ) {
419
                $params[] = true;
420
            } else {
421
                $params[] = false;
422
            }
423
        }
424
        if (version_compare(phpversion(), '4.3.0', '>=')) {
425
            $params[] = isset($this->dsn['client_flags'])
426
                ? $this->dsn['client_flags'] : null;
427
        }
428
        $connect_function = $this->options['persistent'] ? 'mysql_pconnect' : 'mysql_connect';
429
 
430
        $connection = @call_user_func_array($connect_function, $params);
431
        if (!$connection) {
432
            if (($err = @mysql_error()) != '') {
433
                return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
434
                    $err, __FUNCTION__);
435
            } else {
436
                return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
437
                    'unable to establish a connection', __FUNCTION__);
438
            }
439
        }
440
 
441
        if (!empty($this->dsn['charset'])) {
442
            $result = $this->setCharset($this->dsn['charset'], $connection);
443
            if (PEAR::isError($result)) {
444
                return $result;
445
            }
446
        }
447
 
448
        $this->connection = $connection;
449
        $this->connected_dsn = $this->dsn;
450
        $this->connected_database_name = '';
451
        $this->opened_persistent = $this->options['persistent'];
452
        $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
453
 
454
        if ($this->database_name) {
455
            if ($this->database_name != $this->connected_database_name) {
456
                if (!@mysql_select_db($this->database_name, $connection)) {
457
                    $err = $this->raiseError(null, null, null,
458
                        'Could not select the database: '.$this->database_name, __FUNCTION__);
459
                    return $err;
460
                }
461
                $this->connected_database_name = $this->database_name;
462
            }
463
        }
464
 
465
        $this->supported['transactions'] = $this->options['use_transactions'];
466
        if ($this->options['default_table_type']) {
467
            switch (strtoupper($this->options['default_table_type'])) {
468
            case 'BLACKHOLE':
469
            case 'MEMORY':
470
            case 'ARCHIVE':
471
            case 'CSV':
472
            case 'HEAP':
473
            case 'ISAM':
474
            case 'MERGE':
475
            case 'MRG_ISAM':
476
            case 'ISAM':
477
            case 'MRG_MYISAM':
478
            case 'MYISAM':
479
                $this->supported['transactions'] = false;
480
                $this->warnings[] = $this->options['default_table_type'] .
481
                    ' is not a supported default table type';
482
                break;
483
            }
484
        }
485
 
486
        $this->supported['sub_selects'] = 'emulated';
487
        $this->supported['prepared_statements'] = 'emulated';
488
        $this->start_transaction = false;
489
        $this->varchar_max_length = 255;
490
 
491
        $server_info = $this->getServerVersion();
492
        if (is_array($server_info)) {
493
            if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.1.0', '<')) {
494
                $this->supported['sub_selects'] = true;
495
                $this->supported['prepared_statements'] = true;
496
            }
497
 
498
            if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.0.14', '<')
499
                || !version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.1.1', '<')
500
            ) {
501
                $this->supported['savepoints'] = true;
502
            }
503
 
504
            if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.0.11', '<')) {
505
                $this->start_transaction = true;
506
            }
507
 
508
            if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
509
                $this->varchar_max_length = 65532;
510
            }
511
        }
512
 
513
        return MDB2_OK;
514
    }
515
    // }}}
516
    // {{{ setCharset()
517
 
518
    /**
519
     * Set the charset on the current connection
520
     *
521
     * @param string    charset
522
     * @param resource  connection handle
523
     *
524
     * @return true on success, MDB2 Error Object on failure
525
     */
526
    function setCharset($charset, $connection = null)
527
    {
528
        if (is_null($connection)) {
529
            $connection = $this->getConnection();
530
            if (PEAR::isError($connection)) {
531
                return $connection;
532
            }
533
        }
534
 
535
        $query = "SET character_set_client = '".mysql_real_escape_string($charset, $connection)."'";
536
        $result = @mysql_query($query, $connection);
537
        if (!$result) {
538
            return $this->raiseError(null, null, null,
539
                'Unable to set client charset: '.$charset, __FUNCTION__);
540
        }
541
 
542
        return MDB2_OK;
543
    }
544
 
545
    // }}}
546
    // {{{ disconnect()
547
 
548
    /**
549
     * Log out and disconnect from the database.
550
     *
551
     * @param  boolean $force if the disconnect should be forced even if the
552
     *                        connection is opened persistently
553
     * @return mixed true on success, false if not connected and error
554
     *                object on error
555
     * @access public
556
     */
557
    function disconnect($force = true)
558
    {
559
        if (is_resource($this->connection)) {
560
            if ($this->in_transaction) {
561
                $dsn = $this->dsn;
562
                $database_name = $this->database_name;
563
                $persistent = $this->options['persistent'];
564
                $this->dsn = $this->connected_dsn;
565
                $this->database_name = $this->connected_database_name;
566
                $this->options['persistent'] = $this->opened_persistent;
567
                $this->rollback();
568
                $this->dsn = $dsn;
569
                $this->database_name = $database_name;
570
                $this->options['persistent'] = $persistent;
571
            }
572
 
573
            if (!$this->opened_persistent || $force) {
574
                @mysql_close($this->connection);
575
            }
576
        }
577
        return parent::disconnect($force);
578
    }
579
 
580
    // }}}
581
    // {{{ _doQuery()
582
 
583
    /**
584
     * Execute a query
585
     * @param string $query  query
586
     * @param boolean $is_manip  if the query is a manipulation query
587
     * @param resource $connection
588
     * @param string $database_name
589
     * @return result or error object
590
     * @access protected
591
     */
592
    function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
593
    {
594
        $this->last_query = $query;
595
        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
596
        if ($result) {
597
            if (PEAR::isError($result)) {
598
                return $result;
599
            }
600
            $query = $result;
601
        }
602
        if ($this->options['disable_query']) {
603
            $result = $is_manip ? 0 : null;
604
            return $result;
605
        }
606
 
607
        if (is_null($connection)) {
608
            $connection = $this->getConnection();
609
            if (PEAR::isError($connection)) {
610
                return $connection;
611
            }
612
        }
613
        if (is_null($database_name)) {
614
            $database_name = $this->database_name;
615
        }
616
 
617
        if ($database_name) {
618
            if ($database_name != $this->connected_database_name) {
619
                if (!@mysql_select_db($database_name, $connection)) {
620
                    $err = $this->raiseError(null, null, null,
621
                        'Could not select the database: '.$database_name, __FUNCTION__);
622
                    return $err;
623
                }
624
                $this->connected_database_name = $database_name;
625
            }
626
        }
627
 
628
        $function = $this->options['result_buffering']
629
            ? 'mysql_query' : 'mysql_unbuffered_query';
630
        $result = @$function($query, $connection);
631
        if (!$result) {
632
            $err =& $this->raiseError(null, null, null,
633
                'Could not execute statement', __FUNCTION__);
634
            return $err;
635
        }
636
 
637
        $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
638
        return $result;
639
    }
640
 
641
    // }}}
642
    // {{{ _affectedRows()
643
 
644
    /**
645
     * Returns the number of rows affected
646
     *
647
     * @param resource $result
648
     * @param resource $connection
649
     * @return mixed MDB2 Error Object or the number of rows affected
650
     * @access private
651
     */
652
    function _affectedRows($connection, $result = null)
653
    {
654
        if (is_null($connection)) {
655
            $connection = $this->getConnection();
656
            if (PEAR::isError($connection)) {
657
                return $connection;
658
            }
659
        }
660
        return @mysql_affected_rows($connection);
661
    }
662
 
663
    // }}}
664
    // {{{ _modifyQuery()
665
 
666
    /**
667
     * Changes a query string for various DBMS specific reasons
668
     *
669
     * @param string $query  query to modify
670
     * @param boolean $is_manip  if it is a DML query
671
     * @param integer $limit  limit the number of rows
672
     * @param integer $offset  start reading from given offset
673
     * @return string modified query
674
     * @access protected
675
     */
676
    function _modifyQuery($query, $is_manip, $limit, $offset)
677
    {
678
        if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
679
            // "DELETE FROM table" gives 0 affected rows in MySQL.
680
            // This little hack lets you know how many rows were deleted.
681
            if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
682
                $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
683
                                      'DELETE FROM \1 WHERE 1=1', $query);
684
            }
685
        }
686
        if ($limit > 0
687
            && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i', $query)
688
        ) {
689
            $query = rtrim($query);
690
            if (substr($query, -1) == ';') {
691
                $query = substr($query, 0, -1);
692
            }
693
            if ($is_manip) {
694
                return $query . " LIMIT $limit";
695
            } else {
696
                return $query . " LIMIT $offset, $limit";
697
            }
698
        }
699
        return $query;
700
    }
701
 
702
    // }}}
703
    // {{{ getServerVersion()
704
 
705
    /**
706
     * return version information about the server
707
     *
708
     * @param string     $native  determines if the raw version string should be returned
709
     * @return mixed array/string with version information or MDB2 error object
710
     * @access public
711
     */
712
    function getServerVersion($native = false)
713
    {
714
        $connection = $this->getConnection();
715
        if (PEAR::isError($connection)) {
716
            return $connection;
717
        }
718
        if ($this->connected_server_info) {
719
            $server_info = $this->connected_server_info;
720
        } else {
721
            $server_info = @mysql_get_server_info($connection);
722
        }
723
        if (!$server_info) {
724
            return $this->raiseError(null, null, null,
725
                'Could not get server information', __FUNCTION__);
726
        }
727
        // cache server_info
728
        $this->connected_server_info = $server_info;
729
        if (!$native) {
730
            $tmp = explode('.', $server_info, 3);
731
            if (isset($tmp[2]) && strpos($tmp[2], '-')) {
732
                $tmp2 = explode('-', @$tmp[2], 2);
733
            } else {
734
                $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
735
                $tmp2[1] = null;
736
            }
737
            $server_info = array(
738
                'major' => isset($tmp[0]) ? $tmp[0] : null,
739
                'minor' => isset($tmp[1]) ? $tmp[1] : null,
740
                'patch' => $tmp2[0],
741
                'extra' => $tmp2[1],
742
                'native' => $server_info,
743
            );
744
        }
745
        return $server_info;
746
    }
747
 
748
    // }}}
749
    // {{{ prepare()
750
 
751
    /**
752
     * Prepares a query for multiple execution with execute().
753
     * With some database backends, this is emulated.
754
     * prepare() requires a generic query as string like
755
     * 'INSERT INTO numbers VALUES(?,?)' or
756
     * 'INSERT INTO numbers VALUES(:foo,:bar)'.
757
     * The ? and :[a-zA-Z] and  are placeholders which can be set using
758
     * bindParam() and the query can be send off using the execute() method.
759
     *
760
     * @param string $query the query to prepare
761
     * @param mixed   $types  array that contains the types of the placeholders
762
     * @param mixed   $result_types  array that contains the types of the columns in
763
     *                        the result set or MDB2_PREPARE_RESULT, if set to
764
     *                        MDB2_PREPARE_MANIP the query is handled as a manipulation query
765
     * @param mixed   $lobs   key (field) value (parameter) pair for all lob placeholders
766
     * @return mixed resource handle for the prepared query on success, a MDB2
767
     *        error on failure
768
     * @access public
769
     * @see bindParam, execute
770
     */
771
    function &prepare($query, $types = null, $result_types = null, $lobs = array())
772
    {
773
        if ($this->options['emulate_prepared']
774
            || $this->supported['prepared_statements'] !== true
775
        ) {
776
            $obj =& parent::prepare($query, $types, $result_types, $lobs);
777
            return $obj;
778
        }
779
        $is_manip = ($result_types === MDB2_PREPARE_MANIP);
780
        $offset = $this->offset;
781
        $limit = $this->limit;
782
        $this->offset = $this->limit = 0;
783
        $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
784
        $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
785
        if ($result) {
786
            if (PEAR::isError($result)) {
787
                return $result;
788
            }
789
            $query = $result;
790
        }
791
        $placeholder_type_guess = $placeholder_type = null;
792
        $question = '?';
793
        $colon = ':';
794
        $positions = array();
795
        $position = 0;
796
        while ($position < strlen($query)) {
797
            $q_position = strpos($query, $question, $position);
798
            $c_position = strpos($query, $colon, $position);
799
            if ($q_position && $c_position) {
800
                $p_position = min($q_position, $c_position);
801
            } elseif ($q_position) {
802
                $p_position = $q_position;
803
            } elseif ($c_position) {
804
                $p_position = $c_position;
805
            } else {
806
                break;
807
            }
808
            if (is_null($placeholder_type)) {
809
                $placeholder_type_guess = $query[$p_position];
810
            }
811
 
812
            $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
813
            if (PEAR::isError($new_pos)) {
814
                return $new_pos;
815
            }
816
            if ($new_pos != $position) {
817
                $position = $new_pos;
818
                continue; //evaluate again starting from the new position
819
            }
820
 
821
            if ($query[$position] == $placeholder_type_guess) {
822
                if (is_null($placeholder_type)) {
823
                    $placeholder_type = $query[$p_position];
824
                    $question = $colon = $placeholder_type;
825
                }
826
                if ($placeholder_type == ':') {
827
                    $parameter = preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si', '\\1', $query);
828
                    if ($parameter === '') {
829
                        $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
830
                            'named parameter with an empty name', __FUNCTION__);
831
                        return $err;
832
                    }
833
                    $positions[$p_position] = $parameter;
834
                    $query = substr_replace($query, '?', $position, strlen($parameter)+1);
835
                } else {
836
                    $positions[$p_position] = count($positions);
837
                }
838
                $position = $p_position + 1;
839
            } else {
840
                $position = $p_position;
841
            }
842
        }
843
        $connection = $this->getConnection();
844
        if (PEAR::isError($connection)) {
845
            return $connection;
846
        }
847
        $statement_name = sprintf($this->options['statement_format'], $this->phptype, md5(time() + rand()));
848
        $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
849
        $statement =& $this->_doQuery($query, true, $connection);
850
        if (PEAR::isError($statement)) {
851
            return $statement;
852
        }
853
 
854
        $class_name = 'MDB2_Statement_'.$this->phptype;
855
        $obj =& new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
856
        $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
857
        return $obj;
858
    }
859
 
860
    // }}}
861
    // {{{ replace()
862
 
863
    /**
864
     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
865
     * query, except that if there is already a row in the table with the same
866
     * key field values, the REPLACE query just updates its values instead of
867
     * inserting a new row.
868
     *
869
     * The REPLACE type of query does not make part of the SQL standards. Since
870
     * practically only MySQL implements it natively, this type of query is
871
     * emulated through this method for other DBMS using standard types of
872
     * queries inside a transaction to assure the atomicity of the operation.
873
     *
874
     * @access public
875
     *
876
     * @param string $table name of the table on which the REPLACE query will
877
     *  be executed.
878
     * @param array $fields associative array that describes the fields and the
879
     *  values that will be inserted or updated in the specified table. The
880
     *  indexes of the array are the names of all the fields of the table. The
881
     *  values of the array are also associative arrays that describe the
882
     *  values and other properties of the table fields.
883
     *
884
     *  Here follows a list of field properties that need to be specified:
885
     *
886
     *    value:
887
     *          Value to be assigned to the specified field. This value may be
888
     *          of specified in database independent type format as this
889
     *          function can perform the necessary datatype conversions.
890
     *
891
     *    Default:
892
     *          this property is required unless the Null property
893
     *          is set to 1.
894
     *
895
     *    type
896
     *          Name of the type of the field. Currently, all types Metabase
897
     *          are supported except for clob and blob.
898
     *
899
     *    Default: no type conversion
900
     *
901
     *    null
902
     *          Boolean property that indicates that the value for this field
903
     *          should be set to null.
904
     *
905
     *          The default value for fields missing in INSERT queries may be
906
     *          specified the definition of a table. Often, the default value
907
     *          is already null, but since the REPLACE may be emulated using
908
     *          an UPDATE query, make sure that all fields of the table are
909
     *          listed in this function argument array.
910
     *
911
     *    Default: 0
912
     *
913
     *    key
914
     *          Boolean property that indicates that this field should be
915
     *          handled as a primary key or at least as part of the compound
916
     *          unique index of the table that will determine the row that will
917
     *          updated if it exists or inserted a new row otherwise.
918
     *
919
     *          This function will fail if no key field is specified or if the
920
     *          value of a key field is set to null because fields that are
921
     *          part of unique index they may not be null.
922
     *
923
     *    Default: 0
924
     *
925
     * @return mixed MDB2_OK on success, a MDB2 error on failure
926
     */
927
    function replace($table, $fields)
928
    {
929
        $count = count($fields);
930
        $query = $values = '';
931
        $keys = $colnum = 0;
932
        for (reset($fields); $colnum < $count; next($fields), $colnum++) {
933
            $name = key($fields);
934
            if ($colnum > 0) {
935
                $query .= ',';
936
                $values.= ',';
937
            }
938
            $query.= $name;
939
            if (isset($fields[$name]['null']) && $fields[$name]['null']) {
940
                $value = 'NULL';
941
            } else {
942
                $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
943
                $value = $this->quote($fields[$name]['value'], $type);
944
            }
945
            $values.= $value;
946
            if (isset($fields[$name]['key']) && $fields[$name]['key']) {
947
                if ($value === 'NULL') {
948
                    return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
949
                        'key value '.$name.' may not be NULL', __FUNCTION__);
950
                }
951
                $keys++;
952
            }
953
        }
954
        if ($keys == 0) {
955
            return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
956
                'not specified which fields are keys', __FUNCTION__);
957
        }
958
 
959
        $connection = $this->getConnection();
960
        if (PEAR::isError($connection)) {
961
            return $connection;
962
        }
963
 
964
        $query = "REPLACE INTO $table ($query) VALUES ($values)";
965
        $result =& $this->_doQuery($query, true, $connection);
966
        if (PEAR::isError($result)) {
967
            return $result;
968
        }
969
        return $this->_affectedRows($connection, $result);
970
    }
971
 
972
    // }}}
973
    // {{{ nextID()
974
 
975
    /**
976
     * Returns the next free id of a sequence
977
     *
978
     * @param string $seq_name name of the sequence
979
     * @param boolean $ondemand when true the sequence is
980
     *                          automatic created, if it
981
     *                          not exists
982
     *
983
     * @return mixed MDB2 Error Object or id
984
     * @access public
985
     */
986
    function nextID($seq_name, $ondemand = true)
987
    {
988
        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
989
        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
990
        $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
991
        $this->expectError(MDB2_ERROR_NOSUCHTABLE);
992
        $result =& $this->_doQuery($query, true);
993
        $this->popExpect();
994
        if (PEAR::isError($result)) {
995
            if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
996
                $this->loadModule('Manager', null, true);
997
                $result = $this->manager->createSequence($seq_name);
998
                if (PEAR::isError($result)) {
999
                    return $this->raiseError($result, null, null,
1000
                        'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
1001
                } else {
1002
                    return $this->nextID($seq_name, false);
1003
                }
1004
            }
1005
            return $result;
1006
        }
1007
        $value = $this->lastInsertID();
1008
        if (is_numeric($value)) {
1009
            $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
1010
            $result =& $this->_doQuery($query, true);
1011
            if (PEAR::isError($result)) {
1012
                $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
1013
            }
1014
        }
1015
        return $value;
1016
    }
1017
 
1018
    // }}}
1019
    // {{{ lastInsertID()
1020
 
1021
    /**
1022
     * Returns the autoincrement ID if supported or $id or fetches the current
1023
     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
1024
     *
1025
     * @param string $table name of the table into which a new row was inserted
1026
     * @param string $field name of the field into which a new row was inserted
1027
     * @return mixed MDB2 Error Object or id
1028
     * @access public
1029
     */
1030
    function lastInsertID($table = null, $field = null)
1031
    {
1032
        // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
1033
        return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
1034
    }
1035
 
1036
    // }}}
1037
    // {{{ currID()
1038
 
1039
    /**
1040
     * Returns the current id of a sequence
1041
     *
1042
     * @param string $seq_name name of the sequence
1043
     * @return mixed MDB2 Error Object or id
1044
     * @access public
1045
     */
1046
    function currID($seq_name)
1047
    {
1048
        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
1049
        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
1050
        $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
1051
        return $this->queryOne($query, 'integer');
1052
    }
1053
}
1054
 
1055
/**
1056
 * MDB2 MySQL result driver
1057
 *
1058
 * @package MDB2
1059
 * @category Database
1060
 * @author  Lukas Smith <smith@pooteeweet.org>
1061
 */
1062
class MDB2_Result_mysql extends MDB2_Result_Common
1063
{
1064
    // }}}
1065
    // {{{ fetchRow()
1066
 
1067
    /**
1068
     * Fetch a row and insert the data into an existing array.
1069
     *
1070
     * @param int       $fetchmode  how the array data should be indexed
1071
     * @param int    $rownum    number of the row where the data can be found
1072
     * @return int data array on success, a MDB2 error on failure
1073
     * @access public
1074
     */
1075
    function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
1076
    {
1077
        if (!is_null($rownum)) {
1078
            $seek = $this->seek($rownum);
1079
            if (PEAR::isError($seek)) {
1080
                return $seek;
1081
            }
1082
        }
1083
        if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
1084
            $fetchmode = $this->db->fetchmode;
1085
        }
1086
        if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
1087
            $row = @mysql_fetch_assoc($this->result);
1088
            if (is_array($row)
1089
                && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
1090
            ) {
1091
                $row = array_change_key_case($row, $this->db->options['field_case']);
1092
            }
1093
        } else {
1094
           $row = @mysql_fetch_row($this->result);
1095
        }
1096
 
1097
        if (!$row) {
1098
            if ($this->result === false) {
1099
                $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1100
                    'resultset has already been freed', __FUNCTION__);
1101
                return $err;
1102
            }
1103
            $null = null;
1104
            return $null;
1105
        }
1106
        $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
1107
        if ($mode) {
1108
            $this->db->_fixResultArrayValues($row, $mode);
1109
        }
1110
        if (!empty($this->types)) {
1111
            $row = $this->db->datatype->convertResultRow($this->types, $row, false);
1112
        }
1113
        if (!empty($this->values)) {
1114
            $this->_assignBindColumns($row);
1115
        }
1116
        if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
1117
            $object_class = $this->db->options['fetch_class'];
1118
            if ($object_class == 'stdClass') {
1119
                $row = (object) $row;
1120
            } else {
1121
                $row = &new $object_class($row);
1122
            }
1123
        }
1124
        ++$this->rownum;
1125
        return $row;
1126
    }
1127
 
1128
    // }}}
1129
    // {{{ _getColumnNames()
1130
 
1131
    /**
1132
     * Retrieve the names of columns returned by the DBMS in a query result.
1133
     *
1134
     * @return  mixed   Array variable that holds the names of columns as keys
1135
     *                  or an MDB2 error on failure.
1136
     *                  Some DBMS may not return any columns when the result set
1137
     *                  does not contain any rows.
1138
     * @access private
1139
     */
1140
    function _getColumnNames()
1141
    {
1142
        $columns = array();
1143
        $numcols = $this->numCols();
1144
        if (PEAR::isError($numcols)) {
1145
            return $numcols;
1146
        }
1147
        for ($column = 0; $column < $numcols; $column++) {
1148
            $column_name = @mysql_field_name($this->result, $column);
1149
            $columns[$column_name] = $column;
1150
        }
1151
        if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
1152
            $columns = array_change_key_case($columns, $this->db->options['field_case']);
1153
        }
1154
        return $columns;
1155
    }
1156
 
1157
    // }}}
1158
    // {{{ numCols()
1159
 
1160
    /**
1161
     * Count the number of columns returned by the DBMS in a query result.
1162
     *
1163
     * @return mixed integer value with the number of columns, a MDB2 error
1164
     *                       on failure
1165
     * @access public
1166
     */
1167
    function numCols()
1168
    {
1169
        $cols = @mysql_num_fields($this->result);
1170
        if (is_null($cols)) {
1171
            if ($this->result === false) {
1172
                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1173
                    'resultset has already been freed', __FUNCTION__);
1174
            } elseif (is_null($this->result)) {
1175
                return count($this->types);
1176
            }
1177
            return $this->db->raiseError(null, null, null,
1178
                'Could not get column count', __FUNCTION__);
1179
        }
1180
        return $cols;
1181
    }
1182
 
1183
    // }}}
1184
    // {{{ free()
1185
 
1186
    /**
1187
     * Free the internal resources associated with result.
1188
     *
1189
     * @return boolean true on success, false if result is invalid
1190
     * @access public
1191
     */
1192
    function free()
1193
    {
1194
        if (is_resource($this->result) && $this->db->connection) {
1195
            $free = @mysql_free_result($this->result);
1196
            if ($free === false) {
1197
                return $this->db->raiseError(null, null, null,
1198
                    'Could not free result', __FUNCTION__);
1199
            }
1200
        }
1201
        $this->result = false;
1202
        return MDB2_OK;
1203
    }
1204
}
1205
 
1206
/**
1207
 * MDB2 MySQL buffered result driver
1208
 *
1209
 * @package MDB2
1210
 * @category Database
1211
 * @author  Lukas Smith <smith@pooteeweet.org>
1212
 */
1213
class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
1214
{
1215
    // }}}
1216
    // {{{ seek()
1217
 
1218
    /**
1219
     * Seek to a specific row in a result set
1220
     *
1221
     * @param int    $rownum    number of the row where the data can be found
1222
     * @return mixed MDB2_OK on success, a MDB2 error on failure
1223
     * @access public
1224
     */
1225
    function seek($rownum = 0)
1226
    {
1227
        if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {
1228
            if ($this->result === false) {
1229
                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1230
                    'resultset has already been freed', __FUNCTION__);
1231
            } elseif (is_null($this->result)) {
1232
                return MDB2_OK;
1233
            }
1234
            return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
1235
                'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
1236
        }
1237
        $this->rownum = $rownum - 1;
1238
        return MDB2_OK;
1239
    }
1240
 
1241
    // }}}
1242
    // {{{ valid()
1243
 
1244
    /**
1245
     * Check if the end of the result set has been reached
1246
     *
1247
     * @return mixed true or false on sucess, a MDB2 error on failure
1248
     * @access public
1249
     */
1250
    function valid()
1251
    {
1252
        $numrows = $this->numRows();
1253
        if (PEAR::isError($numrows)) {
1254
            return $numrows;
1255
        }
1256
        return $this->rownum < ($numrows - 1);
1257
    }
1258
 
1259
    // }}}
1260
    // {{{ numRows()
1261
 
1262
    /**
1263
     * Returns the number of rows in a result object
1264
     *
1265
     * @return mixed MDB2 Error Object or the number of rows
1266
     * @access public
1267
     */
1268
    function numRows()
1269
    {
1270
        $rows = @mysql_num_rows($this->result);
1271
        if (is_null($rows)) {
1272
            if ($this->result === false) {
1273
                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1274
                    'resultset has already been freed', __FUNCTION__);
1275
            } elseif (is_null($this->result)) {
1276
                return 0;
1277
            }
1278
            return $this->db->raiseError(null, null, null,
1279
                'Could not get row count', __FUNCTION__);
1280
        }
1281
        return $rows;
1282
    }
1283
}
1284
 
1285
/**
1286
 * MDB2 MySQL statement driver
1287
 *
1288
 * @package MDB2
1289
 * @category Database
1290
 * @author  Lukas Smith <smith@pooteeweet.org>
1291
 */
1292
class MDB2_Statement_mysql extends MDB2_Statement_Common
1293
{
1294
    // {{{ _execute()
1295
 
1296
    /**
1297
     * Execute a prepared query statement helper method.
1298
     *
1299
     * @param mixed $result_class string which specifies which result class to use
1300
     * @param mixed $result_wrap_class string which specifies which class to wrap results in
1301
     * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
1302
     * @access private
1303
     */
1304
    function &_execute($result_class = true, $result_wrap_class = false)
1305
    {
1306
        if (is_null($this->statement)) {
1307
            $result =& parent::_execute($result_class, $result_wrap_class);
1308
            return $result;
1309
        }
1310
        $this->db->last_query = $this->query;
1311
        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
1312
        if ($this->db->getOption('disable_query')) {
1313
            $result = $this->is_manip ? 0 : null;
1314
            return $result;
1315
        }
1316
 
1317
        $connection = $this->db->getConnection();
1318
        if (PEAR::isError($connection)) {
1319
            return $connection;
1320
        }
1321
 
1322
        $query = 'EXECUTE '.$this->statement;
1323
        if (!empty($this->positions)) {
1324
            $parameters = array();
1325
            foreach ($this->positions as $parameter) {
1326
                if (!array_key_exists($parameter, $this->values)) {
1327
                    return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
1328
                        'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
1329
                }
1330
                $value = $this->values[$parameter];
1331
                $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
1332
                if (is_resource($value) || $type == 'clob' || $type == 'blob') {
1333
                    if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
1334
                        if ($match[1] == 'file://') {
1335
                            $value = $match[2];
1336
                        }
1337
                        $value = @fopen($value, 'r');
1338
                        $close = true;
1339
                    }
1340
                    if (is_resource($value)) {
1341
                        $data = '';
1342
                        while (!@feof($value)) {
1343
                            $data.= @fread($value, $this->db->options['lob_buffer_length']);
1344
                        }
1345
                        if ($close) {
1346
                            @fclose($value);
1347
                        }
1348
                        $value = $data;
1349
                    }
1350
                }
1351
                $param_query = 'SET @'.$parameter.' = '.$this->db->quote($value, $type);
1352
                $result = $this->db->_doQuery($param_query, true, $connection);
1353
                if (PEAR::isError($result)) {
1354
                    return $result;
1355
                }
1356
            }
1357
            $query.= ' USING @'.implode(', @', array_values($this->positions));
1358
        }
1359
 
1360
        $result = $this->db->_doQuery($query, $this->is_manip, $connection);
1361
        if (PEAR::isError($result)) {
1362
            return $result;
1363
        }
1364
 
1365
        if ($this->is_manip) {
1366
            $affected_rows = $this->db->_affectedRows($connection, $result);
1367
            return $affected_rows;
1368
        }
1369
 
1370
        $result =& $this->db->_wrapResult($result, $this->result_types,
1371
            $result_class, $result_wrap_class, $this->limit, $this->offset);
1372
        $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
1373
        return $result;
1374
    }
1375
 
1376
    // }}}
1377
    // {{{ free()
1378
 
1379
    /**
1380
     * Release resources allocated for the specified prepared query.
1381
     *
1382
     * @return mixed MDB2_OK on success, a MDB2 error on failure
1383
     * @access public
1384
     */
1385
    function free()
1386
    {
1387
        if (is_null($this->positions)) {
1388
            return $this->db->raiseError(MDB2_ERROR, null, null,
1389
                'Prepared statement has already been freed', __FUNCTION__);
1390
        }
1391
        $result = MDB2_OK;
1392
 
1393
        if (!is_null($this->statement)) {
1394
            $connection = $this->db->getConnection();
1395
            if (PEAR::isError($connection)) {
1396
                return $connection;
1397
            }
1398
            $query = 'DEALLOCATE PREPARE '.$this->statement;
1399
            $result = $this->db->_doQuery($query, true, $connection);
1400
        }
1401
 
1402
        parent::free();
1403
        return $result;
1404
    }
1405
}
1406
?>