mysqli_native_moodle_database.php 45.7 KB
Newer Older
skodak's avatar
skodak committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.


/**
 * Native mysqli class representing moodle database interface.
 *
22
 * @package    core
23
 * @subpackage dml
skodak's avatar
skodak committed
24
25
26
 * @copyright  2008 Petr Skoda (http://skodak.org)
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
27

28
29
defined('MOODLE_INTERNAL') || die();

30
31
require_once($CFG->libdir.'/dml/moodle_database.php');
require_once($CFG->libdir.'/dml/mysqli_native_moodle_recordset.php');
32
require_once($CFG->libdir.'/dml/mysqli_native_moodle_temptables.php');
33
34
35
36
37
38

/**
 * Native mysqli class representing moodle database interface.
 */
class mysqli_native_moodle_database extends moodle_database {

39
    protected $mysqli = null;
40

41
42
    private $transactions_supported = null;

43
44
45
46
47
48
49
50
51
    /**
     * Attempt to create the database
     * @param string $dbhost
     * @param string $dbuser
     * @param string $dbpass
     * @param string $dbname
     * @return bool success
     * @throws dml_exception if error
     */
skodak's avatar
skodak committed
52
    public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
53
54
55
56
57
58
        $driverstatus = $this->driver_installed();

        if ($driverstatus !== true) {
            throw new dml_exception('dbdriverproblem', $driverstatus);
        }

59
60
61
62
63
        if (empty($this->dboptions['dbport'])) {
            $dbport = ini_get('mysqli.default_port');
        } else {
            $dbport = (int)$this->dboptions['dbport'];
        }
64
        ob_start();
65
        $conn = new mysqli($dbhost, $dbuser, $dbpass, '', $dbport); /// Connect without db
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        $dberr = ob_get_contents();
        ob_end_clean();
        $errorno = @$conn->connect_errno;

        if ($errorno !== 0) {
            throw new dml_connection_exception($dberr);
        }

        $result = $conn->query("CREATE DATABASE $dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci");

        $conn->close();

        if (!$result) {
            throw new dml_exception('cannotcreatedb');
        }

        return true;
    }

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    /**
     * Detects if all needed PHP stuff installed.
     * Note: can be used before connect()
     * @return mixed true if ok, string if something
     */
    public function driver_installed() {
        if (!extension_loaded('mysqli')) {
            return get_string('mysqliextensionisnotpresentinphp', 'install');
        }
        return true;
    }

    /**
     * Returns database family type - describes SQL dialect
     * Note: can be used before connect()
     * @return string db family name (mysql, postgres, mssql, oracle, etc.)
     */
    public function get_dbfamily() {
        return 'mysql';
    }

    /**
     * Returns more specific database driver type
     * Note: can be used before connect()
109
     * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
110
111
112
113
114
115
116
117
     */
    protected function get_dbtype() {
        return 'mysqli';
    }

    /**
     * Returns general database library name
     * Note: can be used before connect()
118
     * @return string db type pdo, native
119
120
121
122
123
     */
    protected function get_dblibrary() {
        return 'native';
    }

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    /**
     * Returns the current MySQL db engine.
     *
     * This is an ugly workaround for MySQL default engine problems,
     * Moodle is designed to work best on ACID compliant databases
     * with full transaction support. Do not use MyISAM.
     *
     * @return string or null MySQL engine name
     */
    public function get_dbengine() {
        if (isset($this->dboptions['dbengine'])) {
            return $this->dboptions['dbengine'];
        }

        $engine = null;

        if (!$this->external) {
            // look for current engine of our config table (the first table that gets created),
            // so that we create all tables with the same engine
            $sql = "SELECT engine FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = DATABASE() AND table_name = '{$this->prefix}config'";
            $this->query_start($sql, NULL, SQL_QUERY_AUX);
            $result = $this->mysqli->query($sql);
            $this->query_end($result);
            if ($rec = $result->fetch_assoc()) {
                $engine = $rec['engine'];
            }
            $result->close();
        }

        if ($engine) {
            return $engine;
        }

        // get the default database engine
        $sql = "SELECT @@storage_engine";
        $this->query_start($sql, NULL, SQL_QUERY_AUX);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);
        if ($rec = $result->fetch_assoc()) {
            $engine = $rec['@@storage_engine'];
        }
        $result->close();

        if (!$this->external and $engine === 'MyISAM') {
            // we really do not want MyISAM for Moodle, InnoDB or XtraDB is a reasonable defaults if supported
            $sql = "SHOW STORAGE ENGINES";
            $this->query_start($sql, NULL, SQL_QUERY_AUX);
            $result = $this->mysqli->query($sql);
            $this->query_end($result);
173
            $engines = array();
174
            while ($res = $result->fetch_assoc()) {
175
176
                if ($res['Support'] === 'YES' or $res['Support'] === 'DEFAULT') {
                    $engines[$res['Engine']] = true;
177
178
179
                }
            }
            $result->close();
180
181
182
183
184
185
            if (isset($engines['InnoDB'])) {
                $engine = 'InnoDB';
            }
            if (isset($engines['XtraDB'])) {
                $engine = 'XtraDB';
            }
186
187
188
189
190
        }

        return $engine;
    }

