blob: 11690712373cfc9f4256c0b8a1fa8e46c42b39c5 [file] [log] [blame]
Alex Bilbie84445d02011-03-10 16:43:39 +00001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 5.1.6 or newer
6 *
7 * @package CodeIgniter
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
Alex Bilbie01ab0042011-03-18 19:24:30 +000019 * SQLSRV Database Adapter Class
Alex Bilbie84445d02011-03-10 16:43:39 +000020 *
21 * Note: _DB is an extender class that the app controller
22 * creates dynamically based on whether the active record
23 * class is being used or not.
24 *
25 * @package CodeIgniter
26 * @subpackage Drivers
27 * @category Database
28 * @author ExpressionEngine Dev Team
29 * @link http://codeigniter.com/user_guide/database/
30 */
Alex Bilbie01ab0042011-03-18 19:24:30 +000031class CI_DB_sqlsrv_driver extends CI_DB {
Alex Bilbie84445d02011-03-10 16:43:39 +000032
33 var $dbdriver = 'sqlsrv';
34
35 // The character used for escaping
36 var $_escape_char = '';
37
38 // clause and character used for LIKE escape sequences
39 var $_like_escape_str = " ESCAPE '%s' ";
40 var $_like_escape_chr = '!';
41
42 /**
43 * The syntax to count rows is slightly different across different
44 * database engines, so this string appears in each driver and is
45 * used for the count_all() and count_all_results() functions.
46 */
47 var $_count_string = "SELECT COUNT(*) AS ";
48 var $_random_keyword = ' ASC'; // not currently supported
49
50 /**
51 * Non-persistent database connection
52 *
53 * @access private called by the base class
54 * @return resource
55 */
56 function db_connect()
57 {
58 if ($this->port != '')
59 {
60 $this->hostname .= ','.$this->port;
61 }
62
Alex Bilbie5336ee22011-03-12 23:35:29 +000063 return @sqlsrv_connect($this->hostname, array('UID' => $this->username, 'PWD' => $this->password, 'Database' => $this->database, 'ConnectionPooling' => 0, 'ReturnDatesAsStrings' => 1));
Alex Bilbie84445d02011-03-10 16:43:39 +000064 }
65
66 // --------------------------------------------------------------------
67
68 /**
69 * Persistent database connection
70 *
71 * @access private called by the base class
72 * @return resource
73 */
74 function db_pconnect()
75 {
76 if ($this->port != '')
77 {
78 $this->hostname .= ','.$this->port;
79 }
80
Alex Bilbie5336ee22011-03-12 23:35:29 +000081 return @sqlsrv_connect($this->hostname, array('UID' => $this->username, 'PWD' => $this->password, 'Database' => $this->database, 'ConnectionPooling' => 1, 'ReturnDatesAsStrings' => 1));
Alex Bilbie84445d02011-03-10 16:43:39 +000082 }
83
84 // --------------------------------------------------------------------
85
86 /**
87 * Reconnect
88 *
89 * Keep / reestablish the db connection if no queries have been
90 * sent for a length of time exceeding the server's idle timeout
91 *
92 * @access public
93 * @return void
94 */
95 function reconnect()
96 {
97 // not implemented in MSSQL
98 }
99
100 // --------------------------------------------------------------------
101
102 /**
103 * Select the database
104 *
105 * @access private called by the base class
106 * @return resource
107 */
108 function db_select()
109 {
Alex Bilbie5336ee22011-03-12 23:35:29 +0000110 return $this->_execute('USE ' . $this->database);
Alex Bilbie84445d02011-03-10 16:43:39 +0000111 }
112
113 // --------------------------------------------------------------------
114
115 /**
116 * Set client character set
117 *
118 * @access public
119 * @param string
120 * @param string
121 * @return resource
122 */
123 function db_set_charset($charset, $collation)
124 {
125 // @todo - add support if needed
126 return TRUE;
127 }
128
129 // --------------------------------------------------------------------
130
131 /**
132 * Execute the query
133 *
134 * @access private called by the base class
135 * @param string an SQL query
136 * @return resource
137 */
138 function _execute($sql)
139 {
140 $sql = $this->_prep_query($sql);
141 return @sqlsrv_query($this->conn_id, $sql);
142 }
143
144 // --------------------------------------------------------------------
145
146 /**
147 * Prep the query
148 *
149 * If needed, each database adapter can prep the query string
150 *
151 * @access private called by execute()
152 * @param string an SQL query
153 * @return string
154 */
155 function _prep_query($sql)
156 {
157 return $sql;
158 }
159
160 // --------------------------------------------------------------------
161
162 /**
163 * Begin Transaction
164 *
165 * @access public
166 * @return bool
167 */
168 function trans_begin($test_mode = FALSE)
169 {
170 if ( ! $this->trans_enabled)
171 {
172 return TRUE;
173 }
174
175 // When transactions are nested we only begin/commit/rollback the outermost ones
176 if ($this->_trans_depth > 0)
177 {
178 return TRUE;
179 }
180
181 // Reset the transaction failure flag.
182 // If the $test_mode flag is set to TRUE transactions will be rolled back
183 // even if the queries produce a successful result.
184 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
185
186 $this->simple_query('BEGIN TRAN');
187 return TRUE;
188 }
189
190 // --------------------------------------------------------------------
191
192 /**
193 * Commit Transaction
194 *
195 * @access public
196 * @return bool
197 */
198 function trans_commit()
199 {
200 if ( ! $this->trans_enabled)
201 {
202 return TRUE;
203 }
204
205 // When transactions are nested we only begin/commit/rollback the outermost ones
206 if ($this->_trans_depth > 0)
207 {
208 return TRUE;
209 }
210
211 $this->simple_query('COMMIT TRAN');
212 return TRUE;
213 }
214
215 // --------------------------------------------------------------------
216
217 /**
218 * Rollback Transaction
219 *
220 * @access public
221 * @return bool
222 */
223 function trans_rollback()
224 {
225 if ( ! $this->trans_enabled)
226 {
227 return TRUE;
228 }
229
230 // When transactions are nested we only begin/commit/rollback the outermost ones
231 if ($this->_trans_depth > 0)
232 {
233 return TRUE;
234 }
235
236 $this->simple_query('ROLLBACK TRAN');
237 return TRUE;
238 }
239
240 // --------------------------------------------------------------------
241
242 /**
243 * Escape String
244 *
245 * @access public
246 * @param string
247 * @param bool whether or not the string will be used in a LIKE condition
248 * @return string
249 */
250 function escape_str($str, $like = FALSE)
251 {
252 if (is_array($str))
253 {
254 foreach ($str as $key => $val)
255 {
256 $str[$key] = $this->escape_str($val, $like);
257 }
258
259 return $str;
260 }
261
262 // Escape single quotes
263 $str = str_replace("'", "''", remove_invisible_characters($str));
264
265 // escape LIKE condition wildcards
266 if ($like === TRUE)
267 {
268 $str = str_replace( array('%', '_', $this->_like_escape_chr),
269 array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr),
270 $str);
271 }
272
273 return $str;
274 }
275
276 // --------------------------------------------------------------------
277
278 /**
279 * Affected Rows
280 *
281 * @access public
282 * @return integer
283 */
284 function affected_rows()
285 {
Alex Bilbie56e20402011-03-12 23:43:54 +0000286 return @sqlrv_rows_affected($this->conn_id);
Alex Bilbie84445d02011-03-10 16:43:39 +0000287 }
288
289 // --------------------------------------------------------------------
290
291 /**
292 * Insert ID
293 *
294 * Returns the last id created in the Identity column.
295 *
296 * @access public
297 * @return integer
298 */
299 function insert_id()
300 {
301 $ver = self::_parse_major_version($this->version());
302 $sql = ($ver >= 8 ? "SELECT SCOPE_IDENTITY() AS last_id" : "SELECT @@IDENTITY AS last_id");
303 $query = $this->query($sql);
304 $row = $query->row();
305 return $row->last_id;
306 }
307
308 // --------------------------------------------------------------------
309
310 /**
311 * Parse major version
312 *
313 * Grabs the major version number from the
314 * database server version string passed in.
315 *
316 * @access private
317 * @param string $version
318 * @return int16 major version number
319 */
320 function _parse_major_version($version)
321 {
322 preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $version, $ver_info);
323 return $ver_info[1]; // return the major version b/c that's all we're interested in.
324 }
325
326 // --------------------------------------------------------------------
327
328 /**
329 * Version number query string
330 *
331 * @access public
332 * @return string
333 */
334 function _version()
335 {
336 return "SELECT @@VERSION AS ver";
337 }
338
339 // --------------------------------------------------------------------
340
341 /**
342 * "Count All" query
343 *
344 * Generates a platform-specific query string that counts all records in
345 * the specified database
346 *
347 * @access public
348 * @param string
349 * @return string
350 */
351 function count_all($table = '')
352 {
353 if ($table == '')
354 {
355 return 0;
356 }
357
358 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
359
360 if ($query->num_rows() == 0)
361 {
362 return 0;
363 }
364
365 $row = $query->row();
366 return (int) $row->numrows;
367 }
368
369 // --------------------------------------------------------------------
370
371 /**
372 * List table query
373 *
374 * Generates a platform-specific query string so that the table names can be fetched
375 *
376 * @access private
377 * @param boolean
378 * @return string
379 */
380 function _list_tables($prefix_limit = FALSE)
381 {
382 $sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
383
384 // for future compatibility
385 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
386 {
387 //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
388 return FALSE; // not currently supported
389 }
390
391 return $sql;
392 }
393
394 // --------------------------------------------------------------------
395
396 /**
397 * List column query
398 *
399 * Generates a platform-specific query string so that the column names can be fetched
400 *
401 * @access private
402 * @param string the table name
403 * @return string
404 */
405 function _list_columns($table = '')
406 {
407 return "SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$table."'";
408 }
409
410 // --------------------------------------------------------------------
411
412 /**
413 * Field data query
414 *
415 * Generates a platform-specific query so that the column data can be retrieved
416 *
417 * @access public
418 * @param string the table name
419 * @return object
420 */
421 function _field_data($table)
422 {
423 return "SELECT TOP 1 * FROM ".$table;
424 }
425
426 // --------------------------------------------------------------------
427
428 /**
429 * The error message string
430 *
431 * @access private
432 * @return string
433 */
434 function _error_message()
435 {
436 return sqlsrv_errors();
437 }
438
439 // --------------------------------------------------------------------
440
441 /**
442 * The error message number
443 *
444 * @access private
445 * @return integer
446 */
447 function _error_number()
448 {
449 // Are error numbers supported?
450 return '';
451 }
452
453 // --------------------------------------------------------------------
454
455 /**
456 * Escape the SQL Identifiers
457 *
458 * This function escapes column and table names
459 *
460 * @access private
461 * @param string
462 * @return string
463 */
464 function _escape_identifiers($item)
465 {
466 if ($this->_escape_char == '')
467 {
468 return $item;
469 }
470
471 foreach ($this->_reserved_identifiers as $id)
472 {
473 if (strpos($item, '.'.$id) !== FALSE)
474 {
475 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
476
477 // remove duplicates if the user already included the escape
478 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
479 }
480 }
481
482 if (strpos($item, '.') !== FALSE)
483 {
484 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
485 }
486 else
487 {
488 $str = $this->_escape_char.$item.$this->_escape_char;
489 }
490
491 // remove duplicates if the user already included the escape
492 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
493 }
494
495 // --------------------------------------------------------------------
496
497 /**
498 * From Tables
499 *
500 * This function implicitly groups FROM tables so there is no confusion
501 * about operator precedence in harmony with SQL standards
502 *
503 * @access public
504 * @param type
505 * @return type
506 */
507 function _from_tables($tables)
508 {
509 if ( ! is_array($tables))
510 {
511 $tables = array($tables);
512 }
513
514 return implode(', ', $tables);
515 }
516
517 // --------------------------------------------------------------------
518
519 /**
520 * Insert statement
521 *
522 * Generates a platform-specific insert string from the supplied data
523 *
524 * @access public
525 * @param string the table name
526 * @param array the insert keys
527 * @param array the insert values
528 * @return string
529 */
530 function _insert($table, $keys, $values)
531 {
532 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
533 }
534
535 // --------------------------------------------------------------------
536
537 /**
538 * Update statement
539 *
540 * Generates a platform-specific update string from the supplied data
541 *
542 * @access public
543 * @param string the table name
544 * @param array the update data
545 * @param array the where clause
546 * @param array the orderby clause
547 * @param array the limit clause
548 * @return string
549 */
550 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
551 {
552 foreach ($values as $key => $val)
553 {
554 $valstr[] = $key." = ".$val;
555 }
556
557 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
558
559 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
560
561 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
562
563 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
564
565 $sql .= $orderby.$limit;
566
567 return $sql;
568 }
569
570
571 // --------------------------------------------------------------------
572
573 /**
574 * Truncate statement
575 *
576 * Generates a platform-specific truncate string from the supplied data
577 * If the database does not support the truncate() command
578 * This function maps to "DELETE FROM table"
579 *
580 * @access public
581 * @param string the table name
582 * @return string
583 */
584 function _truncate($table)
585 {
586 return "TRUNCATE ".$table;
587 }
588
589 // --------------------------------------------------------------------
590
591 /**
592 * Delete statement
593 *
594 * Generates a platform-specific delete string from the supplied data
595 *
596 * @access public
597 * @param string the table name
598 * @param array the where clause
599 * @param string the limit clause
600 * @return string
601 */
602 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
603 {
604 $conditions = '';
605
606 if (count($where) > 0 OR count($like) > 0)
607 {
608 $conditions = "\nWHERE ";
609 $conditions .= implode("\n", $this->ar_where);
610
611 if (count($where) > 0 && count($like) > 0)
612 {
613 $conditions .= " AND ";
614 }
615 $conditions .= implode("\n", $like);
616 }
617
618 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
619
620 return "DELETE FROM ".$table.$conditions.$limit;
621 }
622
623 // --------------------------------------------------------------------
624
625 /**
626 * Limit string
627 *
628 * Generates a platform-specific LIMIT clause
629 *
630 * @access public
631 * @param string the sql query string
632 * @param integer the number of rows to limit the query to
633 * @param integer the offset value
634 * @return string
635 */
636 function _limit($sql, $limit, $offset)
637 {
638 $i = $limit + $offset;
639
640 return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$i.' ', $sql);
641 }
642
643 // --------------------------------------------------------------------
644
645 /**
646 * Close DB Connection
647 *
648 * @access public
649 * @param resource
650 * @return void
651 */
652 function _close($conn_id)
653 {
654 @sqlsrv_close($conn_id);
655 }
656
657}
658
659
660
661/* End of file mssql_driver.php */
662/* Location: ./system/database/drivers/mssql/mssql_driver.php */