forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlsrv_native_moodle_database.php
1392 lines (1190 loc) · 50.2 KB
/
sqlsrv_native_moodle_database.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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 2 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 sqlsrv class representing moodle database interface.
*
* @package core_dml
* @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__.'/moodle_database.php');
require_once(__DIR__.'/sqlsrv_native_moodle_recordset.php');
require_once(__DIR__.'/sqlsrv_native_moodle_temptables.php');
/**
* Native sqlsrv class representing moodle database interface.
*
* @package core_dml
* @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later
*/
class sqlsrv_native_moodle_database extends moodle_database {
protected $sqlsrv = null;
protected $last_error_reporting; // To handle SQL*Server-Native driver default verbosity
protected $temptables; // Control existing temptables (sqlsrv_moodle_temptables object)
protected $collation; // current DB collation cache
/**
* Constructor - instantiates the database, specifying if it's external (connect to other systems) or no (Moodle DB)
* note this has effect to decide if prefix checks must be performed or no
* @param bool true means external database used
*/
public function __construct($external=false) {
parent::__construct($external);
}
/**
* 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() {
// use 'function_exists()' rather than 'extension_loaded()' because
// the name used by 'extension_loaded()' is case specific! The extension
// therefore *could be* mixed case and hence not found.
if (!function_exists('sqlsrv_num_rows')) {
if (stripos(PHP_OS, 'win') === 0) {
return get_string('nativesqlsrvnodriver', 'install');
} else {
return get_string('nativesqlsrvnonwindows', 'install');
}
}
return true;
}
/**
* Returns database family type - describes SQL dialect
* Note: can be used before connect()
* @return string db family name (mysql, postgres, mssql, sqlsrv, oracle, etc.)
*/
public function get_dbfamily() {
return 'mssql';
}
/**
* Returns more specific database driver type
* Note: can be used before connect()
* @return string db type mysqli, pgsql, oci, mssql, sqlsrv
*/
protected function get_dbtype() {
return 'sqlsrv';
}
/**
* Returns general database library name
* Note: can be used before connect()
* @return string db type pdo, native
*/
protected function get_dblibrary() {
return 'native';
}
/**
* Returns localised database type name
* Note: can be used before connect()
* @return string
*/
public function get_name() {
return get_string('nativesqlsrv', 'install');
}
/**
* Returns localised database configuration help.
* Note: can be used before connect()
* @return string
*/
public function get_configuration_help() {
return get_string('nativesqlsrvhelp', 'install');
}
/**
* Returns localised database description
* Note: can be used before connect()
* @return string
*/
public function get_configuration_hints() {
$str = get_string('databasesettingssub_sqlsrv', 'install');
$str .= "<p style='text-align:right'><a href=\"javascript:void(0)\" ";
$str .= "onclick=\"return window.open('http://docs.moodle.org/en/Using_the_Microsoft_SQL_Server_Driver_for_PHP')\"";
$str .= ">";
$str .= '<img src="pix/docs.gif'.'" alt="Docs" class="iconhelp" />';
$str .= get_string('moodledocslink', 'install').'</a></p>';
return $str;
}
/**
* Connect to db
* Must be called before most other methods. (you can call methods that return connection configuration parameters)
* @param string $dbhost The database host.
* @param string $dbuser The database username.
* @param string $dbpass The database username's password.
* @param string $dbname The name of the database being connected to.
* @param mixed $prefix string|bool The moodle db table name's prefix. false is used for external databases where prefix not used
* @param array $dboptions driver specific options
* @return bool true
* @throws dml_connection_exception if error
*/
public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
$driverstatus = $this->driver_installed();
if ($driverstatus !== true) {
throw new dml_exception('dbdriverproblem', $driverstatus);
}
/*
* Log all Errors.
*/
sqlsrv_configure("WarningsReturnAsErrors", FALSE);
sqlsrv_configure("LogSubsystems", SQLSRV_LOG_SYSTEM_OFF);
sqlsrv_configure("LogSeverity", SQLSRV_LOG_SEVERITY_ERROR);
$this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
$this->sqlsrv = sqlsrv_connect($this->dbhost, array
(
'UID' => $this->dbuser,
'PWD' => $this->dbpass,
'Database' => $this->dbname,
'CharacterSet' => 'UTF-8',
'MultipleActiveResultSets' => true,
'ConnectionPooling' => !empty($this->dboptions['dbpersist']),
'ReturnDatesAsStrings' => true,
));
if ($this->sqlsrv === false) {
$this->sqlsrv = null;
$dberr = $this->get_last_error();
throw new dml_connection_exception($dberr);
}
// Allow quoted identifiers
$sql = "SET QUOTED_IDENTIFIER ON";
$this->query_start($sql, null, SQL_QUERY_AUX);
$result = sqlsrv_query($this->sqlsrv, $sql);
$this->query_end($result);
$this->free_result($result);
// Force ANSI nulls so the NULL check was done by IS NULL and NOT IS NULL
// instead of equal(=) and distinct(<>) symbols
$sql = "SET ANSI_NULLS ON";
$this->query_start($sql, null, SQL_QUERY_AUX);
$result = sqlsrv_query($this->sqlsrv, $sql);
$this->query_end($result);
$this->free_result($result);
// Force ANSI warnings so arithmetic/string overflows will be
// returning error instead of transparently truncating data
$sql = "SET ANSI_WARNINGS ON";
$this->query_start($sql, null, SQL_QUERY_AUX);
$result = sqlsrv_query($this->sqlsrv, $sql);
$this->query_end($result);
// Concatenating null with anything MUST return NULL
$sql = "SET CONCAT_NULL_YIELDS_NULL ON";
$this->query_start($sql, null, SQL_QUERY_AUX);
$result = sqlsrv_query($this->sqlsrv, $sql);
$this->query_end($result);
$this->free_result($result);
// Set transactions isolation level to READ_COMMITTED
// prevents dirty reads when using transactions +
// is the default isolation level of sqlsrv
$sql = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED";
$this->query_start($sql, NULL, SQL_QUERY_AUX);
$result = sqlsrv_query($this->sqlsrv, $sql);
$this->query_end($result);
$this->free_result($result);
// Connection established and configured, going to instantiate the temptables controller
$this->temptables = new sqlsrv_native_moodle_temptables($this);
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() {
parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
if ($this->sqlsrv) {
sqlsrv_close($this->sqlsrv);
$this->sqlsrv = null;
}
}
/**
* Called before each db query.
* @param string $sql
* @param array $params array of parameters
* @param int $type type of query
* @param mixed $extrainfo driver specific extra information
* @return void
*/
protected function query_start($sql, array $params = null, $type, $extrainfo = null) {
parent::query_start($sql, $params, $type, $extrainfo);
}
/**
* Called immediately after each db query.
* @param mixed db specific result
* @return void
*/
protected function query_end($result) {
parent::query_end($result);
}
/**
* Returns database server info array
* @return array Array containing 'description', 'version' and 'database' (current db) info
*/
public function get_server_info() {
static $info;
if (!$info) {
$server_info = sqlsrv_server_info($this->sqlsrv);
if ($server_info) {
$info['description'] = $server_info['SQLServerName'];
$info['version'] = $server_info['SQLServerVersion'];
$info['database'] = $server_info['CurrentDatabase'];
}
}
return $info;
}
/**
* Override: Converts short table name {tablename} to real table name
* supporting temp tables (#) if detected
*
* @param string sql
* @return string sql
*/
protected function fix_table_names($sql) {
if (preg_match_all('/\{([a-z][a-z0-9_]*)\}/i', $sql, $matches)) {
foreach ($matches[0] as $key => $match) {
$name = $matches[1][$key];
if ($this->temptables->is_temptable($name)) {
$sql = str_replace($match, $this->temptables->get_correct_name($name), $sql);
} else {
$sql = str_replace($match, $this->prefix.$name, $sql);
}
}
}
return $sql;
}
/**
* Returns supported query parameter types
* @return int bitmask
*/
protected function allowed_param_types() {
return SQL_PARAMS_QM; // sqlsrv 1.1 can bind
}
/**
* Returns last error reported by database engine.
* @return string error message
*/
public function get_last_error() {
$retErrors = sqlsrv_errors(SQLSRV_ERR_ALL);
$errorMessage = 'No errors found';
if ($retErrors != null) {
$errorMessage = '';
foreach ($retErrors as $arrError) {
$errorMessage .= "SQLState: ".$arrError['SQLSTATE']."<br>\n";
$errorMessage .= "Error Code: ".$arrError['code']."<br>\n";
$errorMessage .= "Message: ".$arrError['message']."<br>\n";
}
}
return $errorMessage;
}
/**
* Prepare the query binding and do the actual query.
*
* @param string $sql The sql statement
* @param array $params array of params for binding. If NULL, they are ignored.
* @param int $sql_query_type - Type of operation
* @param bool $free_result - Default true, transaction query will be freed.
* @param bool $scrollable - Default false, to use for quickly seeking to target records
* @return resource|bool result
*/
private function do_query($sql, $params, $sql_query_type, $free_result = true, $scrollable = false) {
list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
/*
* Bound variables *are* supported. Until I can get it to work, emulate the bindings
* The challenge/problem/bug is that although they work, doing a SELECT SCOPE_IDENTITY()
* doesn't return a value (no result set)
*
* -- somebody from MS
*/
$sql = $this->emulate_bound_params($sql, $params);
$this->query_start($sql, $params, $sql_query_type);
if (!$scrollable) { // Only supporting next row
$result = sqlsrv_query($this->sqlsrv, $sql);
} else { // Supporting absolute/relative rows
$result = sqlsrv_query($this->sqlsrv, $sql, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC));
}
if ($result === false) {
// TODO do something with error or just use if DEV or DEBUG?
$dberr = $this->get_last_error();
}
$this->query_end($result);
if ($free_result) {
$this->free_result($result);
return true;
}
return $result;
}
/**
* Return tables in database WITHOUT current prefix.
* @param bool $usecache if true, returns list of cached tables.
* @return array of table names in lowercase and without prefix
*/
public function get_tables($usecache = true) {
if ($usecache and count($this->tables) > 0) {
return $this->tables;
}
$this->tables = array ();
$prefix = str_replace('_', '\\_', $this->prefix);
$sql = "SELECT table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name LIKE '$prefix%' ESCAPE '\\' AND table_type = 'BASE TABLE'";
$this->query_start($sql, null, SQL_QUERY_AUX);
$result = sqlsrv_query($this->sqlsrv, $sql);
$this->query_end($result);
if ($result) {
while ($row = sqlsrv_fetch_array($result)) {
$tablename = reset($row);
if ($this->prefix !== '') {
if (strpos($tablename, $this->prefix) !== 0) {
continue;
}
$tablename = substr($tablename, strlen($this->prefix));
}
$this->tables[$tablename] = $tablename;
}
$this->free_result($result);
}
// Add the currently available temptables
$this->tables = array_merge($this->tables, $this->temptables->get_temptables());
return $this->tables;
}
/**
* Return table indexes - everything lowercased.
* @param string $table The table we want to get indexes from.
* @return array of arrays
*/
public function get_indexes($table) {
$indexes = array ();
$tablename = $this->prefix.$table;
// Indexes aren't covered by information_schema metatables, so we need to
// go to sys ones. Skipping primary key indexes on purpose.
$sql = "SELECT i.name AS index_name, i.is_unique, ic.index_column_id, c.name AS column_name
FROM sys.indexes i
JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
JOIN sys.tables t ON i.object_id = t.object_id
WHERE t.name = '$tablename' AND i.is_primary_key = 0
ORDER BY i.name, i.index_id, ic.index_column_id";
$this->query_start($sql, null, SQL_QUERY_AUX);
$result = sqlsrv_query($this->sqlsrv, $sql);
$this->query_end($result);
if ($result) {
$lastindex = '';
$unique = false;
$columns = array ();
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
if ($lastindex and $lastindex != $row['index_name'])
{ // Save lastindex to $indexes and reset info
$indexes[$lastindex] = array
(
'unique' => $unique,
'columns' => $columns
);
$unique = false;
$columns = array ();
}
$lastindex = $row['index_name'];
$unique = empty($row['is_unique']) ? false : true;
$columns[] = $row['column_name'];
}
if ($lastindex) { // Add the last one if exists
$indexes[$lastindex] = array
(
'unique' => $unique,
'columns' => $columns
);
}
$this->free_result($result);
}
return $indexes;
}
/**
* Returns detailed information about columns in table. This information is cached internally.
* @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 ();
if (!$this->temptables->is_temptable($table)) { // normal table, get metadata from own schema
$sql = "SELECT column_name AS name,
data_type AS type,
numeric_precision AS max_length,
character_maximum_length AS char_max_length,
numeric_scale AS scale,
is_nullable AS is_nullable,
columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
column_default AS default_value
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '{".$table."}'
ORDER BY ordinal_position";
} else { // temp table, get metadata from tempdb schema
$sql = "SELECT column_name AS name,
data_type AS type,
numeric_precision AS max_length,
character_maximum_length AS char_max_length,
numeric_scale AS scale,
is_nullable AS is_nullable,
columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
column_default AS default_value
FROM tempdb.INFORMATION_SCHEMA.COLUMNS ".
// check this statement
// JOIN tempdb..sysobjects ON name = table_name
// WHERE id = object_id('tempdb..{".$table."}')
"WHERE table_name LIKE '{".$table."}__________%'
ORDER BY ordinal_position";
}
list($sql, $params, $type) = $this->fix_sql_params($sql, null);
$this->query_start($sql, null, SQL_QUERY_AUX);
$result = sqlsrv_query($this->sqlsrv, $sql);
$this->query_end($result);
if (!$result) {
return array ();
}
while ($rawcolumn = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$rawcolumn = (object)$rawcolumn;
$info = new stdClass();
$info->name = $rawcolumn->name;
$info->type = $rawcolumn->type;
$info->meta_type = $this->sqlsrvtype2moodletype($info->type);
// Prepare auto_increment info
$info->auto_increment = $rawcolumn->auto_increment ? true : false;
// Define type for auto_increment columns
$info->meta_type = ($info->auto_increment && $info->meta_type == 'I') ? 'R' : $info->meta_type;
// id columns being auto_incremnt are PK by definition
$info->primary_key = ($info->name == 'id' && $info->meta_type == 'R' && $info->auto_increment);
// Put correct length for character and LOB types
$info->max_length = $info->meta_type == 'C' ? $rawcolumn->char_max_length : $rawcolumn->max_length;
$info->max_length = ($info->meta_type == 'X' || $info->meta_type == 'B') ? -1 : $info->max_length;
// Scale
$info->scale = $rawcolumn->scale ? $rawcolumn->scale : false;
// Prepare not_null info
$info->not_null = $rawcolumn->is_nullable == 'NO' ? true : false;
// Process defaults
$info->has_default = !empty($rawcolumn->default_value);
if ($rawcolumn->default_value === NULL) {
$info->default_value = NULL;
} else {
$info->default_value = preg_replace("/^[\(N]+[']?(.*?)[']?[\)]+$/", '\\1', $rawcolumn->default_value);
}
// Process binary
$info->binary = $info->meta_type == 'B' ? true : false;
$this->columns[$table][$info->name] = new database_column_info($info);
}
$this->free_result($result);
return $this->columns[$table];
}
/**
* 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
*/
protected function normalise_value($column, $value) {
$this->detect_objects($value);
if (is_bool($value)) { // Always, convert boolean to int
$value = (int)$value;
} // And continue processing because text columns with numeric info need special handling below
if ($column->meta_type == 'B')
{ // BLOBs need to be properly "packed", but can be inserted directly if so.
if (!is_null($value)) { // If value not null, unpack it to unquoted hexadecimal byte-string format
$value = unpack('H*hex', $value); // we leave it as array, so emulate_bound_params() can detect it
} // easily and "bind" the param ok.
} else if ($column->meta_type == 'X') { // sqlsrv doesn't cast from int to text, so if text column
if (is_numeric($value)) { // and is numeric value then cast to string
$value = array('numstr' => (string)$value); // and put into array, so emulate_bound_params() will know how
} // to "bind" the param ok, avoiding reverse conversion to number
} 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
}
}
return $value;
}
/**
* Selectively call sqlsrv_free_stmt(), avoiding some warnings without using the horrible @
*
* @param sqlsrv_resource $resource resource to be freed if possible
* @return bool
*/
private function free_result($resource) {
if (!is_bool($resource)) { // true/false resources cannot be freed
return sqlsrv_free_stmt($resource);
}
}
/**
* Provides mapping between sqlsrv native data types and moodle_database - database_column_info - ones)
*
* @param string $sqlsrv_type native sqlsrv data type
* @return string 1-char database_column_info data type
*/
private function sqlsrvtype2moodletype($sqlsrv_type) {
$type = null;
switch (strtoupper($sqlsrv_type)) {
case 'BIT':
$type = 'L';
break;
case 'INT':
case 'SMALLINT':
case 'INTEGER':
case 'BIGINT':
$type = 'I';
break;
case 'DECIMAL':
case 'REAL':
case 'FLOAT':
$type = 'N';
break;
case 'VARCHAR':
case 'NVARCHAR':
$type = 'C';
break;
case 'TEXT':
case 'NTEXT':
case 'VARCHAR(MAX)':
case 'NVARCHAR(MAX)':
$type = 'X';
break;
case 'IMAGE':
case 'VARBINARY(MAX)':
$type = 'B';
break;
case 'DATETIME':
$type = 'D';
break;
}
if (!$type) {
throw new dml_exception('invalidsqlsrvnativetype', $sqlsrv_type);
}
return $type;
}
/**
* Do NOT use in code, to be used by database_manager only!
* @param string $sql query
* @return bool true
* @throws dml_exception A DML specific exception is thrown for any errors.
*/
public function change_database_structure($sql) {
$this->reset_caches();
$this->query_start($sql, null, SQL_QUERY_STRUCTURE);
$result = sqlsrv_query($this->sqlsrv, $sql);
$this->query_end($result);
return true;
}
/**
* Prepare the array of params for native binding
*/
protected function build_native_bound_params(array $params = null) {
return null;
}
/**
* Workaround for SQL*Server Native driver similar to MSSQL driver for
* consistent behavior.
*/
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
$parts = explode('?', $sql);
$return = array_shift($parts);
foreach ($params as $param) {
if (is_bool($param)) {
$return .= (int)$param;
} else if (is_array($param) && isset($param['hex'])) { // detect hex binary, bind it specially
$return .= '0x'.$param['hex'];
} else if (is_array($param) && isset($param['numstr'])) { // detect numerical strings that *must not*
$return .= "N'{$param['numstr']}'"; // be converted back to number params, but bound as strings
} else if (is_null($param)) {
$return .= 'NULL';
} else if (is_number($param)) { // we can not use is_numeric() because it eats leading zeros from strings like 0045646
$return .= "'$param'"; // this is a hack for MDL-23997, we intentionally use string because it is compatible with both nvarchar and int types
} else if (is_float($param)) {
$return .= $param;
} else {
$param = str_replace("'", "''", $param);
$return .= "N'$param'";
}
$return .= array_shift($parts);
}
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 methods instead!
* @param string $sql query
* @param array $params query parameters
* @return bool true
* @throws dml_exception A DML specific exception is thrown for any errors.
*/
public function execute($sql, array $params = null) {
if (strpos($sql, ';') !== false) {
throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
}
$this->do_query($sql, $params, SQL_QUERY_UPDATE);
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 like:
* @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).
* @return moodle_recordset instance
* @throws dml_exception A DML specific exception is thrown for any errors.
*/
public function get_recordset_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
$limitfrom = (int)$limitfrom;
$limitnum = (int)$limitnum;
$limitfrom = max(0, $limitfrom);
$limitnum = max(0, $limitnum);
if ($limitfrom or $limitnum) {
if ($limitnum >= 1) { // Only apply TOP clause if we have any limitnum (limitfrom offset is handled later)
$fetch = $limitfrom + $limitnum;
if (PHP_INT_MAX - $limitnum < $limitfrom) { // Check PHP_INT_MAX overflow
$fetch = PHP_INT_MAX;
}
$sql = preg_replace('/^([\s(])*SELECT([\s]+(DISTINCT|ALL))?(?!\s*TOP\s*\()/i',
"\\1SELECT\\2 TOP $fetch", $sql);
}
}
$result = $this->do_query($sql, $params, SQL_QUERY_SELECT, false, (bool)$limitfrom);
if ($limitfrom) { // Skip $limitfrom records
sqlsrv_fetch($result, SQLSRV_SCROLL_ABSOLUTE, $limitfrom - 1);
}
return $this->create_recordset($result);
}
/**
* Create a record set and initialize with first row
*
* @param mixed $result
* @return sqlsrv_native_moodle_recordset
*/
protected function create_recordset($result) {
return new sqlsrv_native_moodle_recordset($result);
}
/**
* Get a number of records as an array of objects using a SQL statement.
*
* Return value is like:
* @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).
* @return array of objects, or empty array if no records were found
* @throws dml_exception A DML specific exception is thrown for any errors.
*/
public function get_records_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
$rs = $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
$results = array();
foreach ($rs as $row) {
$id = reset($row);
if (isset($results[$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);
}
$results[$id] = (object)$row;
}
$rs->close();
return $results;
}
/**
* 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
* @return array of values
* @throws dml_exception A DML specific exception is thrown for any errors.
*/
public function get_fieldset_sql($sql, array $params = null) {
$rs = $this->get_recordset_sql($sql, $params);
$results = array ();
foreach ($rs as $row) {
$results[] = reset($row);
}
$rs->close();
return $results;
}
/**
* 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
* @return bool|int true or new id
* @throws dml_exception A DML specific exception is thrown for any errors.
*/
public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
if (!is_array($params)) {
$params = (array)$params;
}
$isidentity = false;
if ($customsequence) {
if (!isset($params['id'])) {
throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
}
$returnid = false;
$columns = $this->get_columns($table);
if (isset($columns['id']) and $columns['id']->auto_increment) {
$isidentity = true;
}
// Disable IDENTITY column before inserting record with id, only if the
// column is identity, from meta information.
if ($isidentity) {
$sql = 'SET IDENTITY_INSERT {'.$table.'} ON'; // Yes, it' ON!!
$this->do_query($sql, null, SQL_QUERY_AUX);
}
} else {
unset($params['id']);
}
if (empty($params)) {
throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
}
$fields = implode(',', array_keys($params));
$qms = array_fill(0, count($params), '?');
$qms = implode(',', $qms);
$sql = "INSERT INTO {" . $table . "} ($fields) VALUES($qms)";
$query_id = $this->do_query($sql, $params, SQL_QUERY_INSERT);
if ($customsequence) {
// Enable IDENTITY column after inserting record with id, only if the
// column is identity, from meta information.
if ($isidentity) {
$sql = 'SET IDENTITY_INSERT {'.$table.'} OFF'; // Yes, it' OFF!!
$this->do_query($sql, null, SQL_QUERY_AUX);
}
}
if ($returnid) {
$id = $this->sqlsrv_fetch_id();
return $id;
} else {
return true;
}
}
/**
* Get the ID of the current action
*
* @return mixed ID
*/
private function sqlsrv_fetch_id() {
$query_id = sqlsrv_query($this->sqlsrv, 'SELECT SCOPE_IDENTITY()');
if ($query_id === false) {
$dberr = $this->get_last_error();
return false;
}
$row = $this->sqlsrv_fetchrow($query_id);
return (int)$row[0];
}
/**
* Fetch a single row into an numbered array
*
* @param mixed $query_id
*/
private function sqlsrv_fetchrow($query_id) {
$row = sqlsrv_fetch_array($query_id, SQLSRV_FETCH_NUMERIC);
if ($row === false) {
$dberr = $this->get_last_error();
return false;
}
foreach ($row as $key => $value) {
$row[$key] = ($value === ' ' || $value === NULL) ? '' : $value;
}
return $row;
}
/**
* 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.
* @return bool|int true or new id
* @throws dml_exception A DML specific exception is thrown for any errors.
*/
public function insert_record($table, $dataobject, $returnid = true, $bulk = false) {
$dataobject = (array)$dataobject;
$columns = $this->get_columns($table);
$cleaned = array ();
foreach ($dataobject as $field => $value) {
if ($field === 'id') {
continue;
}
if (!isset($columns[$field])) {
continue;
}
$column = $columns[$field];
$cleaned[$field] = $this->normalise_value($column, $value);
}
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
* @return bool true
* @throws dml_exception A DML specific exception is thrown for any errors.
*/
public function import_record($table, $dataobject) {
if (!is_object($dataobject)) {
$dataobject = (object)$dataobject;
}
$columns = $this->get_columns($table);
$cleaned = array ();
foreach ($dataobject as $field => $value) {
if (!isset($columns[$field])) {