191
192
193
194
195
196
    /**
     * Returns localised database type name
     * Note: can be used before connect()
     * @return string
     */
    public function get_name() {
197
        return get_string('nativemysqli', 'install');
198
199
    }

skodak's avatar
skodak committed
200
201
202
203
204
205
206
207
208
    /**
     * Returns localised database configuration help.
     * Note: can be used before connect()
     * @return string
     */
    public function get_configuration_help() {
        return get_string('nativemysqlihelp', 'install');
    }

209
210
211
212
213
214
    /**
     * Returns localised database description
     * Note: can be used before connect()
     * @return string
     */
    public function get_configuration_hints() {
215
        return get_string('databasesettingssub_mysqli', 'install');
216
217
    }

218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    /**
     * Diagnose database and tables, this function is used
     * to verify database and driver settings, db engine types, etc.
     *
     * @return string null means everything ok, string means problem found.
     */
    public function diagnose() {
        $sloppymyisamfound = false;
        $prefix = str_replace('_', '\\_', $this->prefix);
        $sql = "SHOW TABLE STATUS WHERE Name LIKE BINARY '$prefix%'";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);
        if ($result) {
            while ($arr = $result->fetch_assoc()) {
                if ($arr['Engine'] === 'MyISAM') {
                    $sloppymyisamfound = true;
                    break;
                }
            }
            $result->close();
        }

        if ($sloppymyisamfound) {
            return get_string('myisamproblem', 'error');
        } else {
            return null;
        }
    }

248
249
250
251
252
253
254
255
256
257
258
    /**
     * Connect to db
     * Must be called before other methods.
     * @param string $dbhost
     * @param string $dbuser
     * @param string $dbpass
     * @param string $dbname
     * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
     * @param array $dboptions driver specific options
     * @return bool success
     */
259
    public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
260
261
262
263
264
265
        $driverstatus = $this->driver_installed();

        if ($driverstatus !== true) {
            throw new dml_exception('dbdriverproblem', $driverstatus);
        }

266
        $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
267

268
269
270
271
272
273
274
        // dbsocket is used ONLY if host is NULL or 'localhost',
        // you can not disable it because it is always tried if dbhost is 'localhost'
        if (!empty($this->dboptions['dbsocket']) and strpos($this->dboptions['dbsocket'], '/') !== false) {
            $dbsocket = $this->dboptions['dbsocket'];
        } else {
            $dbsocket = ini_get('mysqli.default_socket');
        }
275
276
277
278
279
        if (empty($this->dboptions['dbport'])) {
            $dbport = ini_get('mysqli.default_port');
        } else {
            $dbport = (int)$this->dboptions['dbport'];
        }
280
        ob_start();
