forked from xrado/kohana-mssql
/
mssql.php
244 lines (203 loc) · 6.13 KB
/
mssql.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
<?php defined('SYSPATH') or die('No direct script access.');
/**
* MsSQL database connection.
*
* @author Kohana Team, xrado
*/
class Kohana_Database_MsSQL extends Database_PDO {
public function query($type, $sql, $as_object = FALSE, array $params = NULL)
{
// Make sure the database is connected
$this->_connection or $this->connect();
// Mssql specific
if(preg_match("/OFFSET ([0-9]+)/i",$sql,$matches))
{
list($replace,$offset) = $matches;
$sql = str_replace($replace,'',$sql);
}
if(preg_match("/LIMIT ([0-9]+)/i",$sql,$matches))
{
list($replace,$limit) = $matches;
$sql = str_replace($replace,'',$sql);
}
if(isset($limit) || isset($offset))
{
if (!isset($offset))
{
$sql = preg_replace("/^(SELECT|DELETE|UPDATE)\s/i", "$1 TOP " . $limit . ' ', $sql);
}
else
{
$ob_count = (int)preg_match_all('/ORDER BY/i',$sql,$ob_matches,PREG_OFFSET_CAPTURE);
if($ob_count < 1)
{
$over = 'ORDER BY (SELECT 0)';
}
else
{
$ob_last = array_pop($ob_matches[0]);
$orderby = strrchr($sql, $ob_last[0]);
$over = preg_replace('/[^,\s]*\.([^,\s]*)/i', 'inner_tbl.$1', $orderby);
// Remove ORDER BY clause from $sql
$sql = substr($sql, 0, $ob_last[1]);
}
// Add ORDER BY clause as an argument for ROW_NUMBER()
$sql = "SELECT ROW_NUMBER() OVER ($over) AS KOHANA_DB_ROWNUM, * FROM ($sql) AS inner_tbl";
$start = $offset + 1;
$end = $offset + $limit;
$sql = "WITH outer_tbl AS ($sql) SELECT * FROM outer_tbl WHERE KOHANA_DB_ROWNUM BETWEEN $start AND $end";
}
}
if ( ! empty($this->_config['profiling']))
{
// Benchmark this query for the current instance
$benchmark = Profiler::start("Database ({$this->_instance})", $sql);
}
try
{
$result = $this->_connection->query($sql);
}
catch (Exception $e)
{
if (isset($benchmark))
{
// This benchmark is worthless
Profiler::delete($benchmark);
}
$errArr = $this->_connection->errorInfo();
$resultTextError = $this->_connection->query( "select * from sys.messages where language_id=1033 and message_id=".arr::get($errArr, 1, 0) )->fetchAll();
// Convert the exception in a database exception
throw new Database_Exception('[:code] :error ( :info )', array(
':code' => $e->getCode(),
':error' => $e->getMessage(),
#':query' => $sql,
':info' => arr::get($resultTextError[0], 'text')
), $e->getCode());
}
if (isset($benchmark))
{
Profiler::stop($benchmark);
}
// Set the last query
$this->last_query = $sql;
if ($type === Database::SELECT)
{
// Convert the result into an array, as PDOStatement::rowCount is not reliable
if ($as_object === FALSE)
{
$result->setFetchMode(PDO::FETCH_ASSOC);
}
elseif (is_string($as_object))
{
$result->setFetchMode(PDO::FETCH_CLASS, $as_object, $params);
}
else
{
$result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
}
$result = $result->fetchAll();
// Return an iterator of results
return new Database_Result_Cached($result, $sql, $as_object, $params);
}
elseif ($type === Database::INSERT)
{
// Return a list of insert id and rows created
return array(
$this->insert_id(),
$result->rowCount(),
);
}
else
{
// Return the number of rows affected
return $result->rowCount();
}
}
public function insert_id()
{
$table = preg_match('/^insert\s+into\s+(.*?)\s+/i',$this->last_query,$match) ? arr::get($match,1) : NULL;
if (!empty($table)) $query = 'SELECT IDENT_CURRENT(\'' . $this->quote_identifier($table) . '\') AS insert_id';
else $query = 'SELECT SCOPE_IDENTITY() AS insert_id';
$data = $this->query(Database::SELECT,$query,FALSE)->current();
return Arr::get($data,'insert_id');
}
public function datatype($type)
{
static $types = array
(
'nvarchar' => array('type' => 'string'),
'ntext' => array('type' => 'string'),
'tinyint' => array('type' => 'int', 'min' => '0', 'max' => '255'),
);
if (isset($types[$type]))
return $types[$type];
return parent::datatype($type);
}
public function begin($mode = NULL)
{
// Make sure the database is connected
$this->_connection or $this->connect();
return $this->_connection->beginTransaction();
}
public function commit()
{
// Make sure the database is connected
$this->_connection or $this->connect();
return $this->_connection->commit();
}
public function rollback()
{
// Make sure the database is connected
$this->_connection or $this->connect();
return $this->_connection->rollBack();
}
public function list_tables($like = NULL)
{
if (is_string($like))
{
// Search for table names
$result = $this->query(Database::SELECT, 'SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '.$this->quote($like), FALSE)->as_array();
}
else
{
// Find all table names
$result = $this->query(Database::SELECT, 'SELECT * FROM INFORMATION_SCHEMA.TABLES', FALSE)->as_array();
}
$tables = array();
foreach ($result as $row)
{
// Get the table name from the results
$tables[] = $row['TABLE_NAME'];
}
return $tables;
}
public function list_columns($table, $like = NULL, $add_prefix = TRUE)
{
if (is_string($like))
{
$results = $this->query(Database::SELECT,'SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME LIKE '.$this->quote($table), FALSE);
}
else
{
$results = $this->query(Database::SELECT,'SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '.$this->quote($table), FALSE);
}
$result = array();
foreach ($results as $row)
{
list($type, $length) = $this->_parse_type($row['DATA_TYPE']);
$column = $this->datatype($type);
$column['column_name'] = $row['COLUMN_NAME'];
$column['column_default'] = $row['COLUMN_DEFAULT'];
$column['data_type'] = $type;
$column['is_nullable'] = ($row['IS_NULLABLE'] == 'YES');
$column['ordinal_position'] = $row['ORDINAL_POSITION'];
if($row['CHARACTER_MAXIMUM_LENGTH'])
{
$column['character_maximum_length'] = $row['CHARACTER_MAXIMUM_LENGTH'];
}
$result[$row['COLUMN_NAME']] = $column;
}
return $result;
}
public function set_charset($charset){}
}