Subversion-Projekte lars-tiefland.ci

Revision

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

Revision Autor Zeilennr. Zeile
68 lars 1
<?php
2
/**
3
 * CodeIgniter
4
 *
5
 * An open source application development framework for PHP
6
 *
7
 * This content is released under the MIT License (MIT)
8
 *
2414 lars 9
 * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
68 lars 10
 *
11
 * Permission is hereby granted, free of charge, to any person obtaining a copy
12
 * of this software and associated documentation files (the "Software"), to deal
13
 * in the Software without restriction, including without limitation the rights
14
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
 * copies of the Software, and to permit persons to whom the Software is
16
 * furnished to do so, subject to the following conditions:
17
 *
18
 * The above copyright notice and this permission notice shall be included in
19
 * all copies or substantial portions of the Software.
20
 *
21
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
 * THE SOFTWARE.
28
 *
29
 * @package	CodeIgniter
30
 * @author	EllisLab Dev Team
31
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
2414 lars 32
 * @copyright	Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
33
 * @license	https://opensource.org/licenses/MIT	MIT License
68 lars 34
 * @link	https://codeigniter.com
35
 * @since	Version 2.0.3
36
 * @filesource
37
 */
38
defined('BASEPATH') OR exit('No direct script access allowed');
39
 
40
/**
41
 * SQLSRV Database Adapter Class
42
 *
43
 * Note: _DB is an extender class that the app controller
44
 * creates dynamically based on whether the query builder
45
 * class is being used or not.
46
 *
47
 * @package		CodeIgniter
48
 * @subpackage	Drivers
49
 * @category	Database
50
 * @author		EllisLab Dev Team
51
 * @link		https://codeigniter.com/user_guide/database/
52
 */
53
class CI_DB_sqlsrv_driver extends CI_DB {
54
 
55
	/**
56
	 * Database driver
57
	 *
58
	 * @var	string
59
	 */
60
	public $dbdriver = 'sqlsrv';
61
 
62
	/**
63
	 * Scrollable flag
64
	 *
65
	 * Determines what cursor type to use when executing queries.
66
	 *
67
	 * FALSE or SQLSRV_CURSOR_FORWARD would increase performance,
68
	 * but would disable num_rows() (and possibly insert_id())
69
	 *
70
	 * @var	mixed
71
	 */
72
	public $scrollable;
73
 
74
	// --------------------------------------------------------------------
75
 
76
	/**
77
	 * ORDER BY random keyword
78
	 *
79
	 * @var	array
80
	 */
81
	protected $_random_keyword = array('NEWID()', 'RAND(%d)');
82
 
83
	/**
84
	 * Quoted identifier flag
85
	 *
86
	 * Whether to use SQL-92 standard quoted identifier
87
	 * (double quotes) or brackets for identifier escaping.
88
	 *
89
	 * @var	bool
90
	 */
91
	protected $_quoted_identifier = TRUE;
92
 
93
	// --------------------------------------------------------------------
94
 
95
	/**
96
	 * Class constructor
97
	 *
98
	 * @param	array	$params
99
	 * @return	void
100
	 */
101
	public function __construct($params)
102
	{
103
		parent::__construct($params);
104
 
105
		// This is only supported as of SQLSRV 3.0
106
		if ($this->scrollable === NULL)
107
		{
108
			$this->scrollable = defined('SQLSRV_CURSOR_CLIENT_BUFFERED')
109
				? SQLSRV_CURSOR_CLIENT_BUFFERED
110
				: FALSE;
111
		}
112
	}
113
 
114
	// --------------------------------------------------------------------
115
 
116
	/**
117
	 * Database connection
118
	 *
119
	 * @param	bool	$pooling
120
	 * @return	resource
121
	 */
122
	public function db_connect($pooling = FALSE)
123
	{
124
		$charset = in_array(strtolower($this->char_set), array('utf-8', 'utf8'), TRUE)
125
			? 'UTF-8' : SQLSRV_ENC_CHAR;
126
 
127
		$connection = array(
128
			'UID'			=> empty($this->username) ? '' : $this->username,
129
			'PWD'			=> empty($this->password) ? '' : $this->password,
130
			'Database'		=> $this->database,
131
			'ConnectionPooling'	=> ($pooling === TRUE) ? 1 : 0,
132
			'CharacterSet'		=> $charset,
133
			'Encrypt'		=> ($this->encrypt === TRUE) ? 1 : 0,
134
			'ReturnDatesAsStrings'	=> 1
135
		);
136
 
137
		// If the username and password are both empty, assume this is a
138
		// 'Windows Authentication Mode' connection.
139
		if (empty($connection['UID']) && empty($connection['PWD']))
140
		{
141
			unset($connection['UID'], $connection['PWD']);
142
		}
143
 
144
		if (FALSE !== ($this->conn_id = sqlsrv_connect($this->hostname, $connection)))
145
		{
146
			// Determine how identifiers are escaped
147
			$query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi');
148
			$query = $query->row_array();
149
			$this->_quoted_identifier = empty($query) ? FALSE : (bool) $query['qi'];
150
			$this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']');
151
		}
152
 
153
		return $this->conn_id;
154
	}
