1 <?php defined('SYSPATH') OR die('No direct access allowed.');
3 * MSSQL Database Driver
7 * @copyright (c) 2007-2008 Kohana Team
8 * @license http://kohanaphp.com/license.html
10 class Database_Mssql_Driver extends Database_Driver
13 * Database connection link
18 * Database configuration
23 * Sets the config for the class.
25 * @param array database configuration
27 public function __construct($config)
29 $this->db_config = $config;
31 Kohana::log('debug', 'MSSQL Database Driver Initialized');
35 * Closes the database connection.
37 public function __destruct()
39 is_resource($this->link) and mssql_close($this->link);
45 * @return return connection
47 public function connect()
49 // Check if link already exists
50 if (is_resource($this->link))
53 // Import the connect variables
54 extract($this->db_config['connection']);
56 // Persistent connections enabled?
57 $connect = ($this->db_config['persistent'] == TRUE) ? 'mssql_pconnect' : 'mssql_connect';
59 // Build the connection info
60 $host = isset($host) ? $host : $socket;
62 // Windows uses a comma instead of a colon
63 $port = (isset($port) AND is_string($port)) ? (KOHANA_IS_WIN ? ',' : ':').$port : '';
65 // Make the connection and select the database
66 if (($this->link = $connect($host.$port, $user, $pass, TRUE)) AND mssql_select_db($database, $this->link))
68 /* This is being removed so I can use it, will need to come up with a more elegant workaround in the future...
70 if ($charset = $this->db_config['character_set'])
72 $this->set_charset($charset);
76 // Clear password after successful connect
77 $this->db_config['connection']['pass'] = NULL;
85 public function query($sql)
87 // Only cache if it's turned on, and only cache if it's not a write statement
88 if ($this->db_config['cache'] AND ! preg_match('#\b(?:INSERT|UPDATE|REPLACE|SET)\b#i', $sql))
90 $hash = $this->query_hash($sql);
92 if ( ! isset($this->query_cache[$hash]))
94 // Set the cached object
95 $this->query_cache[$hash] = new Mssql_Result(mssql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql);
99 // Rewind cached result
100 $this->query_cache[$hash]->rewind();
103 // Return the cached query
104 return $this->query_cache[$hash];
107 return new Mssql_Result(mssql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql);
110 public function escape_table($table)
112 if (stripos($table, ' AS ') !== FALSE)
114 // Force 'AS' to uppercase
115 $table = str_ireplace(' AS ', ' AS ', $table);
117 // Runs escape_table on both sides of an AS statement
118 $table = array_map(array($this, __FUNCTION__), explode(' AS ', $table));
120 // Re-create the AS statement
121 return implode(' AS ', $table);
123 return '['.str_replace('.', '[.]', $table).']';
126 public function escape_column($column)
128 if (!$this->db_config['escape'])
134 // This matches any functions we support to SELECT.
135 if ( preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches))
137 if ( count($matches) == 3)
139 return $matches[1].'('.$this->escape_column($matches[2]).')';
141 else if ( count($matches) == 5)
143 return $matches[1].'('.$this->escape_column($matches[2]).') AS '.$this->escape_column($matches[2]);
147 // This matches any modifiers we support to SELECT.
148 if ( ! preg_match('/\b(?:rand|all|distinct(?:row)?|high_priority|sql_(?:small_result|b(?:ig_result|uffer_result)|no_cache|ca(?:che|lc_found_rows)))\s/i', $column))
150 if (stripos($column, ' AS ') !== FALSE)
152 // Force 'AS' to uppercase
153 $column = str_ireplace(' AS ', ' AS ', $column);
155 // Runs escape_column on both sides of an AS statement
156 $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column));
158 // Re-create the AS statement
159 return implode(' AS ', $column);
162 return preg_replace('/[^.*]+/', '[$0]', $column);
165 $parts = explode(' ', $column);
168 for ($i = 0, $c = count($parts); $i < $c; $i++)
170 // The column is always last
173 $column .= preg_replace('/[^.*]+/', '[$0]', $parts[$i]);
175 else // otherwise, it's a modifier
177 $column .= $parts[$i].' ';
184 * Limit in SQL Server 2000 only uses the keyword
185 * 'TOP'; 2007 may have an offset keyword, but
186 * I am unsure - for pagination style limit,offset
187 * functionality, a fancy query needs to be built.
189 * @param unknown_type $limit
192 public function limit($limit, $offset=null)
194 return 'TOP '.$limit;
197 public function compile_select($database)
199 $sql = ($database['distinct'] == TRUE) ? 'SELECT DISTINCT ' : 'SELECT ';
200 $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*';
202 if (count($database['from']) > 0)
206 foreach ($database['from'] as $from)
207 $froms[] = $this->escape_column($from);
209 $sql .= implode(', ', $froms);
212 if (count($database['join']) > 0)
214 foreach($database['join'] AS $join)
216 $sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions'];
220 if (count($database['where']) > 0)
225 $sql .= implode("\n", $database['where']);
227 if (count($database['groupby']) > 0)
229 $sql .= "\nGROUP BY ";
230 $sql .= implode(', ', $database['groupby']);
233 if (count($database['having']) > 0)
236 $sql .= implode("\n", $database['having']);
239 if (count($database['orderby']) > 0)
241 $sql .= "\nORDER BY ";
242 $sql .= implode(', ', $database['orderby']);
245 if (is_numeric($database['limit']))
248 $sql .= $this->limit($database['limit']);
254 public function escape_str($str)
256 if (!$this->db_config['escape'])
259 is_resource($this->link) or $this->connect();
260 //mssql_real_escape_string($str, $this->link); <-- this function doesn't exist
262 $characters = array('/\x00/', '/\x1a/', '/\n/', '/\r/', '/\\\/', '/\'/');
263 $replace = array('\\\x00', '\\x1a', '\\n', '\\r', '\\\\', "''");
264 return preg_replace($characters, $replace, $str);
267 public function list_tables()
269 $sql = 'SHOW TABLES FROM ['.$this->db_config['connection']['database'].']';
270 $result = $this->query($sql)->result(FALSE, MSSQL_ASSOC);
273 foreach ($result as $row)
275 $retval[] = current($row);
281 public function show_error()
283 return mssql_get_last_message($this->link);
286 public function list_fields($table)
290 foreach ($this->field_data($table) as $row)
292 // Make an associative array
293 $result[$row->Field] = $this->sql_type($row->Type);
299 public function field_data($table)
301 $query = $this->query("SELECT COLUMN_NAME AS Field, DATA_TYPE as Type FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$this->escape_table($table)."'", $this->link);
303 return $query->result_array(TRUE);
310 class Mssql_Result extends Database_Result {
312 // Fetch function and return type
313 protected $fetch_type = 'mssql_fetch_object';
314 protected $return_type = MSSQL_ASSOC;
317 * Sets up the result variables.
319 * @param resource query result
320 * @param resource database link
321 * @param boolean return objects or arrays
322 * @param string SQL query that was run
324 public function __construct($result, $link, $object = TRUE, $sql)
326 $this->result = $result;
328 // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query
329 if (is_resource($result))
331 $this->current_row = 0;
332 $this->total_rows = mssql_num_rows($this->result);
333 $this->fetch_type = ($object === TRUE) ? 'mssql_fetch_object' : 'mssql_fetch_array';
335 elseif (is_bool($result))
337 if ($result == FALSE)
340 throw new Kohana_Database_Exception('database.error', mssql_get_last_message($link).' - '.$sql);
344 // Its an DELETE, INSERT, REPLACE, or UPDATE querys
345 $last_id = mssql_query('SELECT @@IDENTITY AS last_id', $link);
346 $result = mssql_fetch_assoc($last_id);
347 $this->insert_id = $result['last_id'];
348 $this->total_rows = mssql_rows_affected($link);
353 $this->result($object);
360 * Destruct, the cleanup crew!
362 public function __destruct()
364 if (is_resource($this->result))
366 mssql_free_result($this->result);
370 public function result($object = TRUE, $type = MSSQL_ASSOC)
372 $this->fetch_type = ((bool) $object) ? 'mssql_fetch_object' : 'mssql_fetch_array';
374 // This check has to be outside the previous statement, because we do not
375 // know the state of fetch_type when $object = NULL
376 // NOTE - The class set by $type must be defined before fetching the result,
377 // autoloading is disabled to save a lot of stupid overhead.
378 if ($this->fetch_type == 'mssql_fetch_object')
380 $this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
384 $this->return_type = $type;
390 public function as_array($object = NULL, $type = MSSQL_ASSOC)
392 return $this->result_array($object, $type);
395 public function result_array($object = NULL, $type = MSSQL_ASSOC)
399 if (is_string($object))
403 elseif (is_bool($object))
405 if ($object === TRUE)
407 $fetch = 'mssql_fetch_object';
409 // NOTE - The class set by $type must be defined before fetching the result,
410 // autoloading is disabled to save a lot of stupid overhead.
411 $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
415 $fetch = 'mssql_fetch_array';
420 // Use the default config values
421 $fetch = $this->fetch_type;
423 if ($fetch == 'mssql_fetch_object')
425 $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
429 if (mssql_num_rows($this->result))
431 // Reset the pointer location to make sure things work properly
432 mssql_data_seek($this->result, 0);
434 while ($row = $fetch($this->result, $type))
440 return isset($rows) ? $rows : array();
443 public function list_fields()
445 $field_names = array();
446 while ($field = mssql_fetch_field($this->result))
448 $field_names[] = $field->name;
454 public function seek($offset)
456 if ( ! $this->offsetExists($offset))
459 return mssql_data_seek($this->result, $offset);
462 } // End mssql_Result Class