Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
mssqlconnection.php
1<?php
2
3namespace Bitrix\Main\DB;
4
7
15{
16 /**********************************************************
17 * SqlHelper
18 **********************************************************/
19
20 protected function createSqlHelper()
21 {
22 return new MssqlSqlHelper($this);
23 }
24
25 /***********************************************************
26 * Connection and disconnection
27 ***********************************************************/
28
37 protected function connectInternal()
38 {
39 if ($this->isConnected)
40 return;
41
42 $connectionInfo = array(
43 "UID" => $this->login,
44 "PWD" => $this->password,
45 "Database" => $this->database,
46 "ReturnDatesAsStrings" => true,
47 /*"CharacterSet" => "utf-8",*/
48 );
49
50 if (($this->options & self::PERSISTENT) != 0)
51 $connectionInfo["ConnectionPooling"] = true;
52 else
53 $connectionInfo["ConnectionPooling"] = false;
54
55 $connection = sqlsrv_connect($this->host, $connectionInfo);
56
57 if (!$connection)
58 throw new ConnectionException('MS Sql connect error', $this->getErrorMessage());
59
60 $this->resource = $connection;
61 $this->isConnected = true;
62
63 // hide cautions
64 sqlsrv_configure("WarningsReturnAsErrors", 0);
65
66 $this->afterConnected();
67 }
68
75 protected function disconnectInternal()
76 {
77 if (!$this->isConnected)
78 return;
79
80 $this->isConnected = false;
81 sqlsrv_close($this->resource);
82 }
83
84 /*********************************************************
85 * Query
86 *********************************************************/
87
91 protected function queryInternal($sql, array $binds = null, \Bitrix\Main\Diag\SqlTrackerQuery $trackerQuery = null)
92 {
93 $this->connectInternal();
94
95 $trackerQuery?->startQuery($sql, $binds);
96
97 $result = sqlsrv_query($this->resource, $sql, array(), array("Scrollable" => 'forward'));
98
99 $trackerQuery?->finishQuery();
100
101 $this->lastQueryResult = $result;
102
103 if (!$result)
104 throw new SqlQueryException('MS Sql query error', $this->getErrorMessage(), $sql);
105
106 return $result;
107 }
108
112 protected function createResult($result, \Bitrix\Main\Diag\SqlTrackerQuery $trackerQuery = null)
113 {
114 return new MssqlResult($result, $this, $trackerQuery);
115 }
116
120 public function getInsertedId()
121 {
122 return $this->queryScalar("SELECT @@IDENTITY as ID");
123 }
124
128 public function getAffectedRowsCount()
129 {
130 return sqlsrv_rows_affected($this->lastQueryResult);
131 }
132
136 public function isTableExists($tableName)
137 {
138 $tableName = preg_replace("/[^A-Za-z0-9%_]+/i", "", $tableName);
139 $tableName = trim($tableName);
140
141 if ($tableName == '')
142 return false;
143
144 $result = $this->queryScalar(
145 "SELECT COUNT(TABLE_NAME) ".
146 "FROM INFORMATION_SCHEMA.TABLES ".
147 "WHERE TABLE_NAME LIKE '".$this->getSqlHelper()->forSql($tableName)."'"
148 );
149 return ($result > 0);
150 }
151
155 public function isIndexExists($tableName, array $columns)
156 {
157 return $this->getIndexName($tableName, $columns) !== null;
158 }
159
163 public function getIndexName($tableName, array $columns, $strict = false)
164 {
165 if (empty($columns))
166 {
167 return null;
168 }
169
170 //2005
171 //$rs = $this->query("SELECT index_id, COL_NAME(object_id, column_id) AS column_name, key_ordinal FROM SYS.INDEX_COLUMNS WHERE object_id=OBJECT_ID('".$this->forSql($tableName)."')", true);
172
173 //2000
174 $rs = $this->query(
175 "SELECT s.indid as index_id, s.keyno as key_ordinal, c.name column_name, si.name index_name ".
176 "FROM sysindexkeys s ".
177 " INNER JOIN syscolumns c ON s.id = c.id AND s.colid = c.colid ".
178 " INNER JOIN sysobjects o ON s.id = o.Id AND o.xtype = 'U' ".
179 " LEFT JOIN sysindexes si ON si.indid = s.indid AND si.id = s.id ".
180 "WHERE o.name = UPPER('".$this->getSqlHelper()->forSql($tableName)."')");
181
182 $indexes = array();
183 while ($ar = $rs->fetch())
184 {
185 $indexes[$ar["index_name"]][$ar["key_ordinal"] - 1] = $ar["column_name"];
186 }
187
188 return static::findIndex($indexes, $columns, $strict);
189 }
190
194 public function getTableFields($tableName)
195 {
196 if (!isset($this->tableColumnsCache[$tableName]))
197 {
198 $this->connectInternal();
199
200 $query = $this->queryInternal("SELECT TOP 0 * FROM ".$this->getSqlHelper()->quote($tableName));
201
202 $result = $this->createResult($query);
203
204 $this->tableColumnsCache[$tableName] = $result->getFields();
205 }
206 return $this->tableColumnsCache[$tableName];
207 }
208
212 public function createTable($tableName, $fields, $primary = array(), $autoincrement = array())
213 {
214 $sql = 'CREATE TABLE '.$this->getSqlHelper()->quote($tableName).' (';
215 $sqlFields = array();
216
217 foreach ($fields as $columnName => $field)
218 {
219 if (!($field instanceof ScalarField))
220 {
221 throw new ArgumentException(sprintf(
222 'Field `%s` should be an Entity\ScalarField instance', $columnName
223 ));
224 }
225
226 $realColumnName = $field->getColumnName();
227
228 $sqlFields[] = $this->getSqlHelper()->quote($realColumnName)
229 . ' ' . $this->getSqlHelper()->getColumnTypeByField($field)
230 . ' NOT NULL'
231 . (in_array($columnName, $autoincrement, true) ? ' IDENTITY (1, 1)' : '')
232 ;
233 }
234
235 $sql .= join(', ', $sqlFields);
236
237 if (!empty($primary))
238 {
239 foreach ($primary as &$primaryColumn)
240 {
241 $realColumnName = $fields[$primaryColumn]->getColumnName();
242 $primaryColumn = $this->getSqlHelper()->quote($realColumnName);
243 }
244
245 $sql .= ', PRIMARY KEY('.join(', ', $primary).')';
246 }
247
248 $sql .= ')';
249
250 $this->query($sql);
251 }
252
256 public function renameTable($currentName, $newName)
257 {
258 $this->query('EXEC sp_rename '.$this->getSqlHelper()->quote($currentName).', '.$this->getSqlHelper()->quote($newName));
259 }
260
264 public function dropTable($tableName)
265 {
266 $this->query('DROP TABLE '.$this->getSqlHelper()->quote($tableName));
267 }
268
269 /*********************************************************
270 * Transaction
271 *********************************************************/
272
276 public function startTransaction()
277 {
278 $this->connectInternal();
279 sqlsrv_begin_transaction($this->resource);
280 }
281
285 public function commitTransaction()
286 {
287 $this->connectInternal();
288 sqlsrv_commit($this->resource);
289 }
290
294 public function rollbackTransaction()
295 {
296 $this->connectInternal();
297 sqlsrv_rollback($this->resource);
298 }
299
300 /*********************************************************
301 * Type, version, cache, etc.
302 *********************************************************/
303
307 public function getType()
308 {
309 return "mssql";
310 }
311
315 public function getVersion()
316 {
317 if ($this->version == null)
318 {
319 $version = $this->queryScalar("SELECT @@VERSION");
320 if ($version != null)
321 {
322 $version = trim($version);
323 $this->versionExpress = (mb_strpos($version, "Express Edition") > 0);
324 preg_match("#[0-9]+\\.[0-9]+\\.[0-9]+#", $version, $arr);
325 $this->version = $arr[0];
326 }
327 }
328
329 return array($this->version, $this->versionExpress);
330 }
331
335 public function getErrorMessage()
336 {
337 $errors = "";
338 foreach (sqlsrv_errors(SQLSRV_ERR_ERRORS) as $error)
339 {
340 $errors .= "SQLSTATE: ".$error['SQLSTATE'].";"." code: ".$error['code']."; message: ".$error[ 'message']."\n";
341 }
342 return $errors;
343 }
344}
getIndexName($tableName, array $columns, $strict=false)
renameTable($currentName, $newName)
isIndexExists($tableName, array $columns)
createResult($result, \Bitrix\Main\Diag\SqlTrackerQuery $trackerQuery=null)
queryInternal($sql, array $binds=null, \Bitrix\Main\Diag\SqlTrackerQuery $trackerQuery=null)
createTable($tableName, $fields, $primary=array(), $autoincrement=array())