155
 
156
	// --------------------------------------------------------------------
157
 
158
	/**
159
	 * Select the database
160
	 *
161
	 * @param	string	$database
162
	 * @return	bool
163
	 */
164
	public function db_select($database = '')
165
	{
166
		if ($database === '')
167
		{
168
			$database = $this->database;
169
		}
170
 
171
		if ($this->_execute('USE '.$this->escape_identifiers($database)))
172
		{
173
			$this->database = $database;
174
			$this->data_cache = array();
175
			return TRUE;
176
		}
177
 
178
		return FALSE;
179
	}
180
 
181
	// --------------------------------------------------------------------
182
 
183
	/**
184
	 * Execute the query
185
	 *
186
	 * @param	string	$sql	an SQL query
187
	 * @return	resource
188
	 */
189
	protected function _execute($sql)
190
	{
191
		return ($this->scrollable === FALSE OR $this->is_write_type($sql))
192
			? sqlsrv_query($this->conn_id, $sql)
193
			: sqlsrv_query($this->conn_id, $sql, NULL, array('Scrollable' => $this->scrollable));
194
	}
195
 
196
	// --------------------------------------------------------------------
197
 
198
	/**
199
	 * Begin Transaction
200
	 *
201
	 * @return	bool
202
	 */
203
	protected function _trans_begin()
204
	{
205
		return sqlsrv_begin_transaction($this->conn_id);
206
	}
207
 
208
	// --------------------------------------------------------------------
209
 
210
	/**
211
	 * Commit Transaction
212
	 *
213
	 * @return	bool
214
	 */
215
	protected function _trans_commit()
216
	{
217
		return sqlsrv_commit($this->conn_id);
218
	}
219
 
220
	// --------------------------------------------------------------------
221
 
222
	/**
223
	 * Rollback Transaction
224
	 *
225
	 * @return	bool
226
	 */
227
	protected function _trans_rollback()
228
	{
229
		return sqlsrv_rollback($this->conn_id);
230
	}
231
 
232
	// --------------------------------------------------------------------
233
 
234
	/**
235
	 * Affected Rows
236
	 *
237
	 * @return	int
238
	 */
239
	public function affected_rows()
240
	{
241
		return sqlsrv_rows_affected($this->result_id);
242
	}
243
 
244
	// --------------------------------------------------------------------
245
 
246
	/**
247
	 * Insert ID
248
	 *
249
	 * Returns the last id created in the Identity column.
250
	 *
251
	 * @return	string
252
	 */
253
	public function insert_id()
254
	{
255
		return $this->query('SELECT SCOPE_IDENTITY() AS insert_id')->row()->insert_id;
256
	}
257
 
258
	// --------------------------------------------------------------------
259
 
260
	/**
261
	 * Database version number
262
	 *
263
	 * @return	string
264
	 */
265
	public function version()
266
	{
267
		if (isset($this->data_cache['version']))
268
		{
269
			return $this->data_cache['version'];
270
		}
271
 
272
		if ( ! $this->conn_id OR ($info = sqlsrv_server_info($this->conn_id)) === FALSE)
273
		{
274
			return FALSE;
275
		}
276
 
277
		return $this->data_cache['version'] = $info['SQLServerVersion'];
278
	}