281
        $this->mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname, $dbport, $dbsocket);
282
283
284
285
286
287
        $dberr = ob_get_contents();
        ob_end_clean();
        $errorno = @$this->mysqli->connect_errno;

        if ($errorno !== 0) {
            throw new dml_connection_exception($dberr);
288
        }
289

290
        $this->query_start("--set_charset()", null, SQL_QUERY_AUX);
291
        $this->mysqli->set_charset('utf8');
292
293
        $this->query_end(true);

294
295
296
        // If available, enforce strict mode for the session. That guaranties
        // standard behaviour under some situations, avoiding some MySQL nasty
        // habits like truncating data or performing some transparent cast losses.
Petr Skoda's avatar
Petr Skoda committed
297
        // With strict mode enforced, Moodle DB layer will be consistently throwing
298
299
300
301
302
303
304
305
306
        // the corresponding exceptions as expected.
        $si = $this->get_server_info();
        if (version_compare($si['version'], '5.0.2', '>=')) {
            $sql = "SET SESSION sql_mode = 'STRICT_ALL_TABLES'";
            $this->query_start($sql, null, SQL_QUERY_AUX);
            $result = $this->mysqli->query($sql);
            $this->query_end($result);
        }

307
308
309
        // Connection stabilished and configured, going to instantiate the temptables controller
        $this->temptables = new mysqli_native_moodle_temptables($this);

310
311
312
313
314
315
316
317
318
        return true;
    }

    /**
     * Close database connection and release all resources
     * and memory (especially circular memory references).
     * Do NOT use connect() again, create a new instance if needed.
     */
    public function dispose() {
Petr Skoda's avatar
Petr Skoda committed
319
        parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
        if ($this->mysqli) {
            $this->mysqli->close();
            $this->mysqli = null;
        }
    }

    /**
     * Returns database server info array
     * @return array
     */
    public function get_server_info() {
        return array('description'=>$this->mysqli->server_info, 'version'=>$this->mysqli->server_info);
    }

    /**
     * Returns supported query parameter types
Petr Skoda's avatar
Petr Skoda committed
336
     * @return int bitmask
337
338
339
340
341
342
343
     */
    protected function allowed_param_types() {
        return SQL_PARAMS_QM;
    }

    /**
     * Returns last error reported by database engine.
Petr Skoda's avatar
Petr Skoda committed
344
     * @return string error message
345
346
347
348
349
350
351
352
353
     */
    public function get_last_error() {
        return $this->mysqli->error;
    }

    /**
     * Return tables in database WITHOUT current prefix
     * @return array of table names in lowercase and without prefix
     */
354
355
356
357
358
    public function get_tables($usecache=true) {
        if ($usecache and $this->tables !== null) {
            return $this->tables;
        }
        $this->tables = array();
359
360
361
362
363
        $sql = "SHOW TABLES";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);
        if ($result) {
364
365
            while ($arr = $result->fetch_assoc()) {
                $tablename = reset($arr);
366
367
368
369
370
                if ($this->prefix !== '') {
                    if (strpos($tablename, $this->prefix) !== 0) {
                        continue;
                    }
                    $tablename = substr($tablename, strlen($this->prefix));
371
                }
372
                $this->tables[$tablename] = $tablename;
373
374
375
            }
            $result->close();
        }
376
377
378

        // Add the currently available temptables
        $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
379
        return $this->tables;
