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