summaryrefslogtreecommitdiff
path: root/includes/db/DatabaseOracle.php
blob: f031f78012d4ebdb97c3a18b47a1b445fc0918c3 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
<?php
/**
 * This is the Oracle database abstraction layer.
 *
 * This program 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.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Database
 */

/**
 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
 * other things. We use a wrapper class to handle that and other
 * Oracle-specific bits, like converting column names back to lowercase.
 * @ingroup Database
 */
class ORAResult {
	private $rows;
	private $cursor;
	private $nrows;

	private $columns = array();

	private function array_unique_md( $array_in ) {
		$array_out = array();
		$array_hashes = array();

		foreach ( $array_in as $item ) {
			$hash = md5( serialize( $item ) );
			if ( !isset( $array_hashes[$hash] ) ) {
				$array_hashes[$hash] = $hash;
				$array_out[] = $item;
			}
		}

		return $array_out;
	}

	/**
	 * @param DatabaseBase $db
	 * @param resource $stmt A valid OCI statement identifier
	 * @param bool $unique
	 */
	function __construct( &$db, $stmt, $unique = false ) {
		$this->db =& $db;

		$this->nrows = oci_fetch_all( $stmt, $this->rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM );
		if ( $this->nrows === false ) {
			$e = oci_error( $stmt );
			$db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
			$this->free();

			return;
		}

		if ( $unique ) {
			$this->rows = $this->array_unique_md( $this->rows );
			$this->nrows = count( $this->rows );
		}

		if ( $this->nrows > 0 ) {
			foreach ( $this->rows[0] as $k => $v ) {
				$this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
			}
		}

		$this->cursor = 0;
		oci_free_statement( $stmt );
	}

	public function free() {
		unset( $this->db );
	}

	public function seek( $row ) {
		$this->cursor = min( $row, $this->nrows );
	}

	public function numRows() {
		return $this->nrows;
	}

	public function numFields() {
		return count( $this->columns );
	}

	public function fetchObject() {
		if ( $this->cursor >= $this->nrows ) {
			return false;
		}
		$row = $this->rows[$this->cursor++];
		$ret = new stdClass();
		foreach ( $row as $k => $v ) {
			$lc = $this->columns[$k];
			$ret->$lc = $v;
		}

		return $ret;
	}

	public function fetchRow() {
		if ( $this->cursor >= $this->nrows ) {
			return false;
		}

		$row = $this->rows[$this->cursor++];
		$ret = array();
		foreach ( $row as $k => $v ) {
			$lc = $this->columns[$k];
			$ret[$lc] = $v;
			$ret[$k] = $v;
		}

		return $ret;
	}
}

/**
 * Utility class.
 * @ingroup Database
 */
class ORAField implements Field {
	private $name, $tablename, $default, $max_length, $nullable,
		$is_pk, $is_unique, $is_multiple, $is_key, $type;

	function __construct( $info ) {
		$this->name = $info['column_name'];
		$this->tablename = $info['table_name'];
		$this->default = $info['data_default'];
		$this->max_length = $info['data_length'];
		$this->nullable = $info['not_null'];
		$this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
		$this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
		$this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
		$this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
		$this->type = $info['data_type'];
	}

	function name() {
		return $this->name;
	}

	function tableName() {
		return $this->tablename;
	}

	function defaultValue() {
		return $this->default;
	}

	function maxLength() {
		return $this->max_length;
	}

	function isNullable() {
		return $this->nullable;
	}

	function isKey() {
		return $this->is_key;
	}

	function isMultipleKey() {
		return $this->is_multiple;
	}

	function type() {
		return $this->type;
	}
}

/**
 * @ingroup Database
 */
class DatabaseOracle extends DatabaseBase {
	/** @var resource */
	protected $mLastResult = null;

	/** @var int The number of rows affected as an integer */
	protected $mAffectedRows;

	/** @var int */
	private $mInsertId = null;

	/** @var bool */
	private $ignoreDupValOnIndex = false;

	/** @var bool|array */
	private $sequenceData = null;

	/** @var string Character set for Oracle database */
	private $defaultCharset = 'AL32UTF8';

	/** @var array */
	private $mFieldInfoCache = array();

	function __construct( $p = null ) {
		global $wgDBprefix;

		if ( !is_array( $p ) ) { // legacy calling pattern
			wfDeprecated( __METHOD__ . " method called without parameter array.", "1.22" );
			$args = func_get_args();
			$p = array(
				'host' => isset( $args[0] ) ? $args[0] : false,
				'user' => isset( $args[1] ) ? $args[1] : false,
				'password' => isset( $args[2] ) ? $args[2] : false,
				'dbname' => isset( $args[3] ) ? $args[3] : false,
				'flags' => isset( $args[4] ) ? $args[4] : 0,
				'tablePrefix' => isset( $args[5] ) ? $args[5] : 'get from global',
				'schema' => 'get from global',
				'foreign' => isset( $args[6] ) ? $args[6] : false
			);
		}
		if ( $p['tablePrefix'] == 'get from global' ) {
			$p['tablePrefix'] = $wgDBprefix;
		}
		$p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
		parent::__construct( $p );
		wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
	}