380
381
382
383
384
385
386
387
    }

    /**
     * Return table indexes - everything lowercased
     * @return array of arrays
     */
    public function get_indexes($table) {
        $indexes = array();
388
389
390
391
392
        $sql = "SHOW INDEXES FROM {$this->prefix}$table";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);
        if ($result) {
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
            while ($res = $result->fetch_object()) {
                if ($res->Key_name === 'PRIMARY') {
                    continue;
                }
                if (!isset($indexes[$res->Key_name])) {
                    $indexes[$res->Key_name] = array('unique'=>empty($res->Non_unique), 'columns'=>array());
                }
                $indexes[$res->Key_name]['columns'][$res->Seq_in_index-1] = $res->Column_name;
            }
            $result->close();
        }
        return $indexes;
    }

    /**
Petr Skoda's avatar
Petr Skoda committed
408
     * Returns detailed information about columns in table. This information is cached internally.
409
410
411
412
413
414
415
416
417
418
419
     * @param string $table name
     * @param bool $usecache
     * @return array array of database_column_info objects indexed with column names
     */
    public function get_columns($table, $usecache=true) {
        if ($usecache and isset($this->columns[$table])) {
            return $this->columns[$table];
        }

        $this->columns[$table] = array();

420
421
422
423
424
425
        $sql = "SHOW COLUMNS FROM {$this->prefix}$table";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);

        if ($result === false) {
426
427
428
            return array();
        }

429
430
431
        while ($rawcolumn = $result->fetch_assoc()) {
            $rawcolumn = (object)array_change_key_case($rawcolumn, CASE_LOWER);

Petr Skoda's avatar
Petr Skoda committed
432
            $info = new stdClass();
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
            $info->name = $rawcolumn->field;
            $matches = null;

            if (preg_match('/varchar\((\d+)\)/i', $rawcolumn->type, $matches)) {
                $info->type          = 'varchar';
                $info->meta_type     = 'C';
                $info->max_length    = $matches[1];
                $info->scale         = null;
                $info->not_null      = ($rawcolumn->null === 'NO');
                $info->default_value = $rawcolumn->default;
                $info->has_default   = is_null($info->default_value) ? false : true;
                $info->primary_key   = ($rawcolumn->key === 'PRI');
                $info->binary        = false;
                $info->unsigned      = null;
                $info->auto_increment= false;
                $info->unique        = null;

            } else if (preg_match('/([a-z]*int[a-z]*)\((\d+)\)/i', $rawcolumn->type, $matches)) {
                $info->type = $matches[1];
                $info->primary_key       = ($rawcolumn->key === 'PRI');
                if ($info->primary_key) {
                    $info->meta_type     = 'R';
                    $info->max_length    = $matches[2];
                    $info->scale         = null;
                    $info->not_null      = ($rawcolumn->null === 'NO');
                    $info->default_value = $rawcolumn->default;
                    $info->has_default   = is_null($info->default_value) ? false : true;
                    $info->binary        = false;
                    $info->unsigned      = (stripos($rawcolumn->type, 'unsigned') !== false);
                    $info->auto_increment= true;
                    $info->unique        = true;
                } else {
                    $info->meta_type     = 'I';
                    $info->max_length    = $matches[2];
                    $info->scale         = null;
                    $info->not_null      = ($rawcolumn->null === 'NO');
                    $info->default_value = $rawcolumn->default;
                    $info->has_default   = is_null($info->default_value) ? false : true;
                    $info->binary        = false;
                    $info->unsigned      = (stripos($rawcolumn->type, 'unsigned') !== false);
                    $info->auto_increment= false;
                    $info->unique        = null;
                }

477
478
            } else if (preg_match('/(decimal|double|float)\((\d+),(\d+)\)/i', $rawcolumn->type, $matches)) {
                $info->type          = $matches[1];
479
                $info->meta_type     = 'N';
480
481
                $info->max_length    = $matches[2];
                $info->scale         = $matches[3];
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
                $info->not_null      = ($rawcolumn->null === 'NO');
                $info->default_value = $rawcolumn->default;
                $info->has_default   = is_null($info->default_value) ? false : true;
                $info->primary_key   = ($rawcolumn->key === 'PRI');
                $info->binary        = false;
                $info->unsigned      = null;
                $info->auto_increment= false;
                $info->unique        = null;

            } else if (preg_match('/([a-z]*text)/i', $rawcolumn->type, $matches)) {
                $info->type          = $matches[1];
                $info->meta_type     = 'X';
                $info->max_length    = -1;
                $info->scale         = null;
                $info->not_null      = ($rawcolumn->null === 'NO');
                $info->default_value = $rawcolumn->default;
                $info->has_default   = is_null($info->default_value) ? false : true;
                $info->primary_key   = ($rawcolumn->key === 'PRI');
                $info->binary        = false;
                $info->unsigned      = null;
                $info->auto_increment= false;
                $info->unique        = null;

505
506
507
508
509
510
511
512
513
514
515
516
517
518
            } else if (preg_match('/([a-z]*blob)/i', $rawcolumn->type, $matches)) {
                $info->type          = $matches[1];
                $info->meta_type     = 'B';
                $info->max_length    = -1;
                $info->scale         = null;
                $info->not_null      = ($rawcolumn->null === 'NO');
                $info->default_value = $rawcolumn->default;
                $info->has_default   = is_null($info->default_value) ? false : true;
                $info->primary_key   = false;
                $info->binary        = true;
                $info->unsigned      = null;
                $info->auto_increment= false;
                $info->unique        = null;

519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
            } else if (preg_match('/enum\((.*)\)/i', $rawcolumn->type, $matches)) {
                $info->type          = 'enum';
                $info->meta_type     = 'C';
                $info->enums         = array();
                $info->max_length    = 0;
                $values = $matches[1];
                $values = explode(',', $values);
                $textlib = textlib_get_instance();
                foreach ($values as $val) {
                    $val = trim($val, "'");
                    $length = $textlib->strlen($val);
                    $info->enums[] = $val;
                    $info->max_length = ($info->max_length < $length) ? $length : $info->max_length;
                }
                $info->scale         = null;
                $info->not_null      = ($rawcolumn->null === 'NO');
                $info->default_value = $rawcolumn->default;
                $info->has_default   = is_null($info->default_value) ? false : true;
                $info->primary_key   = ($rawcolumn->key === 'PRI');
                $info->binary        = false;
                $info->unsigned      = null;
                $info->auto_increment= false;
                $info->unique        = null;
            }

            $this->columns[$table][$info->name] = new database_column_info($info);
        }