279
 
280
	// --------------------------------------------------------------------
281
 
282
	/**
283
	 * List table query
284
	 *
285
	 * Generates a platform-specific query string so that the table names can be fetched
286
	 *
287
	 * @param	bool
288
	 * @return	string	$prefix_limit
289
	 */
290
	protected function _list_tables($prefix_limit = FALSE)
291
	{
292
		$sql = 'SELECT '.$this->escape_identifiers('name')
293
			.' FROM '.$this->escape_identifiers('sysobjects')
294
			.' WHERE '.$this->escape_identifiers('type')." = 'U'";
295
 
296
		if ($prefix_limit === TRUE && $this->dbprefix !== '')
297
		{
298
			$sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' "
299
				.sprintf($this->_escape_like_str, $this->_escape_like_chr);
300
		}
301
 
302
		return $sql.' ORDER BY '.$this->escape_identifiers('name');
303
	}
304
 
305
	// --------------------------------------------------------------------
306
 
307
	/**
308
	 * List column query
309
	 *
310
	 * Generates a platform-specific query string so that the column names can be fetched
311
	 *
312
	 * @param	string	$table
313
	 * @return	string
314
	 */
315
	protected function _list_columns($table = '')
316
	{
317
		return 'SELECT COLUMN_NAME
318
			FROM INFORMATION_SCHEMA.Columns
319
			WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));
320
	}
321
 
322
	// --------------------------------------------------------------------
323
 
324
	/**
325
	 * Returns an object with field data
326
	 *
327
	 * @param	string	$table
328
	 * @return	array
329
	 */
330
	public function field_data($table)
331
	{
332
		$sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT
333
			FROM INFORMATION_SCHEMA.Columns
334
			WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));
335
 
336
		if (($query = $this->query($sql)) === FALSE)
337
		{
338
			return FALSE;
339
		}
340
		$query = $query->result_object();
341
 
342
		$retval = array();
343
		for ($i = 0, $c = count($query); $i < $c; $i++)
344
		{
345
			$retval[$i]			= new stdClass();
346
			$retval[$i]->name		= $query[$i]->COLUMN_NAME;
347
			$retval[$i]->type		= $query[$i]->DATA_TYPE;
348
			$retval[$i]->max_length		= ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION;
349
			$retval[$i]->default		= $query[$i]->COLUMN_DEFAULT;
350
		}
351
 
352
		return $retval;
353
	}
354
 
355
	// --------------------------------------------------------------------
356
 
357
	/**
358
	 * Error
359
	 *
360
	 * Returns an array containing code and message of the last
2107 lars 361
	 * database error that has occurred.
68 lars 362
	 *
363
	 * @return	array
364
	 */
365
	public function error()
366
	{
367
		$error = array('code' => '00000', 'message' => '');
368
		$sqlsrv_errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
369
 
370
		if ( ! is_array($sqlsrv_errors))
371
		{
372
			return $error;
373
		}
374
 
375
		$sqlsrv_error = array_shift($sqlsrv_errors);
376
		if (isset($sqlsrv_error['SQLSTATE']))
377
		{
378
			$error['code'] = isset($sqlsrv_error['code']) ? $sqlsrv_error['SQLSTATE'].'/'.$sqlsrv_error['code'] : $sqlsrv_error['SQLSTATE'];
379
		}
380
		elseif (isset($sqlsrv_error['code']))
381
		{
382
			$error['code'] = $sqlsrv_error['code'];
383
		}
384
 
385
		if (isset($sqlsrv_error['message']))
386
		{
387
			$error['message'] = $sqlsrv_error['message'];
388
		}
389
 
390
		return $error;
391
	}
392
 
393
	// --------------------------------------------------------------------
394
 
395
	/**
396
	 * Update statement
397
	 *
398
	 * Generates a platform-specific update string from the supplied data
399
	 *
400
	 * @param	string	$table
401
	 * @param	array	$values
402
	 * @return	string
403
	 */
404
	protected function _update($table, $values)
405
	{
406
		$this->qb_limit = FALSE;
407
		$this->qb_orderby = array();
408
		return parent::_update($table, $values);
409
	}
410
 
411
	// --------------------------------------------------------------------
412
 