	function __destruct() {
		if ( $this->mOpened ) {
			wfSuppressWarnings();
			$this->close();
			wfRestoreWarnings();
		}
	}

	function getType() {
		return 'oracle';
	}

	function cascadingDeletes() {
		return true;
	}

	function cleanupTriggers() {
		return true;
	}

	function strictIPs() {
		return true;
	}

	function realTimestamps() {
		return true;
	}

	function implicitGroupby() {
		return false;
	}

	function implicitOrderby() {
		return false;
	}

	function searchableIPs() {
		return true;
	}

	/**
	 * Usually aborts on failure
	 * @param string $server
	 * @param string $user
	 * @param string $password
	 * @param string $dbName
	 * @throws DBConnectionError
	 * @return DatabaseBase|null
	 */
	function open( $server, $user, $password, $dbName ) {
		global $wgDBOracleDRCP;
		if ( !function_exists( 'oci_connect' ) ) {
			throw new DBConnectionError(
				$this,
				"Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
					"(Note: if you recently installed PHP, you may need to restart your webserver\n " .
					"and database)\n" );
		}

		$this->close();
		$this->mUser = $user;
		$this->mPassword = $password;
		// changed internal variables functions
		// mServer now holds the TNS endpoint
		// mDBname is schema name if different from username
		if ( !$server ) {
			// backward compatibillity (server used to be null and TNS was supplied in dbname)
			$this->mServer = $dbName;
			$this->mDBname = $user;
		} else {
			$this->mServer = $server;
			if ( !$dbName ) {
				$this->mDBname = $user;
			} else {
				$this->mDBname = $dbName;
			}
		}

		if ( !strlen( $user ) ) { # e.g. the class is being loaded
			return null;
		}

		if ( $wgDBOracleDRCP ) {
			$this->setFlag( DBO_PERSISTENT );
		}

		$session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;

		wfSuppressWarnings();
		if ( $this->mFlags & DBO_PERSISTENT ) {
			$this->mConn = oci_pconnect(
				$this->mUser,
				$this->mPassword,
				$this->mServer,
				$this->defaultCharset,
				$session_mode
			);
		} elseif ( $this->mFlags & DBO_DEFAULT ) {
			$this->mConn = oci_new_connect(
				$this->mUser,
				$this->mPassword,
				$this->mServer,
				$this->defaultCharset,
				$session_mode
			);
		} else {
			$this->mConn = oci_connect(
				$this->mUser,
				$this->mPassword,
				$this->mServer,
				$this->defaultCharset,
				$session_mode
			);
		}
		wfRestoreWarnings();

		if ( $this->mUser != $this->mDBname ) {
			//change current schema in session
			$this->selectDB( $this->mDBname );
		}

		if ( !$this->mConn ) {
			throw new DBConnectionError( $this, $this->lastError() );
		}

		$this->mOpened = true;

		# removed putenv calls because they interfere with the system globaly
		$this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
		$this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
		$this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );

		return $this->mConn;
	}

	/**
	 * Closes a database connection, if it is open
	 * Returns success, true if already closed
	 * @return bool
	 */
	protected function closeConnection() {
		return oci_close( $this->mConn );
	}

	function execFlags() {
		return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
	}

	protected function doQuery( $sql ) {
		wfDebug( "SQL: [$sql]\n" );
		if ( !StringUtils::isUtf8( $sql ) ) {
			throw new MWException( "SQL encoding is invalid\n$sql" );
		}

		// handle some oracle specifics
		// remove AS column/table/subquery namings
		if ( !$this->getFlag( DBO_DDLMODE ) ) {
			$sql = preg_replace( '/ as /i', ' ', $sql );
		}

		// Oracle has issues with UNION clause if the statement includes LOB fields
		// So we do a UNION ALL and then filter the results array with array_unique
		$union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
		// EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
		// you have to select data from plan table after explain
		$explain_id = MWTimestamp::getLocalInstance()->format( 'dmYHis' );

		$sql = preg_replace(
			'/^EXPLAIN /',
			'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
			$sql,
			1,
			$explain_count
		);

		wfSuppressWarnings();

		if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
			$e = oci_error( $this->mConn );
			$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );

			return false;
		}

		if ( !oci_execute( $stmt, $this->execFlags() ) ) {
			$e = oci_error( $stmt );
			if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
				$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );

				return false;
			}
		}

		wfRestoreWarnings();

		if ( $explain_count > 0 ) {
			return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
				'WHERE statement_id = \'' . $explain_id . '\'' );
		} elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
			return new ORAResult( $this, $stmt, $union_unique );
		} else {
			$this->mAffectedRows = oci_num_rows( $stmt );

			return true;
		}
	}

	function queryIgnore( $sql, $fname = '' ) {
		return $this->query( $sql, $fname, true );
	}

	/**
	 * Frees resources associated with the LOB descriptor
	 * @param ResultWrapper|resource $res
	 */
	function freeResult( $res ) {
		if ( $res instanceof ResultWrapper ) {
			$res = $res->result;
		}

		$res->free();
	}

	/**
	 * @param ResultWrapper|stdClass $res
	 * @return mixed
	 */
	function fetchObject( $res ) {
		if ( $res instanceof ResultWrapper ) {
			$res = $res->result;
		}

		return $res->fetchObject();
	}

	function fetchRow( $res ) {
		if ( $res instanceof ResultWrapper ) {
			$res = $res->result;
		}

		return $res->fetchRow();
	}

	function numRows( $res ) {
		if ( $res instanceof ResultWrapper ) {
			$res = $res->result;
		}

		return $res->numRows();
	}

	function numFields( $res ) {
		if ( $res instanceof ResultWrapper ) {
			$res = $res->result;
		}

		return $res->numFields();
	}

	function fieldName( $stmt, $n ) {
		return oci_field_name( $stmt, $n );
	}

	/**
	 * This must be called after nextSequenceVal
	 * @return null|int
	 */
	function insertId() {
		return $this->mInsertId;
	}

	/**
	 * @param mixed $res
	 * @param int $row
	 */
	function dataSeek( $res, $row ) {
		if ( $res instanceof ORAResult ) {
			$res->seek( $row );
		} else {
			$res->result->seek( $row );
		}
	}

	function lastError() {
		if ( $this->mConn === false ) {
			$e = oci_error();
		} else {
			$e = oci_error( $this->mConn );
		}

		return $e['message'];
	}

	function lastErrno() {
		if ( $this->mConn === false ) {
			$e = oci_error();
		} else {
			$e = oci_error( $this->mConn );
		}

		return $e['code'];
	}

	function affectedRows() {
		return $this->mAffectedRows;
	}

	/**
	 * Returns information about an index
	 * If errors are explicitly ignored, returns NULL on failure
	 * @param string $table
	 * @param string $index
	 * @param string $fname
	 * @return bool
	 */
	function indexInfo( $table, $index, $fname = __METHOD__ ) {
		return false;
	}

	function indexUnique( $table, $index, $fname = __METHOD__ ) {
		return false;
	}

	function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
		if ( !count( $a ) ) {
			return true;
		}

		if ( !is_array( $options ) ) {
			$options = array( $options );
		}

		if ( in_array( 'IGNORE', $options ) ) {
			$this->ignoreDupValOnIndex = true;
		}

		if ( !is_array( reset( $a ) ) ) {
			$a = array( $a );
		}

		foreach ( $a as &$row ) {
			$this->insertOneRow( $table, $row, $fname );
		}
		$retVal = true;

		if ( in_array( 'IGNORE', $options ) ) {
			$this->ignoreDupValOnIndex = false;
		}

		return $retVal;
	}

	private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
		$col_info = $this->fieldInfoMulti( $table, $col );
		$col_type = $col_info != false ? $col_info->type() : 'CONSTANT';

		$bind = '';
		if ( is_numeric( $col ) ) {
			$bind = $val;
			$val = null;

			return $bind;
		} elseif ( $includeCol ) {
			$bind = "$col = ";
		}

		if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
			$val = null;
		}

		if ( $val === 'NULL' ) {
			$val = null;
		}

		if ( $val === null ) {
			if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
				$bind .= 'DEFAULT';
			} else {
				$bind .= 'NULL';
			}
		} else {
			$bind .= ':' . $col;
		}

		return $bind;
	}

	/**
	 * @param string $table
	 * @param array $row
	 * @param string $fname
	 * @return bool
	 * @throws DBUnexpectedError
	 */
	private function insertOneRow( $table, $row, $fname ) {
		global $wgContLang;

		$table = $this->tableName( $table );
		// "INSERT INTO tables (a, b, c)"
		$sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
		$sql .= " VALUES (";

		// for each value, append ":key"
		$first = true;
		foreach ( $row as $col => &$val ) {
			if ( !$first ) {
				$sql .= ', ';
			} else {
				$first = false;
			}
			if ( $this->isQuotedIdentifier( $val ) ) {
				$sql .= $this->removeIdentifierQuotes( $val );
				unset( $row[$col] );
			} else {
				$sql .= $this->fieldBindStatement( $table, $col, $val );
			}
		}
		$sql .= ')';

		if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
			$e = oci_error( $this->mConn );
			$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );

			return false;
		}
		foreach ( $row as $col => &$val ) {
			$col_info = $this->fieldInfoMulti( $table, $col );
			$col_type = $col_info != false ? $col_info->type() : 'CONSTANT';

			if ( $val === null ) {
				// do nothing ... null was inserted in statement creation
			} elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
				if ( is_object( $val ) ) {
					$val = $val->fetch();
				}

				// backward compatibility
				if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
					$val = $this->getInfinity();
				}

				$val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
				if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
					$e = oci_error( $stmt );
					$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );

					return false;
				}
			} else {
				/** @var OCI_Lob[] $lob */
				if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
					$e = oci_error( $stmt );
					throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
				}

				if ( is_object( $val ) ) {
					$val = $val->fetch();
				}

				if ( $col_type == 'BLOB' ) {
					$lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
					oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB );
				} else {
					$lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
					oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
				}
			}
		}

		wfSuppressWarnings();

		if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
			$e = oci_error( $stmt );
			if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
				$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );

				return false;
			} else {
				$this->mAffectedRows = oci_num_rows( $stmt );
			}
		} else {
			$this->mAffectedRows = oci_num_rows( $stmt );
		}

		wfRestoreWarnings();

		if ( isset( $lob ) ) {
			foreach ( $lob as $lob_v ) {
				$lob_v->free();
			}
		}

		if ( !$this->mTrxLevel ) {
			oci_commit( $this->mConn );
		}

		return oci_free_statement( $stmt );
	}

	function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
		$insertOptions = array(), $selectOptions = array()
	) {
		$destTable = $this->tableName( $destTable );
		if ( !is_array( $selectOptions ) ) {
			$selectOptions = array( $selectOptions );
		}
		list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
		if ( is_array( $srcTable ) ) {
			$srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
		} else {
			$srcTable = $this->tableName( $srcTable );
		}

		if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
			!isset( $varMap[$sequenceData['column']] )
		) {
			$varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
		}

		// count-alias subselect fields to avoid abigious definition errors
		$i = 0;
		foreach ( $varMap as &$val ) {
			$val = $val . ' field' . ( $i++ );
		}

		$sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
			" SELECT $startOpts " . implode( ',', $varMap ) .
			" FROM $srcTable $useIndex ";
		if ( $conds != '*' ) {
			$sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
		}
		$sql .= " $tailOpts";

		if ( in_array( 'IGNORE', $insertOptions ) ) {
			$this->ignoreDupValOnIndex = true;
		}

		$retval = $this->query( $sql, $fname );

		if ( in_array( 'IGNORE', $insertOptions ) ) {
			$this->ignoreDupValOnIndex = false;
		}

		return $retval;
	}

	public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
		$fname = __METHOD__
	) {
		if ( !count( $rows ) ) {
			return true; // nothing to do
		}

		if ( !is_array( reset( $rows ) ) ) {
			$rows = array( $rows );
		}

		$sequenceData = $this->getSequenceData( $table );
		if ( $sequenceData !== false ) {
			// add sequence column to each list of columns, when not set
			foreach ( $rows as &$row ) {
				if ( !isset( $row[$sequenceData['column']] ) ) {
					$row[$sequenceData['column']] =
						$this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
							$sequenceData['sequence'] . '\')' );
				}
			}
		}

		return parent::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
	}

	function tableName( $name, $format = 'quoted' ) {
		/*
		Replace reserved words with better ones
		Using uppercase because that's the only way Oracle can handle
		quoted tablenames
		*/
		switch ( $name ) {
			case 'user':
				$name = 'MWUSER';
				break;
			case 'text':
				$name = 'PAGECONTENT';
				break;
		}

		return strtoupper( parent::tableName( $name, $format ) );
	}

	function tableNameInternal( $name ) {
		$name = $this->tableName( $name );

		return preg_replace( '/.*\.(.*)/', '$1', $name );
	}

	/**
	 * Return the next in a sequence, save the value for retrieval via insertId()
	 *
	 * @param string $seqName
	 * @return null|int
	 */
	function nextSequenceValue( $seqName ) {
		$res = $this->query( "SELECT $seqName.nextval FROM dual" );
		$row = $this->fetchRow( $res );
		$this->mInsertId = $row[0];

		return $this->mInsertId;
	}

	/**
	 * Return sequence_name if table has a sequence
	 *
	 * @param string $table
	 * @return bool
	 */
	private function getSequenceData( $table ) {
		if ( $this->sequenceData == null ) {
			$result = $this->doQuery( "SELECT lower(asq.sequence_name),
				lower(atc.table_name),
				lower(atc.column_name)
			FROM all_sequences asq, all_tab_columns atc
			WHERE decode(
					atc.table_name,
					'{$this->mTablePrefix}MWUSER',
					'{$this->mTablePrefix}USER',
					atc.table_name
				) || '_' ||
				atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
				AND asq.sequence_owner = upper('{$this->mDBname}')
				AND atc.owner = upper('{$this->mDBname}')" );

			while ( ( $row = $result->fetchRow() ) !== false ) {
				$this->sequenceData[$row[1]] = array(
					'sequence' => $row[0],
					'column' => $row[2]
				);
			}
		}
		$table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );

		return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
	}

	/**
	 * Returns the size of a text field, or -1 for "unlimited"
	 *
	 * @param string $table
	 * @param string $field
	 * @return mixed
	 */
	function textFieldSize( $table, $field ) {
		$fieldInfoData = $this->fieldInfo( $table, $field );

		return $fieldInfoData->maxLength();
	}

	function limitResult( $sql, $limit, $offset = false ) {
		if ( $offset === false ) {
			$offset = 0;
		}

		return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
	}

	function encodeBlob( $b ) {
		return new Blob( $b );
	}

	function decodeBlob( $b ) {
		if ( $b instanceof Blob ) {
			$b = $b->fetch();
		}

		return $b;
	}

	function unionQueries( $sqls, $all ) {
		$glue = ' UNION ALL ';

		return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) .
			'FROM (' . implode( $glue, $sqls ) . ')';
	}

	function wasDeadlock() {
		return $this->lastErrno() == 'OCI-00060';
	}

	function duplicateTableStructure( $oldName, $newName, $temporary = false,
		$fname = __METHOD__
	) {
		$temporary = $temporary ? 'TRUE' : 'FALSE';

		$newName = strtoupper( $newName );
		$oldName = strtoupper( $oldName );

		$tabName = substr( $newName, strlen( $this->mTablePrefix ) );
		$oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
		$newPrefix = strtoupper( $this->mTablePrefix );

		return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
			"'$oldPrefix', '$newPrefix', $temporary ); END;" );
	}

	function listTables( $prefix = null, $fname = __METHOD__ ) {
		$listWhere = '';
		if ( !empty( $prefix ) ) {
			$listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
		}

		$owner = strtoupper( $this->mDBname );
		$result = $this->doQuery( "SELECT table_name FROM all_tables " .
			"WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );

		// dirty code ... i know
		$endArray = array();
		$endArray[] = strtoupper( $prefix . 'MWUSER' );
		$endArray[] = strtoupper( $prefix . 'PAGE' );
		$endArray[] = strtoupper( $prefix . 'IMAGE' );
		$fixedOrderTabs = $endArray;
		while ( ( $row = $result->fetchRow() ) !== false ) {
			if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
				$endArray[] = $row['table_name'];
			}
		}

		return $endArray;
	}

	public function dropTable( $tableName, $fName = __METHOD__ ) {
		$tableName = $this->tableName( $tableName );
		if ( !$this->tableExists( $tableName ) ) {
			return false;
		}

		return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
	}

	function timestamp( $ts = 0 ) {
		return wfTimestamp( TS_ORACLE, $ts );
	}

	/**
	 * Return aggregated value function call
	 *
	 * @param array $valuedata
	 * @param string $valuename
	 * @return mixed
	 */
	public function aggregateValue( $valuedata, $valuename = 'value' ) {
		return $valuedata;
	}

	function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
		# Ignore errors during error handling to avoid infinite
		# recursion
		$ignore = $this->ignoreErrors( true );
		++$this->mErrorCount;

		if ( $ignore || $tempIgnore ) {
			wfDebug( "SQL ERROR (ignored): $error\n" );
			$this->ignoreErrors( $ignore );
		} else {
			throw new DBQueryError( $this, $error, $errno, $sql, $fname );
		}
	}

	/**
	 * @return string Wikitext of a link to the server software's web site
	 */
	public function getSoftwareLink() {
		return '[{{int:version-db-oracle-url}} Oracle]';
	}

	/**
	 * @return string Version information from the database
	 */
	function getServerVersion() {
		//better version number, fallback on driver
		$rset = $this->doQuery(
			'SELECT version FROM product_component_version ' .
				'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
		);
		if ( !( $row = $rset->fetchRow() ) ) {
			return oci_server_version( $this->mConn );
		}

		return $row['version'];
	}

	/**
	 * Query whether a given index exists
	 * @param string $table
	 * @param string $index
	 * @param string $fname
	 * @return bool
	 */
	function indexExists( $table, $index, $fname = __METHOD__ ) {
		$table = $this->tableName( $table );
		$table = strtoupper( $this->removeIdentifierQuotes( $table ) );
		$index = strtoupper( $index );
		$owner = strtoupper( $this->mDBname );
		$sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
		$res = $this->doQuery( $sql );
		if ( $res ) {
			$count = $res->numRows();
			$res->free();
		} else {
			$count = 0;
		}

		return $count != 0;
	}

	/**
	 * Query whether a given table exists (in the given schema, or the default mw one if not given)
	 * @param string $table
	 * @param string $fname
	 * @return bool
	 */
	function tableExists( $table, $fname = __METHOD__ ) {
		$table = $this->tableName( $table );
		$table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
		$owner = $this->addQuotes( strtoupper( $this->mDBname ) );
		$sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
		$res = $this->doQuery( $sql );
		if ( $res && $res->numRows() > 0 ) {
			$exists = true;
		} else {
			$exists = false;
		}

		$res->free();

		return $exists;
	}

	/**
	 * Function translates mysql_fetch_field() functionality on ORACLE.
	 * Caching is present for reducing query time.
	 * For internal calls. Use fieldInfo for normal usage.
	 * Returns false if the field doesn't exist
	 *
	 * @param array|string $table
	 * @param string $field
	 * @return ORAField|ORAResult
	 */
	private function fieldInfoMulti( $table, $field ) {
		$field = strtoupper( $field );
		if ( is_array( $table ) ) {
			$table = array_map( array( &$this, 'tableNameInternal' ), $table );
			$tableWhere = 'IN (';
			foreach ( $table as &$singleTable ) {
				$singleTable = $this->removeIdentifierQuotes( $singleTable );
				if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
					return $this->mFieldInfoCache["$singleTable.$field"];
				}
				$tableWhere .= '\'' . $singleTable . '\',';
			}
			$tableWhere = rtrim( $tableWhere, ',' ) . ')';
		} else {
			$table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
			if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
				return $this->mFieldInfoCache["$table.$field"];
			}
			$tableWhere = '= \'' . $table . '\'';
		}

		$fieldInfoStmt = oci_parse(
			$this->mConn,
			'SELECT * FROM wiki_field_info_full WHERE table_name ' .
				$tableWhere . ' and column_name = \'' . $field . '\''
		);
		if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
			$e = oci_error( $fieldInfoStmt );
			$this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );

			return false;
		}
		$res = new ORAResult( $this, $fieldInfoStmt );
		if ( $res->numRows() == 0 ) {
			if ( is_array( $table ) ) {
				foreach ( $table as &$singleTable ) {
					$this->mFieldInfoCache["$singleTable.$field"] = false;
				}
			} else {
				$this->mFieldInfoCache["$table.$field"] = false;
			}
			$fieldInfoTemp = null;
		} else {
			$fieldInfoTemp = new ORAField( $res->fetchRow() );
			$table = $fieldInfoTemp->tableName();
			$this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
		}
		$res->free();

		return $fieldInfoTemp;
	}

	/**
	 * @throws DBUnexpectedError
	 * @param string $table
	 * @param string $field
	 * @return ORAField
	 */
	function fieldInfo( $table, $field ) {
		if ( is_array( $table ) ) {
			throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
		}

		return $this->fieldInfoMulti( $table, $field );
	}

	protected function doBegin( $fname = __METHOD__ ) {
		$this->mTrxLevel = 1;
		$this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
	}

	protected function doCommit( $fname = __METHOD__ ) {
		if ( $this->mTrxLevel ) {
			$ret = oci_commit( $this->mConn );
			if ( !$ret ) {
				throw new DBUnexpectedError( $this, $this->lastError() );
			}
			$this->mTrxLevel = 0;
			$this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
		}
	}

	protected function doRollback( $fname = __METHOD__ ) {
		if ( $this->mTrxLevel ) {
			oci_rollback( $this->mConn );
			$this->mTrxLevel = 0;
			$this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
		}
	}

	/**
	 * defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
	 *
	 * @param resource $fp
	 * @param bool|string $lineCallback
	 * @param bool|callable $resultCallback
	 * @param string $fname
	 * @param bool|callable $inputCallback
	 * @return bool|string
	 */
	function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
		$fname = __METHOD__, $inputCallback = false ) {
		$cmd = '';
		$done = false;
		$dollarquote = false;

		$replacements = array();

		while ( !feof( $fp ) ) {
			if ( $lineCallback ) {
				call_user_func( $lineCallback );
			}
			$line = trim( fgets( $fp, 1024 ) );
			$sl = strlen( $line ) - 1;

			if ( $sl < 0 ) {
				continue;
			}
			if ( '-' == $line[0] && '-' == $line[1] ) {
				continue;
			}

			// Allow dollar quoting for function declarations
			if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
				if ( $dollarquote ) {
					$dollarquote = false;
					$line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
					$done = true;
				} else {
					$dollarquote = true;
				}
			} elseif ( !$dollarquote ) {
				if ( ';' == $line[$sl] && ( $sl < 2 || ';' != $line[$sl - 1] ) ) {
					$done = true;
					$line = substr( $line, 0, $sl );
				}
			}

			if ( $cmd != '' ) {
				$cmd .= ' ';
			}
			$cmd .= "$line\n";

			if ( $done ) {
				$cmd = str_replace( ';;', ";", $cmd );
				if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
					if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
						$replacements[$defines[2]] = $defines[1];
					}
				} else {
					foreach ( $replacements as $mwVar => $scVar ) {
						$cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
					}

					$cmd = $this->replaceVars( $cmd );
					if ( $inputCallback ) {
						call_user_func( $inputCallback, $cmd );
					}
					$res = $this->doQuery( $cmd );
					if ( $resultCallback ) {
						call_user_func( $resultCallback, $res, $this );
					}

					if ( false === $res ) {
						$err = $this->lastError();

						return "Query \"{$cmd}\" failed with error code \"$err\".\n";
					}
				}

				$cmd = '';
				$done = false;
			}
		}

		return true;
	}

	function selectDB( $db ) {
		$this->mDBname = $db;
		if ( $db == null || $db == $this->mUser ) {
			return true;
		}
		$sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
		$stmt = oci_parse( $this->mConn, $sql );
		wfSuppressWarnings();
		$success = oci_execute( $stmt );
		wfRestoreWarnings();
		if ( !$success ) {
			$e = oci_error( $stmt );
			if ( $e['code'] != '1435' ) {
				$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
			}

			return false;
		}

		return true;
	}

	function strencode( $s ) {
		return str_replace( "'", "''", $s );
	}

	function addQuotes( $s ) {
		global $wgContLang;
		if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
			$s = $wgContLang->checkTitleEncoding( $s );
		}

		return "'" . $this->strencode( $s ) . "'";
	}

	public function addIdentifierQuotes( $s ) {
		if ( !$this->getFlag( DBO_DDLMODE ) ) {
			$s = '/*Q*/' . $s;
		}

		return $s;
	}

	public function removeIdentifierQuotes( $s ) {
		return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
	}

	public function isQuotedIdentifier( $s ) {
		return strpos( $s, '/*Q*/' ) !== false;
	}

	private function wrapFieldForWhere( $table, &$col, &$val ) {
		global $wgContLang;

		$col_info = $this->fieldInfoMulti( $table, $col );
		$col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
		if ( $col_type == 'CLOB' ) {
			$col = 'TO_CHAR(' . $col . ')';
			$val = $wgContLang->checkTitleEncoding( $val );
		} elseif ( $col_type == 'VARCHAR2' ) {
			$val = $wgContLang->checkTitleEncoding( $val );
		}
	}

	private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
		$conds2 = array();
		foreach ( $conds as $col => $val ) {
			if ( is_array( $val ) ) {
				$conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
			} else {
				if ( is_numeric( $col ) && $parentCol != null ) {
					$this->wrapFieldForWhere( $table, $parentCol, $val );
				} else {
					$this->wrapFieldForWhere( $table, $col, $val );
				}
				$conds2[$col] = $val;
			}
		}

		return $conds2;
	}

	function selectRow( $table, $vars, $conds, $fname = __METHOD__,
		$options = array(), $join_conds = array()
	) {
		if ( is_array( $conds ) ) {
			$conds = $this->wrapConditionsForWhere( $table, $conds );
		}

		return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
	}

	/**
	 * Returns an optional USE INDEX clause to go after the table, and a
	 * string to go at the end of the query
	 *
	 * @param array $options An associative array of options to be turned into
	 *   an SQL query, valid keys are listed in the function.
	 * @return array
	 */
	function makeSelectOptions( $options ) {
		$preLimitTail = $postLimitTail = '';
		$startOpts = '';

		$noKeyOptions = array();
		foreach ( $options as $key => $option ) {
			if ( is_numeric( $key ) ) {
				$noKeyOptions[$option] = true;
			}
		}

		$preLimitTail .= $this->makeGroupByWithHaving( $options );

		$preLimitTail .= $this->makeOrderBy( $options );

		if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
			$postLimitTail .= ' FOR UPDATE';
		}

		if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
			$startOpts .= 'DISTINCT';
		}

		if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
			$useIndex = $this->useIndexClause( $options['USE INDEX'] );
		} else {
			$useIndex = '';
		}

		return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
	}

	public function delete( $table, $conds, $fname = __METHOD__ ) {
		if ( is_array( $conds ) ) {
			$conds = $this->wrapConditionsForWhere( $table, $conds );
		}
		// a hack for deleting pages, users and images (which have non-nullable FKs)
		// all deletions on these tables have transactions so final failure rollbacks these updates
		$table = $this->tableName( $table );
		if ( $table == $this->tableName( 'user' ) ) {
			$this->update( 'archive', array( 'ar_user' => 0 ),
				array( 'ar_user' => $conds['user_id'] ), $fname );
			$this->update( 'ipblocks', array( 'ipb_user' => 0 ),
				array( 'ipb_user' => $conds['user_id'] ), $fname );
			$this->update( 'image', array( 'img_user' => 0 ),
				array( 'img_user' => $conds['user_id'] ), $fname );
			$this->update( 'oldimage', array( 'oi_user' => 0 ),
				array( 'oi_user' => $conds['user_id'] ), $fname );
			$this->update( 'filearchive', array( 'fa_deleted_user' => 0 ),
				array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
			$this->update( 'filearchive', array( 'fa_user' => 0 ),
				array( 'fa_user' => $conds['user_id'] ), $fname );
			$this->update( 'uploadstash', array( 'us_user' => 0 ),
				array( 'us_user' => $conds['user_id'] ), $fname );
			$this->update( 'recentchanges', array( 'rc_user' => 0 ),
				array( 'rc_user' => $conds['user_id'] ), $fname );
			$this->update( 'logging', array( 'log_user' => 0 ),
				array( 'log_user' => $conds['user_id'] ), $fname );
		} elseif ( $table == $this->tableName( 'image' ) ) {
			$this->update( 'oldimage', array( 'oi_name' => 0 ),
				array( 'oi_name' => $conds['img_name'] ), $fname );
		}

		return parent::delete( $table, $conds, $fname );
	}

	/**
	 * @param string $table
	 * @param array $values
	 * @param array $conds
	 * @param string $fname
	 * @param array $options
	 * @return bool
	 * @throws DBUnexpectedError
	 */
	function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
		global $wgContLang;

		$table = $this->tableName( $table );
		$opts = $this->makeUpdateOptions( $options );
		$sql = "UPDATE $opts $table SET ";

		$first = true;
		foreach ( $values as $col => &$val ) {
			$sqlSet = $this->fieldBindStatement( $table, $col, $val, true );

			if ( !$first ) {
				$sqlSet = ', ' . $sqlSet;
			} else {
				$first = false;
			}
			$sql .= $sqlSet;
		}

		if ( $conds !== array() && $conds !== '*' ) {
			$conds = $this->wrapConditionsForWhere( $table, $conds );
			$sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
		}

		if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
			$e = oci_error( $this->mConn );
			$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );

			return false;
		}
		foreach ( $values as $col => &$val ) {
			$col_info = $this->fieldInfoMulti( $table, $col );
			$col_type = $col_info != false ? $col_info->type() : 'CONSTANT';

			if ( $val === null ) {
				// do nothing ... null was inserted in statement creation
			} elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
				if ( is_object( $val ) ) {
					$val = $val->getData();
				}

				if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
					$val = '31-12-2030 12:00:00.000000';
				}

				$val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
				if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
					$e = oci_error( $stmt );
					$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );

					return false;
				}
			} else {
				/** @var OCI_Lob[] $lob */
				if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
					$e = oci_error( $stmt );
					throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
				}

				if ( is_object( $val ) ) {
					$val = $val->getData();
				}

				if ( $col_type == 'BLOB' ) {
					$lob[$col]->writeTemporary( $val );
					oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB );
				} else {
					$lob[$col]->writeTemporary( $val );
					oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
				}
			}
		}

		wfSuppressWarnings();

		if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
			$e = oci_error( $stmt );
			if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
				$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );

				return false;
			} else {
				$this->mAffectedRows = oci_num_rows( $stmt );
			}
		} else {
			$this->mAffectedRows = oci_num_rows( $stmt );
		}

		wfRestoreWarnings();

		if ( isset( $lob ) ) {
			foreach ( $lob as $lob_v ) {
				$lob_v->free();
			}
		}

		if ( !$this->mTrxLevel ) {
			oci_commit( $this->mConn );
		}

		return oci_free_statement( $stmt );
	}

	function bitNot( $field ) {
		// expecting bit-fields smaller than 4bytes
		return 'BITNOT(' . $field . ')';
	}

	function bitAnd( $fieldLeft, $fieldRight ) {
		return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
	}

	function bitOr( $fieldLeft, $fieldRight ) {
		return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
	}

	function getDBname() {
		return $this->mDBname;
	}

	function getServer() {
		return $this->mServer;
	}

	public function buildGroupConcatField(
		$delim, $table, $field, $conds = '', $join_conds = array()
	) {
		$fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";

		return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
	}

	public function getSearchEngine() {
		return 'SearchOracle';
	}

	public function getInfinity() {
		return '31-12-2030 12:00:00.000000';
	}
}