547
548
        $result->close();

549
550
551
        return $this->columns[$table];
    }

552
553
554
555
556
557
558
    /**
     * Normalise values based in RDBMS dependencies (booleans, LOBs...)
     *
     * @param database_column_info $column column metadata corresponding with the value we are going to normalise
     * @param mixed $value value we are going to normalise
     * @return mixed the normalised value
     */
559
    protected function normalise_value($column, $value) {
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
        if (is_bool($value)) { // Always, convert boolean to int
            $value = (int)$value;

        } else if ($value === '') {
            if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
                $value = 0; // prevent '' problems in numeric fields
            }
        }
        // workaround for problem with wrong enums in mysql - TODO: Out in Moodle 2.1
        if (!empty($column->enums)) {
            if (is_null($value) and !$column->not_null) {
                // ok - nulls allowed
            } else {
                if (!in_array((string)$value, $column->enums)) {
                    throw new dml_write_exception('Enum value '.s($value).' not allowed in field '.$field.' table '.$table.'.');
                }
            }
        }
        return $value;
    }

581
582
583
584
585
    /**
     * Is db in unicode mode?
     * @return bool
     */
    public function setup_is_unicodedb() {
586
587
588
589
590
        $sql = "SHOW LOCAL VARIABLES LIKE 'character_set_database'";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);

591
        $return = false;
592
        if ($result) {
593
594
595
596
597
598
            while($row = $result->fetch_assoc()) {
                if (isset($row['Value'])) {
                    $return = (strtoupper($row['Value']) === 'UTF8' or strtoupper($row['Value']) === 'UTF-8');
                }
                break;
            }
599
600
            $result->close();
        }
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622

        if (!$return) {
            return false;
        }

        $sql = "SHOW LOCAL VARIABLES LIKE 'collation_database'";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);

        $return = false;
        if ($result) {
            while($row = $result->fetch_assoc()) {
                if (isset($row['Value'])) {
                    $return = (strpos($row['Value'], 'latin1') !== 0);
                }
                break;
            }
            $result->close();
        }

        return $return;