413
	/**
414
	 * Truncate statement
415
	 *
416
	 * Generates a platform-specific truncate string from the supplied data
417
	 *
418
	 * If the database does not support the TRUNCATE statement,
419
	 * then this method maps to 'DELETE FROM table'
420
	 *
421
	 * @param	string	$table
422
	 * @return	string
423
	 */
424
	protected function _truncate($table)
425
	{
426
		return 'TRUNCATE TABLE '.$table;
427
	}
428
 
429
	// --------------------------------------------------------------------
430
 
431
	/**
432
	 * Delete statement
433
	 *
434
	 * Generates a platform-specific delete string from the supplied data
435
	 *
436
	 * @param	string	$table
437
	 * @return	string
438
	 */
439
	protected function _delete($table)
440
	{
441
		if ($this->qb_limit)
442
		{
443
			return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete';
444
		}
445
 
446
		return parent::_delete($table);
447
	}
448
 
449
	// --------------------------------------------------------------------
450
 
451
	/**
452
	 * LIMIT
453
	 *
454
	 * Generates a platform-specific LIMIT clause
455
	 *
456
	 * @param	string	$sql	SQL Query
457
	 * @return	string
458
	 */
459
	protected function _limit($sql)
460
	{
461
		// As of SQL Server 2012 (11.0.*) OFFSET is supported
462
		if (version_compare($this->version(), '11', '>='))
463
		{
464
			// SQL Server OFFSET-FETCH can be used only with the ORDER BY clause
465
			empty($this->qb_orderby) && $sql .= ' ORDER BY 1';
466
 
467
			return $sql.' OFFSET '.(int) $this->qb_offset.' ROWS FETCH NEXT '.$this->qb_limit.' ROWS ONLY';
468
		}
469
 
470
		$limit = $this->qb_offset + $this->qb_limit;
471
 
472
		// An ORDER BY clause is required for ROW_NUMBER() to work
473
		if ($this->qb_offset && ! empty($this->qb_orderby))
474
		{
475
			$orderby = $this->_compile_order_by();
476
 
477
			// We have to strip the ORDER BY clause
478
			$sql = trim(substr($sql, 0, strrpos($sql, $orderby)));
479
 
480
			// Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results
2107 lars 481
			if (count($this->qb_select) === 0 OR strpos(implode(',', $this->qb_select), '*') !== FALSE)
68 lars 482
			{
483
				$select = '*'; // Inevitable
484
			}
485
			else
486
			{
487
				// Use only field names and their aliases, everything else is out of our scope.
488
				$select = array();
489
				$field_regexp = ($this->_quoted_identifier)
490
					? '("[^\"]+")' : '(\[[^\]]+\])';
491
				for ($i = 0, $c = count($this->qb_select); $i < $c; $i++)
492
				{
493
					$select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m)
494
						? $m[1] : $this->qb_select[$i];
495
				}
496
				$select = implode(', ', $select);
497
			}
498
 
499
			return 'SELECT '.$select." FROM (\n\n"
500
				.preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql)
501
				."\n\n) ".$this->escape_identifiers('CI_subquery')
502
				."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit;
503
		}
504
 
505
		return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql);
506
	}
507
 
508
	// --------------------------------------------------------------------
509
 
510
	/**
511
	 * Insert batch statement
512
	 *
513
	 * Generates a platform-specific insert string from the supplied data.
514
	 *
515
	 * @param	string	$table	Table name
516
	 * @param	array	$keys	INSERT keys
517
	 * @param	array	$values	INSERT values
518
	 * @return	string|bool
519
	 */
520
	protected function _insert_batch($table, $keys, $values)
521
	{
522
		// Multiple-value inserts are only supported as of SQL Server 2008
523
		if (version_compare($this->version(), '10', '>='))
524
		{
525
			return parent::_insert_batch($table, $keys, $values);
526
		}
527
 
2107 lars 528
		return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE;
68 lars 529
	}
530
 
531
	// --------------------------------------------------------------------
532
 
533
	/**
534
	 * Close DB Connection
535
	 *
536
	 * @return	void
537
	 */
538
	protected function _close()
539
	{
540
		sqlsrv_close($this->conn_id);
541
	}
542
 
543
}