1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
database.php
См. документацию.
1<?php
2
9
11
13{
16
17 public
18 $escL = '"',
19 $escR = '"';
20
21 public $type = "PGSQL";
22
23 public function ToNumber($expr)
24 {
25 return "CASE WHEN " . $expr . "~E'^[0-9]+$' THEN " . $expr . "::integer ELSE 0 END";
26 }
27
28 public function DateFormatToDB($format, $field = false)
29 {
30 $this->DoConnect();
31 if ($field === false)
32 {
33 $field = "#FIELD#";
34 }
35 return "to_char(".$field.", '".$this->connection->getSqlHelper()->formatDate($format)."')";
36 }
37
38 public static function CurrentTimeFunction()
39 {
40 return "CURRENT_TIMESTAMP";
41 }
42
43 public static function CurrentDateFunction()
44 {
45 return "CURRENT_DATE";
46 }
47
48 public function DatetimeToTimestampFunction($fieldName)
49 {
50 $timeZone = "";
51 if (CTimeZone::Enabled())
52 {
53 static $diff = false;
54 if($diff === false)
55 $diff = CTimeZone::GetOffset();
56
57 if($diff <> 0)
58 $timeZone = $diff > 0? "+".$diff: $diff;
59 }
60 return "extract(epoch FROM $fieldName)".$timeZone;
61 }
62
63 public function DatetimeToDateFunction($strValue)
64 {
65 return 'cast(' . $strValue . ' as date)';
66 }
67
68 public function ForSqlLike($strValue, $iMaxLength = 0)
69 {
70 if ($iMaxLength > 0)
71 $strValue = mb_substr($strValue ?? '', 0, $iMaxLength);
72
73 $this->DoConnect();
74 return pg_escape_string($this->db_Conn, str_replace("\\", "\\\\", $strValue ?? ''));
75 }
76
77 protected function QueryInternal($strSql)
78 {
79 // Handle E_WARNING
80 set_error_handler(function () {
81 // noop
82 });
83
84 $result = pg_query($this->db_Conn, $strSql);
85
86 restore_error_handler();
87
88 return $result;
89 }
90
91 protected function GetError()
92 {
93 return pg_last_error($this->db_Conn);
94 }
95
96 protected function GetErrorCode()
97 {
98 if (preg_match("/ERROR:\\s*([^:]+):/i", $this->getError(), $matches))
99 {
100 return $matches[1];
101 }
102 return '';
103 }
104
105 public function GetTableFields($table)
106 {
107 if (!isset($this->column_cache[$table]))
108 {
109 $this->column_cache[$table] = array();
110 $this->DoConnect();
111
112 $sqlHelper = $this->connection->getSqlHelper();
113
114 $fullTextColumns = $this->connection->getTableFullTextFields($table);
115
116 $dbResult = $this->query("
117 SELECT
118 column_name,
119 data_type,
120 character_maximum_length
121 FROM
122 information_schema.columns
123 WHERE
124 table_catalog = '" . $sqlHelper->forSql($this->connection->getDatabase()) . "'
125 and table_schema = 'public'
126 and table_name = '" . $sqlHelper->forSql(mb_strtolower($table)) . "'
127 ORDER BY
128 ordinal_position
129 ");
130 $size = 0;
131 while ($field = $dbResult->fetch())
132 {
133 $fieldName = mb_strtoupper($field['COLUMN_NAME']);
134 $fieldType = $field['DATA_TYPE'];
135 switch ($fieldType)
136 {
137 case 'bigint':
138 case 'int8':
139 case 'bigserial':
140 case 'serial8':
141 $size = 8;
142 $type = "int";
143 break;
144 case 'integer':
145 case 'int':
146 case 'int4':
147 case 'serial':
148 case 'serial4':
149 $size = 4;
150 $type = "int";
151 break;
152 case 'smallint':
153 case 'int2':
154 case 'smallserial':
155 case 'serial2':
156 $size = 2;
157 $type = "int";
158 break;
159 case 'double precision':
160 case 'float4':
161 case 'float8':
162 case 'numeric':
163 case 'decimal':
164 case 'real':
165 $type = "real";
166 break;
167 case 'timestamp':
168 case 'timestamp without time zone':
169 case 'timestamptz':
170 case 'timestamp with time zone':
171 $type = "datetime";
172 break;
173 case 'date':
174 $type = "date";
175 break;
176 case 'bytea':
177 $type = "bytes";
178 break;
179 default:
180 $type = array_key_exists($fieldName, $fullTextColumns) ? "fulltext" : "string";
181 break;
182 }
183
184 $this->column_cache[$table][$fieldName] = array(
185 "NAME" => $fieldName,
186 "TYPE" => $type,
187 "MAX_LENGTH" => $field['CHARACTER_MAXIMUM_LENGTH'],
188 "INT_SIZE" => $size,
189 );
190 }
191 }
192 return $this->column_cache[$table];
193 }
194
195 public function PrepareInsert($strTableName, $arFields)
196 {
197 $strInsert1 = "";
198 $strInsert2 = "";
199
200 $this->DoConnect();
201 $sqlHelper = $this->connection->getSqlHelper();
202 $arColumns = $this->GetTableFields($strTableName);
203 foreach ($arColumns as $strColumnName => $arColumnInfo)
204 {
205 $type = $arColumnInfo["TYPE"];
206 if (isset($arFields[$strColumnName]))
207 {
208 if ($strInsert1 != '')
209 {
210 $strInsert1 .= ', ';
211 $strInsert2 .= ', ';
212 }
213
214 $value = $arFields[$strColumnName];
215
216 $strInsert1 .= $sqlHelper->quote($strColumnName);
217
218 if ($value === false)
219 {
220 $strInsert2 .= "NULL";
221 }
222 else
223 {
224 switch ($type)
225 {
226 case "datetime":
227 if ($value == '')
228 $strInsert2 .= "NULL";
229 else
230 $strInsert2 .= CDatabase::CharToDateFunction($value);
231 break;
232 case "date":
233 if ($value == '')
234 $strInsert2 .= "NULL";
235 else
236 $strInsert2 .= CDatabase::CharToDateFunction($value, "SHORT");
237 break;
238 case "int":
239 $value = intval($value);
240 if ($arColumnInfo['INT_SIZE'] == 2)
241 {
242 $value = max(-32768, min(+32767, $value));
243 }
244 elseif ($arColumnInfo['INT_SIZE'] == 4)
245 {
246 $value = max(-2147483648, min(+2147483647, $value));
247 }
248 $strInsert2 .= $value;
249 break;
250 case "real":
251 $value = doubleval($value);
252 if (!is_finite($value))
253 {
254 $value = 0;
255 }
256 $strInsert2 .= "'".$value."'";
257 break;
258 case "bytes":
259 $strInsert2 .= "decode('".bin2hex($value)."', 'hex')";
260 break;
261 case "fulltext":
262 $strInsert2 .= "safe_text_for_tsvector('".$sqlHelper->forSql($value, (int)$arColumnInfo['MAX_LENGTH'])."')";
263 break;
264 default:
265 if ($arColumnInfo['MAX_LENGTH'])
266 {
267 $strInsert2 .= "'" . $sqlHelper->forSql($value, $arColumnInfo['MAX_LENGTH']) . "'";
268 }
269 else
270 {
271 $strInsert2 .= "'" . $sqlHelper->forSql($value) . "'";
272 }
273 }
274 }
275 }
276 elseif (array_key_exists("~".$strColumnName, $arFields))
277 {
278 if ($strInsert1 != '')
279 {
280 $strInsert1 .= ', ';
281 $strInsert2 .= ', ';
282 }
283 $strInsert1 .= $sqlHelper->quote($strColumnName);
284 $strInsert2 .= $arFields["~".$strColumnName];
285 }
286 }
287
288 return array($strInsert1, $strInsert2);
289 }
290
291 public function PrepareUpdate($strTableName, $arFields, $strFileDir="", $lang = false, $strTableAlias = "")
292 {
293 $arBinds = array();
294 return $this->PrepareUpdateBind($strTableName, $arFields, $strFileDir, $lang, $arBinds, $strTableAlias);
295 }
296
297 public function PrepareUpdateBind($strTableName, $arFields, $strFileDir, $lang, &$arBinds, $strTableAlias = "")
298 {
299 $arBinds = array();
300 if ($strTableAlias != "")
301 $strTableAlias .= ".";
302 $strUpdate = "";
303
304 $this->DoConnect();
305 $sqlHelper = $this->connection->getSqlHelper();
306 $arColumns = $this->GetTableFields($strTableName);
307 foreach ($arColumns as $strColumnName => $arColumnInfo)
308 {
309 $type = $arColumnInfo["TYPE"];
310 if (isset($arFields[$strColumnName]))
311 {
312 if ($strUpdate != '')
313 {
314 $strUpdate .= ', ';
315 }
316
317 $value = $arFields[$strColumnName];
318
319 if ($value === false)
320 {
321 $strUpdate .= $strTableAlias . $sqlHelper->quote($strColumnName) . " = NULL";
322 }
323 elseif ($value instanceof SqlExpression)
324 {
325 $strUpdate .= $strTableAlias . $sqlHelper->quote($strColumnName) . " = " . $value->compile();
326 }
327 else
328 {
329 switch ($type)
330 {
331 case "int":
332 $value = intval($value);
333 if ($arColumnInfo['INT_SIZE'] == 2)
334 {
335 $value = max(-32768, min(+32767, $value));
336 }
337 elseif ($arColumnInfo['INT_SIZE'] == 4)
338 {
339 $value = max(-2147483648, min(+2147483647, $value));
340 }
341 break;
342 case "real":
343 $value = doubleval($value);
344 if(!is_finite($value))
345 {
346 $value = 0;
347 }
348 break;
349 case "datetime":
350 if($value == '')
351 $value = "NULL";
352 else
353 $value = CDatabase::CharToDateFunction($value, "FULL", $lang);
354 break;
355 case "date":
356 if($value == '')
357 $value = "NULL";
358 else
359 $value = CDatabase::CharToDateFunction($value, "SHORT", $lang);
360 break;
361 case "bytes":
362 $value = "decode('".bin2hex($value)."', 'hex')";
363 break;
364 case "fulltext":
365 $value = "safe_text_for_tsvector('".$sqlHelper->forSql($value, (int)$arColumnInfo['MAX_LENGTH'])."')";
366 break;
367 default:
368 if ($arColumnInfo['MAX_LENGTH'])
369 {
370 $value = "'" . $sqlHelper->forSql($value, $arColumnInfo['MAX_LENGTH']) . "'";
371 }
372 else
373 {
374 $value = "'" . $sqlHelper->ForSql($value) . "'";
375 }
376 }
377 $strUpdate .= $strTableAlias . $sqlHelper->quote($strColumnName) . " = " . $value;
378 }
379 }
380 elseif (is_set($arFields, "~".$strColumnName))
381 {
382 if ($strUpdate != '')
383 {
384 $strUpdate .= ', ';
385 }
386 $strUpdate .= $strTableAlias . $sqlHelper->quote($strColumnName) . " = " . $arFields["~".$strColumnName];
387 }
388 }
389
390 return $strUpdate;
391 }
392
393 public function PrepareUpdateJoin($strTableName, $arFields, $from, $where)
394 {
395 $tables = '';
396 foreach ($from as $join)
397 {
398 $tables .= ($tables ? ",\n " : "FROM\n ") . $join[0];
399 $where .= ($where ? "\nAND " : "\n") . $join[1];
400 }
401 $fields = '';
402 foreach ($arFields as $fieldName => $fieldValue)
403 {
404 $fields .= ($fields ? ",\n " : "") . $fieldName . '=' . $fieldValue;
405 }
406 $update = 'UPDATE ' . $strTableName . "\n"
407 . "SET\n " . $fields . "\n"
408 . $tables
409 . ($where ? "\nWHERE" . $where : "")
410 ;
411 return $update;
412 }
413
414 public function Insert($table, $arFields, $error_position="", $DEBUG=false, $EXIST_ID="", $ignore_errors=false)
415 {
416 if (!is_array($arFields))
417 return false;
418
419 $str1 = "";
420 $str2 = "";
421 foreach ($arFields as $field => $value)
422 {
423 $str1 .= ($str1 <> ""? ", ":"") . $this->quote($field);
424 if ((string)$value == '')
425 $str2 .= ($str2 <> ""? ", ":"")."''";
426 else
427 $str2 .= ($str2 <> ""? ", ":"").$value;
428 }
429
430 if ($EXIST_ID <> '')
431 {
432 $strSql = "INSERT INTO ".$table."(ID,".$str1.") VALUES ('".$this->ForSql($EXIST_ID)."',".$str2.") RETURNING ID";
433 }
434 else
435 {
436 $strSql = "INSERT INTO ".$table."(".$str1.") VALUES (".$str2.") RETURNING ID";
437 }
438
439 if ($DEBUG)
440 echo "<br>".htmlspecialcharsEx($strSql)."<br>";
441
442 $res = $this->Query($strSql, $ignore_errors, $error_position);
443
444 if ($res === false)
445 return false;
446
447 $row = $res->Fetch();
448
449 return intval(array_shift($row));
450 }
451
452 public function Add($tablename, $arFields, $arCLOBFields = Array(), $strFileDir="", $ignore_errors=false, $error_position="", $arOptions=array())
453 {
454 global $DB;
455
456 if(!isset($this) || !is_object($this) || !isset($this->type))
457 {
458 return $DB->Add($tablename, $arFields, $arCLOBFields, $strFileDir, $ignore_errors, $error_position, $arOptions);
459 }
460 else
461 {
462 $arInsert = $this->PrepareInsert($tablename, $arFields);
463 if (!isset($arFields["ID"]) || intval($arFields["ID"]) <= 0)
464 {
465 $strSql = "INSERT INTO ".$tablename."(".$arInsert[0].") VALUES (".$arInsert[1].") RETURNING ID";
466 $row = $this->Query($strSql, $ignore_errors, $error_position, $arOptions)->Fetch();
467 return intval(array_shift($row));
468 }
469 else
470 {
471 $strSql ="INSERT INTO ".$tablename."(".$arInsert[0].") VALUES(".$arInsert[1].")";
472 $this->Query($strSql, $ignore_errors, $error_position, $arOptions);
473 return intval($arFields["ID"]);
474 }
475 }
476 }
477
478 public function CreateIndex($indexName, $tableName, $columns, $unique = false, $fulltext = false)
479 {
480 foreach ($columns as $i => $columnName)
481 {
482 $columns[$i] = $this->quote($columnName);
483 }
484
485 if ($unique)
486 {
487 return $this->Query('CREATE UNIQUE INDEX ' . $this->quote($indexName) . ' ON ' . $this->quote($tableName) . '(' . implode(',', $columns) . ')', true);
488 }
489 elseif ($fulltext)
490 {
491 return $this->Query('CREATE INDEX ' . $this->quote($indexName) . ' ON ' . $this->quote($tableName) . ' USING GIN (to_tsvector(\'english\', ' . implode(',', $columns) . '))', true);
492 }
493 else
494 {
495 return $this->Query('CREATE INDEX ' . $this->quote($indexName) . ' ON ' . $this->quote($tableName) . '(' . implode(',', $columns) . ')', true);
496 }
497 }
498
499 protected function getThreadId()
500 {
501 return pg_get_pid($this->db_Conn);
502 }
503}
504
505class CDatabase extends CDatabasePgSql
506{
507}
Определения database.php:15
$result
Определения database.php:26
getError()
Определения database.php:973
DoConnect($connectionName='')
Определения database.php:239
Query($strSql, $bIgnoreErrors=false, $error_position="", $arOptions=[])
Определения database.php:556
CharToDateFunction($strValue, $strType="FULL", $lang=false)
Определения database.php:389
ForSql($strValue, $iMaxLength=0)
Определения database.php:697
quote($identifier)
Определения database.php:709
Определения database.php:13
$db_Conn
Определения database.php:15
PrepareUpdate($strTableName, $arFields, $strFileDir="", $lang=false, $strTableAlias="")
Определения database.php:291
ForSqlLike($strValue, $iMaxLength=0)
Определения database.php:68
GetErrorCode()
Определения database.php:96
GetTableFields($table)
Определения database.php:105
PrepareInsert($strTableName, $arFields)
Определения database.php:195
DatetimeToDateFunction($strValue)
Определения database.php:63
$escL
Определения database.php:18
PrepareUpdateBind($strTableName, $arFields, $strFileDir, $lang, &$arBinds, $strTableAlias="")
Определения database.php:297
Insert($table, $arFields, $error_position="", $DEBUG=false, $EXIST_ID="", $ignore_errors=false)
Определения database.php:414
static CurrentDateFunction()
Определения database.php:43
static CurrentTimeFunction()
Определения database.php:38
DatetimeToTimestampFunction($fieldName)
Определения database.php:48
$escR
Определения database.php:19
DateFormatToDB($format, $field=false)
Определения database.php:28
getThreadId()
Определения database.php:499
CreateIndex($indexName, $tableName, $columns, $unique=false, $fulltext=false)
Определения database.php:478
Add($tablename, $arFields, $arCLOBFields=Array(), $strFileDir="", $ignore_errors=false, $error_position="", $arOptions=array())
Определения database.php:452
ToNumber($expr)
Определения database.php:23
$type
Определения database.php:21
PrepareUpdateJoin($strTableName, $arFields, $from, $where)
Определения database.php:393
QueryInternal($strSql)
Определения database.php:77
GetError()
Определения database.php:91
$arFields
Определения dblapprove.php:5
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$res
Определения filter_act.php:7
global $DB
Определения cron_frame.php:29
if(!defined('SITE_ID')) $lang
Определения include.php:91
$arOptions
Определения structure.php:223
is_set($a, $k=false)
Определения tools.php:2133
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$i
Определения factura.php:643
$matches
Определения index.php:22
$dbResult
Определения updtr957.php:3
$fields
Определения yandex_run.php:501