623
624
625
626
627
    }

    /**
     * Do NOT use in code, to be used by database_manager only!
     * @param string $sql query
628
629
     * @return bool true
     * @throws dml_exception if error
630
631
     */
    public function change_database_structure($sql) {
632
        $this->reset_caches();
633
634
635
636
637

        $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);

638
        return true;
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
    }

    /**
     * Very ugly hack which emulates bound parameters in queries
     * because prepared statements do not use query cache.
     */
    protected function emulate_bound_params($sql, array $params=null) {
        if (empty($params)) {
            return $sql;
        }
        /// ok, we have verified sql statement with ? and correct number of params
        $return = strtok($sql, '?');
        foreach ($params as $param) {
            if (is_bool($param)) {
                $return .= (int)$param;
            } else if (is_null($param)) {
                $return .= 'NULL';
656
657
            } else if (is_number($param)) {
                $return .= "'".$param."'"; // we have to always use strings because mysql is using weird automatic int casting
658
            } else if (is_float($param)) {
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
                $return .= $param;
            } else {
                $param = $this->mysqli->real_escape_string($param);
                $return .= "'$param'";
            }
            $return .= strtok('?');
        }
        return $return;
    }

    /**
     * Execute general sql query. Should be used only when no other method suitable.
     * Do NOT use this to make changes in db structure, use database_manager::execute_sql() instead!
     * @param string $sql query
     * @param array $params query parameters
674
675
     * @return bool true
     * @throws dml_exception if error
676
677
678
679
680
     */
    public function execute($sql, array $params=null) {
        list($sql, $params, $type) = $this->fix_sql_params($sql, $params);

        if (strpos($sql, ';') !== false) {
681
            throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
682
683
684
685
        }

        $rawsql = $this->emulate_bound_params($sql, $params);

686
        $this->query_start($sql, $params, SQL_QUERY_UPDATE);
687
        $result = $this->mysqli->query($rawsql);
688
        $this->query_end($result);
689

690
        if ($result === true) {
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
            return true;

        } else {
            $result->close();
            return true;
        }
    }

    /**
     * Get a number of records as a moodle_recordset using a SQL statement.
     *
     * Since this method is a little less readable, use of it should be restricted to
     * code where it's possible there might be large datasets being returned.  For known
     * small datasets use get_records_sql - it leads to simpler code.
     *
     * The return type is as for @see function get_recordset.
     *
     * @param string $sql the SQL select query to execute.
     * @param array $params array of sql parameters
     * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
     * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
712
     * @return moodle_recordset instance
713
     * @throws dml_exception if error
714
715
     */
    public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
skodak's avatar
skodak committed
716
717
        $limitfrom = (int)$limitfrom;
        $limitnum  = (int)$limitnum;
718
719
720
        $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
        $limitnum  = ($limitnum < 0)  ? 0 : $limitnum;

721
722
723
724
        if ($limitfrom or $limitnum) {
            if ($limitnum < 1) {
                $limitnum = "18446744073709551615";
            }
725
            $sql .= " LIMIT $limitfrom, $limitnum";
726
727
        }

728
729
730
        list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
        $rawsql = $this->emulate_bound_params($sql, $params);

731
        $this->query_start($sql, $params, SQL_QUERY_SELECT);
732
        // no MYSQLI_USE_RESULT here, it would block write ops on affected tables
733
734
        $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
        $this->query_end($result);
735

736
        return $this->create_recordset($result);
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
    }

    protected function create_recordset($result) {
        return new mysqli_native_moodle_recordset($result);
    }

    /**
     * Get a number of records as an array of objects using a SQL statement.
     *
     * Return value as for @see function get_records.
     *
     * @param string $sql the SQL select query to execute. The first column of this SELECT statement
     *   must be a unique value (usually the 'id' field), as it will be used as the key of the
     *   returned array.
     * @param array $params array of sql parameters
     * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
     * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
754
     * @return array of objects, or empty array if no records were found
755
     * @throws dml_exception if error
756
757
     */
    public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
