blob: d64e981083560e30f09106f5dc74000b2c63c939 [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/**
19 * MS SQL Database Adapter Class
20 *
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 */
31class CI_DB_mssql_driver extends CI_DB {
32
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
63 return @sqlsrv_connect($this->hostname, array('UID' => $this->username, 'PWD' => $this->password, 'Database' => $this->database, 'ConnectionPooling' => 0));
64 }
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
81 return @sqlsrv_connect($this->hostname, array('UID' => $this->username, 'PWD' => $this->password, 'Database' => $this->database, 'ConnectionPooling' => 1));
82 }
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 {
110 // Note: The brackets are required in the event that the DB name
111 // contains reserved characters
112 return @mssql_select_db('['.$this->database.']', $this->conn_id);
113 }
114
115 // --------------------------------------------------------------------
116
117 /**
118 * Set client character set
119 *
120 * @access public
121 * @param string
122 * @param string
123 * @return resource
124 */
125 function db_set_charset($charset, $collation)
126 {
127 // @todo - add support if needed
128 return TRUE;
129 }
130
131 // --------------------------------------------------------------------
132
133 /**
134 * Execute the query
135 *
136 * @access private called by the base class
137 * @param string an SQL query
138 * @return resource
139 */
140 function _execute($sql)
141 {
142 $sql = $this->_prep_query($sql);
143 return @sqlsrv_query($this->conn_id, $sql);
144 }
145
146 // --------------------------------------------------------------------
147
148 /**
149 * Prep the query
150 *
151 * If needed, each database adapter can prep the query string
152 *
153 * @access private called by execute()
154 * @param string an SQL query
155 * @return string
156 */
157 function _prep_query($sql)
158 {
159 return $sql;
160 }
161
162 // --------------------------------------------------------------------
163
164 /**
165 * Begin Transaction
166 *
167 * @access public
168 * @return bool
169 */
170 function trans_begin($test_mode = FALSE)
171 {
172 if ( ! $this->trans_enabled)
173 {
174 return TRUE;
175 }
176
177 // When transactions are nested we only begin/commit/rollback the outermost ones
178 if ($this->_trans_depth > 0)
179 {
180 return TRUE;
181 }
182
183 // Reset the transaction failure flag.
184 // If the $test_mode flag is set to TRUE transactions will be rolled back
185 // even if the queries produce a successful result.
186 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
187
188 $this->simple_query('BEGIN TRAN');
189 return TRUE;
190 }
191
192 // --------------------------------------------------------------------
193
194 /**
195 * Commit Transaction
196 *
197 * @access public
198 * @return bool
199 */
200 function trans_commit()
201 {
202 if ( ! $this->trans_enabled)
203 {
204 return TRUE;
205 }
206
207 // When transactions are nested we only begin/commit/rollback the outermost ones
208 if ($this->_trans_depth > 0)
209 {
210 return TRUE;
211 }
212
213 $this->simple_query('COMMIT TRAN');
214 return TRUE;
215 }
216
217 // --------------------------------------------------------------------
218
219 /**
220 * Rollback Transaction
221 *
222 * @access public
223 * @return bool
224 */
225 function trans_rollback()
226 {
227 if ( ! $this->trans_enabled)
228 {
229 return TRUE;
230 }
231
232 // When transactions are nested we only begin/commit/rollback the outermost ones
233 if ($this->_trans_depth > 0)
234 {
235 return TRUE;
236 }
237
238 $this->simple_query('ROLLBACK TRAN');
239 return TRUE;
240 }
241
242 // --------------------------------------------------------------------
243
244 /**
245 * Escape String
246 *
247 * @access public
248 * @param string
249 * @param bool whether or not the string will be used in a LIKE condition
250 * @return string
251 */
252 function escape_str($str, $like = FALSE)
253 {
254 if (is_array($str))
255 {
256 foreach ($str as $key => $val)
257 {
258 $str[$key] = $this->escape_str($val, $like);
259 }
260
261 return $str;
262 }
263
264 // Escape single quotes
265 $str = str_replace("'", "''", remove_invisible_characters($str));
266
267 // escape LIKE condition wildcards
268 if ($like === TRUE)
269 {
270 $str = str_replace( array('%', '_', $this->_like_escape_chr),
271 array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr),
272 $str);
273 }
274
275 return $str;
276 }
277
278 // --------------------------------------------------------------------
279
280 /**
281 * Affected Rows
282 *
283 * @access public
284 * @return integer
285 */
286 function affected_rows()
287 {
288 return @mssql_rows_affected($this->conn_id);
289 }
290
291 // --------------------------------------------------------------------
292
293 /**
294 * Insert ID
295 *
296 * Returns the last id created in the Identity column.
297 *
298 * @access public
299 * @return integer
300 */
301 function insert_id()
302 {
303 $ver = self::_parse_major_version($this->version());
304 $sql = ($ver >= 8 ? "SELECT SCOPE_IDENTITY() AS last_id" : "SELECT @@IDENTITY AS last_id");
305 $query = $this->query($sql);
306 $row = $query->row();
307 return $row->last_id;
308 }
309
310 // --------------------------------------------------------------------
311
312 /**
313 * Parse major version
314 *
315 * Grabs the major version number from the
316 * database server version string passed in.
317 *
318 * @access private
319 * @param string $version
320 * @return int16 major version number
321 */
322 function _parse_major_version($version)
323 {
324 preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $version, $ver_info);
325 return $ver_info[1]; // return the major version b/c that's all we're interested in.
326 }
327
328 // --------------------------------------------------------------------
329
330 /**
331 * Version number query string
332 *
333 * @access public
334 * @return string
335 */
336 function _version()
337 {
338 return "SELECT @@VERSION AS ver";
339 }
340
341 // --------------------------------------------------------------------
342
343 /**
344 * "Count All" query
345 *
346 * Generates a platform-specific query string that counts all records in
347 * the specified database
348 *
349 * @access public
350 * @param string
351 * @return string
352 */
353 function count_all($table = '')
354 {
355 if ($table == '')
356 {
357 return 0;
358 }
359
360 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
361
362 if ($query->num_rows() == 0)
363 {
364 return 0;
365 }
366
367 $row = $query->row();
368 return (int) $row->numrows;
369 }
370
371 // --------------------------------------------------------------------
372
373 /**
374 * List table query
375 *
376 * Generates a platform-specific query string so that the table names can be fetched
377 *
378 * @access private
379 * @param boolean
380 * @return string
381 */
382 function _list_tables($prefix_limit = FALSE)
383 {
384 $sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
385
386 // for future compatibility
387 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
388 {
389 //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
390 return FALSE; // not currently supported
391 }
392
393 return $sql;
394 }
395
396 // --------------------------------------------------------------------
397
398 /**
399 * List column query
400 *
401 * Generates a platform-specific query string so that the column names can be fetched
402 *
403 * @access private
404 * @param string the table name
405 * @return string
406 */
407 function _list_columns($table = '')
408 {
409 return "SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$table."'";
410 }
411
412 // --------------------------------------------------------------------
413
414 /**
415 * Field data query
416 *
417 * Generates a platform-specific query so that the column data can be retrieved
418 *
419 * @access public
420 * @param string the table name
421 * @return object
422 */
423 function _field_data($table)
424 {
425 return "SELECT TOP 1 * FROM ".$table;
426 }
427
428 // --------------------------------------------------------------------
429
430 /**
431 * The error message string
432 *
433 * @access private
434 * @return string
435 */
436 function _error_message()
437 {
438 return sqlsrv_errors();
439 }
440
441 // --------------------------------------------------------------------
442
443 /**
444 * The error message number
445 *
446 * @access private
447 * @return integer
448 */
449 function _error_number()
450 {
451 // Are error numbers supported?
452 return '';
453 }
454
455 // --------------------------------------------------------------------
456
457 /**
458 * Escape the SQL Identifiers
459 *
460 * This function escapes column and table names
461 *
462 * @access private
463 * @param string
464 * @return string
465 */
466 function _escape_identifiers($item)
467 {
468 if ($this->_escape_char == '')
469 {
470 return $item;
471 }
472
473 foreach ($this->_reserved_identifiers as $id)
474 {
475 if (strpos($item, '.'.$id) !== FALSE)
476 {
477 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
478
479 // remove duplicates if the user already included the escape
480 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
481 }
482 }
483
484 if (strpos($item, '.') !== FALSE)
485 {
486 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
487 }
488 else
489 {
490 $str = $this->_escape_char.$item.$this->_escape_char;
491 }
492
493 // remove duplicates if the user already included the escape
494 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
495 }
496
497 // --------------------------------------------------------------------
498
499 /**
500 * From Tables
501 *
502 * This function implicitly groups FROM tables so there is no confusion
503 * about operator precedence in harmony with SQL standards
504 *
505 * @access public
506 * @param type
507 * @return type
508 */
509 function _from_tables($tables)
510 {
511 if ( ! is_array($tables))
512 {
513 $tables = array($tables);
514 }
515
516 return implode(', ', $tables);
517 }
518
519 // --------------------------------------------------------------------
520
521 /**
522 * Insert statement
523 *
524 * Generates a platform-specific insert string from the supplied data
525 *
526 * @access public
527 * @param string the table name
528 * @param array the insert keys
529 * @param array the insert values
530 * @return string
531 */
532 function _insert($table, $keys, $values)
533 {
534 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
535 }
536
537 // --------------------------------------------------------------------
538
539 /**
540 * Update statement
541 *
542 * Generates a platform-specific update string from the supplied data
543 *
544 * @access public
545 * @param string the table name
546 * @param array the update data
547 * @param array the where clause
548 * @param array the orderby clause
549 * @param array the limit clause
550 * @return string
551 */
552 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
553 {
554 foreach ($values as $key => $val)
555 {
556 $valstr[] = $key." = ".$val;
557 }
558
559 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
560
561 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
562
563 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
564
565 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
566
567 $sql .= $orderby.$limit;
568
569 return $sql;
570 }
571
572
573 // --------------------------------------------------------------------
574
575 /**
576 * Truncate statement
577 *
578 * Generates a platform-specific truncate string from the supplied data
579 * If the database does not support the truncate() command
580 * This function maps to "DELETE FROM table"
581 *
582 * @access public
583 * @param string the table name
584 * @return string
585 */
586 function _truncate($table)
587 {
588 return "TRUNCATE ".$table;
589 }
590
591 // --------------------------------------------------------------------
592
593 /**
594 * Delete statement
595 *
596 * Generates a platform-specific delete string from the supplied data
597 *
598 * @access public
599 * @param string the table name
600 * @param array the where clause
601 * @param string the limit clause
602 * @return string
603 */
604 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
605 {
606 $conditions = '';
607
608 if (count($where) > 0 OR count($like) > 0)
609 {
610 $conditions = "\nWHERE ";
611 $conditions .= implode("\n", $this->ar_where);
612
613 if (count($where) > 0 && count($like) > 0)
614 {
615 $conditions .= " AND ";
616 }
617 $conditions .= implode("\n", $like);
618 }
619
620 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
621
622 return "DELETE FROM ".$table.$conditions.$limit;
623 }
624
625 // --------------------------------------------------------------------
626
627 /**
628 * Limit string
629 *
630 * Generates a platform-specific LIMIT clause
631 *
632 * @access public
633 * @param string the sql query string
634 * @param integer the number of rows to limit the query to
635 * @param integer the offset value
636 * @return string
637 */
638 function _limit($sql, $limit, $offset)
639 {
640 $i = $limit + $offset;
641
642 return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$i.' ', $sql);
643 }
644
645 // --------------------------------------------------------------------
646
647 /**
648 * Close DB Connection
649 *
650 * @access public
651 * @param resource
652 * @return void
653 */
654 function _close($conn_id)
655 {
656 @sqlsrv_close($conn_id);
657 }
658
659}
660
661
662
663/* End of file mssql_driver.php */
664/* Location: ./system/database/drivers/mssql/mssql_driver.php */