Merge branch 'maint/7.0'
[ninja.git] / system / libraries / drivers / Database / Mssql.php
blob401770a2be0f7805b912593715bbef3091ee8b4d
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3 * MSSQL Database Driver
5 * @package Core
6 * @author Kohana Team
7 * @copyright (c) 2007-2008 Kohana Team
8 * @license http://kohanaphp.com/license.html
9 */
10 class Database_Mssql_Driver extends Database_Driver
12 /**
13 * Database connection link
15 protected $link;
17 /**
18 * Database configuration
20 protected $db_config;
22 /**
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');
34 /**
35 * Closes the database connection.
37 public function __destruct()
39 is_resource($this->link) and mssql_close($this->link);
42 /**
43 * Make the connection
45 * @return return connection
47 public function connect()
49 // Check if link already exists
50 if (is_resource($this->link))
51 return $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->config['connection']['pass'] = NULL;
79 return $this->link;
82 return FALSE;
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(self::$query_cache[$hash]))
94 // Set the cached object
95 self::$query_cache[$hash] = new Mssql_Result(mssql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql);
98 // Return the cached query
99 return self::$query_cache[$hash];
102 return new Mssql_Result(mssql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql);
105 public function escape_table($table)
107 if (stripos($table, ' AS ') !== FALSE)
109 // Force 'AS' to uppercase
110 $table = str_ireplace(' AS ', ' AS ', $table);
112 // Runs escape_table on both sides of an AS statement
113 $table = array_map(array($this, __FUNCTION__), explode(' AS ', $table));
115 // Re-create the AS statement
116 return implode(' AS ', $table);
118 return '['.str_replace('.', '[.]', $table).']';
121 public function escape_column($column)
123 if (!$this->db_config['escape'])
124 return $column;
126 if (strtolower($column) == 'count(*)' OR $column == '*')
127 return $column;
129 // This matches any modifiers we support to SELECT.
130 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))
132 if (stripos($column, ' AS ') !== FALSE)
134 // Force 'AS' to uppercase
135 $column = str_ireplace(' AS ', ' AS ', $column);
137 // Runs escape_column on both sides of an AS statement
138 $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column));
140 // Re-create the AS statement
141 return implode(' AS ', $column);
144 return preg_replace('/[^.*]+/', '[$0]', $column);
147 $parts = explode(' ', $column);
148 $column = '';
150 for ($i = 0, $c = count($parts); $i < $c; $i++)
152 // The column is always last
153 if ($i == ($c - 1))
155 $column .= preg_replace('/[^.*]+/', '[$0]', $parts[$i]);
157 else // otherwise, it's a modifier
159 $column .= $parts[$i].' ';
162 return $column;
166 * Limit in SQL Server 2000 only uses the keyword
167 * 'TOP'; 2007 may have an offset keyword, but
168 * I am unsure - for pagination style limit,offset
169 * functionality, a fancy query needs to be built.
171 * @param unknown_type $limit
172 * @return unknown
174 public function limit($limit, $offset=null)
176 return 'TOP '.$limit;
179 public function compile_select($database)
181 $sql = ($database['distinct'] == TRUE) ? 'SELECT DISTINCT ' : 'SELECT ';
182 $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*';
184 if (count($database['from']) > 0)
186 // Escape the tables
187 $froms = array();
188 foreach ($database['from'] as $from)
189 $froms[] = $this->escape_column($from);
190 $sql .= "\nFROM ";
191 $sql .= implode(', ', $froms);
194 if (count($database['join']) > 0)
196 foreach($database['join'] AS $join)
198 $sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions'];
202 if (count($database['where']) > 0)
204 $sql .= "\nWHERE ";
207 $sql .= implode("\n", $database['where']);
209 if (count($database['groupby']) > 0)
211 $sql .= "\nGROUP BY ";
212 $sql .= implode(', ', $database['groupby']);
215 if (count($database['having']) > 0)
217 $sql .= "\nHAVING ";
218 $sql .= implode("\n", $database['having']);
221 if (count($database['orderby']) > 0)
223 $sql .= "\nORDER BY ";
224 $sql .= implode(', ', $database['orderby']);
227 if (is_numeric($database['limit']))
229 $sql .= "\n";
230 $sql .= $this->limit($database['limit']);
233 return $sql;
236 public function escape_str($str)
238 if (!$this->db_config['escape'])
239 return $str;
241 is_resource($this->link) or $this->connect();
242 //mssql_real_escape_string($str, $this->link); <-- this function doesn't exist
244 $characters = array('/\x00/', '/\x1a/', '/\n/', '/\r/', '/\\\/', '/\'/');
245 $replace = array('\\\x00', '\\x1a', '\\n', '\\r', '\\\\', "''");
246 return preg_replace($characters, $replace, $str);
249 public function list_tables(Database $db)
251 $sql = 'SHOW TABLES FROM ['.$this->db_config['connection']['database'].']';
252 $result = $this->query($sql)->result(FALSE, MSSQL_ASSOC);
254 $retval = array();
255 foreach ($result as $row)
257 $retval[] = current($row);
260 return $retval;
263 public function show_error()
265 return mssql_get_last_message($this->link);
268 public function list_fields($table)
270 static $tables;
272 if (empty($tables[$table]))
274 foreach ($this->field_data($table) as $row)
276 // Make an associative array
277 $tables[$table][$row->Field] = $this->sql_type($row->Type);
281 return $tables[$table];
284 public function field_data($table)
286 $columns = array();
288 if ($query = MSSQL_query('SHOW COLUMNS FROM '.$this->escape_table($table), $this->link))
290 if (MSSQL_num_rows($query) > 0)
292 while ($row = MSSQL_fetch_object($query))
294 $columns[] = $row;
299 return $columns;
304 * MSSQL Result
306 class Mssql_Result extends Database_Result {
308 // Fetch function and return type
309 protected $fetch_type = 'mssql_fetch_object';
310 protected $return_type = MSSQL_ASSOC;
313 * Sets up the result variables.
315 * @param resource query result
316 * @param resource database link
317 * @param boolean return objects or arrays
318 * @param string SQL query that was run
320 public function __construct($result, $link, $object = TRUE, $sql)
322 $this->result = $result;
324 // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query
325 if (is_resource($result))
327 $this->current_row = 0;
328 $this->total_rows = mssql_num_rows($this->result);
329 $this->fetch_type = ($object === TRUE) ? 'mssql_fetch_object' : 'mssql_fetch_array';
331 elseif (is_bool($result))
333 if ($result == FALSE)
335 // SQL error
336 throw new Kohana_Database_Exception('database.error', mssql_get_last_message($link).' - '.$sql);
338 else
340 // Its an DELETE, INSERT, REPLACE, or UPDATE querys
341 $last_id = mssql_query('SELECT @@IDENTITY AS last_id', $link);
342 $result = mssql_fetch_assoc($last_id);
343 $this->insert_id = $result['last_id'];
344 $this->total_rows = mssql_rows_affected($link);
348 // Set result type
349 $this->result($object);
351 // Store the SQL
352 $this->sql = $sql;
356 * Destruct, the cleanup crew!
358 public function __destruct()
360 if (is_resource($this->result))
362 mssql_free_result($this->result);
366 public function result($object = TRUE, $type = MSSQL_ASSOC)
368 $this->fetch_type = ((bool) $object) ? 'mssql_fetch_object' : 'mssql_fetch_array';
370 // This check has to be outside the previous statement, because we do not
371 // know the state of fetch_type when $object = NULL
372 // NOTE - The class set by $type must be defined before fetching the result,
373 // autoloading is disabled to save a lot of stupid overhead.
374 if ($this->fetch_type == 'mssql_fetch_object')
376 $this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
378 else
380 $this->return_type = $type;
383 return $this;
386 public function as_array($object = NULL, $type = MSSQL_ASSOC)
388 return $this->result_array($object, $type);
391 public function result_array($object = NULL, $type = MSSQL_ASSOC)
393 $rows = array();
395 if (is_string($object))
397 $fetch = $object;
399 elseif (is_bool($object))
401 if ($object === TRUE)
403 $fetch = 'mssql_fetch_object';
405 // NOTE - The class set by $type must be defined before fetching the result,
406 // autoloading is disabled to save a lot of stupid overhead.
407 $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
409 else
411 $fetch = 'mssql_fetch_array';
414 else
416 // Use the default config values
417 $fetch = $this->fetch_type;
419 if ($fetch == 'mssql_fetch_object')
421 $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
425 if (mssql_num_rows($this->result))
427 // Reset the pointer location to make sure things work properly
428 mssql_data_seek($this->result, 0);
430 while ($row = $fetch($this->result, $type))
432 $rows[] = $row;
436 return isset($rows) ? $rows : array();
439 public function list_fields()
441 $field_names = array();
442 while ($field = mssql_fetch_field($this->result))
444 $field_names[] = $field->name;
447 return $field_names;
450 public function seek($offset)
452 if ( ! $this->offsetExists($offset))
453 return FALSE;
455 return mssql_data_seek($this->result, $offset);
458 } // End mssql_Result Class