skodak's avatar
skodak committed
758
759
        $limitfrom = (int)$limitfrom;
        $limitnum  = (int)$limitnum;
760
761
762
        $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
        $limitnum  = ($limitnum < 0)  ? 0 : $limitnum;

763
764
765
766
        if ($limitfrom or $limitnum) {
            if ($limitnum < 1) {
                $limitnum = "18446744073709551615";
            }
767
            $sql .= " LIMIT $limitfrom, $limitnum";
768
769
        }

770
771
772
        list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
        $rawsql = $this->emulate_bound_params($sql, $params);

773
        $this->query_start($sql, $params, SQL_QUERY_SELECT);
774
        $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
775
        $this->query_end($result);
776
777

        $return = array();
778

779
780
781
        while($row = $result->fetch_assoc()) {
            $row = array_change_key_case($row, CASE_LOWER);
            $id  = reset($row);
782
783
784
785
            if (isset($return[$id])) {
                $colname = key($row);
                debugging("Did you remember to make the first column something unique in your call to get_records? Duplicate value '$id' found in column '$colname'.", DEBUG_DEVELOPER);
            }
786
787
788
            $return[$id] = (object)$row;
        }
        $result->close();
789

790
791
792
793
794
795
796
797
        return $return;
    }

    /**
     * Selects records and return values (first field) as an array using a SQL statement.
     *
     * @param string $sql The SQL query
     * @param array $params array of sql parameters
798
     * @return array of values
799
     * @throws dml_exception if error
800
801
802
803
804
     */
    public function get_fieldset_sql($sql, array $params=null) {
        list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
        $rawsql = $this->emulate_bound_params($sql, $params);

805
        $this->query_start($sql, $params, SQL_QUERY_SELECT);
806
        $result = $this->mysqli->query($rawsql, MYSQLI_STORE_RESULT);
807
        $this->query_end($result);
808
809

        $return = array();
810

811
812
813
814
        while($row = $result->fetch_assoc()) {
            $return[] = reset($row);
        }
        $result->close();
815

816
817
818
819
820
821
822
823
824
825
        return $return;
    }

    /**
     * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
     * @param string $table name
     * @param mixed $params data record as object or array
     * @param bool $returnit return it of inserted record
     * @param bool $bulk true means repeated inserts expected
     * @param bool $customsequence true if 'id' included in $params, disables $returnid
826
     * @return bool|int true or new id
827
     * @throws dml_exception if error
828
829
830
831
832
833
834
835
     */
    public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
        if (!is_array($params)) {
            $params = (array)$params;
        }

        if ($customsequence) {
            if (!isset($params['id'])) {
836
                throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
837
838
839
840
841
842
843
            }
            $returnid = false;
        } else {
            unset($params['id']);
        }

        if (empty($params)) {
844
            throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
845
846
847
848
849
850
851
        }

        $fields = implode(',', array_keys($params));
        $qms    = array_fill(0, count($params), '?');
        $qms    = implode(',', $qms);

        $sql = "INSERT INTO {$this->prefix}$table ($fields) VALUES($qms)";
852
853

        list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
854
855
        $rawsql = $this->emulate_bound_params($sql, $params);

856
        $this->query_start($sql, $params, SQL_QUERY_INSERT);
857
        $result = $this->mysqli->query($rawsql);
858
        $id = @$this->mysqli->insert_id; // must be called before query_end() which may insert log into db
859
        $this->query_end($result);
860

861
        if (!$id) {
862
            throw new dml_write_exception('unknown error fetching inserted id');
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
        }

        if (!$returnid) {
            return true;
        } else {
            return (int)$id;
        }
    }

    /**
     * Insert a record into a table and return the "id" field if required.
     *
     * Some conversions and safety checks are carried out. Lobs are supported.
     * If the return ID isn't required, then this just reports success as true/false.
     * $data is an object containing needed data
     * @param string $table The database table to be inserted into
     * @param object $data A data object with values for one or more fields in the record
     * @param bool $returnid Should the id of the newly created record entry be returned? If this option is not requested then true/false is returned.
881
     * @return bool|int true or new id
882
     * @throws dml_exception if error
883
884
     */
    public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
885
        $dataobject = (array)$dataobject;
886
887
888
889
890

        $columns = $this->get_columns($table);
        $cleaned = array();

        foreach ($dataobject as $field=>$value) {
891
892
893
            if ($field === 'id') {
                continue;
            }
894
895
896
897
            if (!isset($columns[$field])) {
                continue;
            }
            $column = $columns[$field];
898
            $cleaned[$field] = $this->normalise_value($column, $value);
899
900
901
902
903
904
905
906
907
908
909
        }

        return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
    }

    /**
     * Import a record into a table, id field is required.
     * Safety checks are NOT carried out. Lobs are supported.
     *
     * @param string $table name of database table to be inserted into
     * @param object $dataobject A data object with values for one or more fields in the record
910
911
     * @return bool true
     * @throws dml_exception if error
912
913
     */
    public function import_record($table, $dataobject) {
914
        $dataobject = (array)$dataobject;
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933

        $columns = $this->get_columns($table);
        $cleaned = array();

        foreach ($dataobject as $field=>$value) {
            if (!isset($columns[$field])) {
                continue;
            }
            $cleaned[$field] = $value;
        }

        return $this->insert_record_raw($table, $cleaned, false, true, true);
    }

    /**
     * Update record in database, as fast as possible, no safety checks, lobs not supported.
     * @param string $table name
     * @param mixed $params data record as object or array
     * @param bool true means repeated updates expected
934
935
     * @return bool true
     * @throws dml_exception if error
936
937
     */
    public function update_record_raw($table, $params, $bulk=false) {
938
939
        $params = (array)$params;

940
        if (!isset($params['id'])) {
941
            throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
942
943
944
945
946
        }
        $id = $params['id'];
        unset($params['id']);

        if (empty($params)) {
947
            throw new coding_exception('moodle_database::update_record_raw() no fields found.');
948
949
950
951
952
953
954
955
956
957
958
        }

        $sets = array();
        foreach ($params as $field=>$value) {
            $sets[] = "$field = ?";
        }

        $params[] = $id; // last ? in WHERE condition

        $sets = implode(',', $sets);
        $sql = "UPDATE {$this->prefix}$table SET $sets WHERE id=?";
959
960

        list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
961
962
        $rawsql = $this->emulate_bound_params($sql, $params);

963
        $this->query_start($sql, $params, SQL_QUERY_UPDATE);
964
        $result = $this->mysqli->query($rawsql);
965
        $this->query_end($result);
966
967
968
969
970
971
972
973
974
975
976
977
978
979

        return true;
    }

    /**
     * Update a record in a table
     *
     * $dataobject is an object containing needed data
     * Relies on $dataobject having a variable "id" to
     * specify the record to update
     *
     * @param string $table The database table to be checked against.
     * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
     * @param bool true means repeated updates expected
980
981
     * @return bool true
     * @throws dml_exception if error
982
983
     */
    public function update_record($table, $dataobject, $bulk=false) {
984
        $dataobject = (array)$dataobject;
985
986
987
988
989
990
991
992

        $columns = $this->get_columns($table);
        $cleaned = array();

        foreach ($dataobject as $field=>$value) {
            if (!isset($columns[$field])) {
                continue;
            }
993
994
            $column = $columns[$field];
            $cleaned[$field] = $this->normalise_value($column, $value);
995
996
997
998
999
1000
        }

        return $this->update_record_raw($table, $cleaned, $bulk);
    }

    /**
For faster browsing, not all history is shown. View entire blame