1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
mssqlsqlhelper.php
См. документацию.
1<?php
2
3namespace Bitrix\Main\DB;
4
5use Bitrix\Main;
6use Bitrix\Main\Type;
7use Bitrix\Main\ORM;
8use Bitrix\Main\ORM\Fields\ScalarField;
9
11{
15 public function getLeftQuote()
16 {
17 return '[';
18 }
19
23 public function getRightQuote()
24 {
25 return ']';
26 }
27
31 public function getAliasLength()
32 {
33 return 28;
34 }
35
39 public function getQueryDelimiter()
40 {
41 return "\nGO";
42 }
43
47 public function forSql($value, $maxLength = 0)
48 {
49 if ($maxLength > 0)
50 {
51 $value = mb_substr($value, 0, $maxLength);
52 }
53 $value = str_replace("'", "''", $value);
54 $value = str_replace("\x00", "", $value);
55 return $value;
56 }
57
62 {
63 return "GETDATE()";
64 }
65
69 public function getCurrentDateFunction()
70 {
71 return "convert(datetime, cast(year(getdate()) as varchar(4)) + '-' + cast(month(getdate()) as varchar(2)) + '-' + cast(day(getdate()) as varchar(2)), 120)";
72 }
73
77 public function addSecondsToDateTime($seconds, $from = null)
78 {
79 if ($from === null)
80 {
81 $from = static::getCurrentDateTimeFunction();
82 }
83
84 return 'DATEADD(second, '.$seconds.', '.$from.')';
85 }
86
90 public function getDatetimeToDateFunction($value)
91 {
92 return 'DATEADD(dd, DATEDIFF(dd, 0, '.$value.'), 0)';
93 }
94
98 public function formatDate($format, $field = null)
99 {
100 if ($field === null)
101 {
102 return '';
103 }
104
105 $result = array();
106
107 foreach (preg_split("#(YYYY|MMMM|MM|MI|M|DD|HH|H|GG|G|SS|TT|T)#", $format, -1, PREG_SPLIT_DELIM_CAPTURE) as $part)
108 {
109 switch ($part)
110 {
111 case "YYYY":
112 $result[] = "\n\tCONVERT(varchar(4),DATEPART(yyyy, $field))";
113 break;
114 case "MMMM":
115 $result[] = "\n\tdatename(mm, $field)";
116 break;
117 case "MM":
118 $result[] = "\n\tREPLICATE('0',2-LEN(DATEPART(mm, $field)))+CONVERT(varchar(2),DATEPART(mm, $field))";
119 break;
120 case "MI":
121 $result[] = "\n\tREPLICATE('0',2-LEN(DATEPART(mi, $field)))+CONVERT(varchar(2),DATEPART(mi, $field))";
122 break;
123 case "M":
124 $result[] = "\n\tCONVERT(varchar(3), $field,7)";
125 break;
126 case "DD":
127 $result[] = "\n\tREPLICATE('0',2-LEN(DATEPART(dd, $field)))+CONVERT(varchar(2),DATEPART(dd, $field))";
128 break;
129 case "HH":
130 case "GG":
131 $result[] = "\n\tREPLICATE('0',2-LEN(DATEPART(hh, $field)))+CONVERT(varchar(2),DATEPART(hh, $field))";
132 break;
133 case "H":
134 case "G":
135 $result[] = "\n\tCASE WHEN DATEPART(HH, $field) < 13 THEN RIGHT(REPLICATE('0',2) + CAST(datepart(HH, $field) AS VARCHAR(2)),2) ELSE RIGHT(REPLICATE('0',2) + CAST(datepart(HH, dateadd(HH, -12, $field)) AS VARCHAR(2)), 2) END";
136 break;
137 case "SS":
138 $result[] = "\n\tREPLICATE('0',2-LEN(DATEPART(ss, $field)))+CONVERT(varchar(2),DATEPART(ss, $field))";
139 break;
140 case "TT":
141 case "T":
142 $result[] = "\n\tCASE WHEN DATEPART(HH, $field) < 12 THEN 'AM' ELSE 'PM' END";
143 break;
144 default:
145 $result[] = "'".$part."'";
146 break;
147 }
148 }
149
150 return implode("+", $result);
151 }
152
156 public function getSubstrFunction($str, $from, $length = null)
157 {
158 $sql = 'SUBSTRING('.$str.', '.$from;
159
160 if (!is_null($length))
161 $sql .= ', '.$length;
162 else
163 $sql .= ', LEN('.$str.') + 1 - '.$from;
164
165 return $sql.')';
166 }
167
171 public function getConcatFunction()
172 {
173 return implode(" + ", func_get_args());
174 }
175
179 public function getIsNullFunction($expression, $result)
180 {
181 return "ISNULL(".$expression.", ".$result.")";
182 }
183
187 public function getLengthFunction($field)
188 {
189 return "LEN(".$field.")";
190 }
191
195 public function getCharToDateFunction($value)
196 {
197 return "CONVERT(datetime, '".$value."', 120)";
198 }
199
203 public function getDateToCharFunction($fieldName)
204 {
205 return "CONVERT(varchar(19), ".$fieldName.", 120)";
206 }
207
211 public function castToChar($fieldName)
212 {
213 return 'CAST('.$fieldName.' AS varchar)';
214 }
215
219 public function softCastTextToChar($fieldName)
220 {
221 return 'CONVERT(VARCHAR(8000), '.$fieldName.')';
222 }
223
227 public function getConverter(ScalarField $field)
228 {
229 if ($field instanceof ORM\Fields\DatetimeField)
230 {
231 return array($this, "convertFromDbDateTime");
232 }
233 elseif ($field instanceof ORM\Fields\DateField)
234 {
235 return array($this, "convertFromDbDate");
236 }
237 elseif ($field instanceof ORM\Fields\StringField)
238 {
239 return array($this, "convertFromDbString");
240 }
241 else
242 {
243 return parent::getConverter($field);
244 }
245 }
246
250 public function convertFromDbDateTime($value)
251 {
252 if ($value !== null)
253 {
254 $value = new Type\DateTime(mb_substr($value, 0, 19), "Y-m-d H:i:s");
255 }
256
257 return $value;
258 }
259
263 public function convertFromDbDate($value)
264 {
265 if($value !== null)
266 {
267 $value = new Type\Date($value, "Y-m-d");
268 }
269
270 return $value;
271 }
272
276 public function convertFromDbString($value, $length = null)
277 {
278 if ($value !== null)
279 {
280 if(preg_match("#^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\$#", $value))
281 {
282 return new Type\DateTime($value, "Y-m-d H:i:s");
283 }
284 }
285
286 return parent::convertFromDbString($value, $length);
287 }
288
292 public function getColumnTypeByField(ScalarField $field)
293 {
294 if ($field instanceof ORM\Fields\IntegerField)
295 {
296 return 'int';
297 }
298 elseif ($field instanceof ORM\Fields\FloatField)
299 {
300 return 'float';
301 }
302 elseif ($field instanceof ORM\Fields\DatetimeField)
303 {
304 return 'datetime';
305 }
306 elseif ($field instanceof ORM\Fields\DateField)
307 {
308 return 'date';
309 }
310 elseif ($field instanceof ORM\Fields\TextField)
311 {
312 return 'text';
313 }
314 elseif ($field instanceof ORM\Fields\BooleanField)
315 {
316 $values = $field->getValues();
317
318 if (preg_match('/^[0-9]+$/', $values[0]) && preg_match('/^[0-9]+$/', $values[1]))
319 {
320 return 'int';
321 }
322 else
323 {
324 $falseLen = strlen($values[0]);
325 $trueLen = strlen($values[1]);
326 if ($falseLen === 1 && $trueLen === 1)
327 {
328 return 'char(1)';
329 }
330 return 'varchar(' . max($falseLen, $trueLen) . ')';
331 }
332 }
333 elseif ($field instanceof ORM\Fields\EnumField)
334 {
335 return 'varchar('.max(array_map('strlen', $field->getValues())).')';
336 }
337 else
338 {
339 // string by default
340 $defaultLength = false;
341 foreach ($field->getValidators() as $validator)
342 {
343 if ($validator instanceof ORM\Fields\Validators\LengthValidator)
344 {
345 if ($defaultLength === false || $defaultLength > $validator->getMax())
346 {
347 $defaultLength = $validator->getMax();
348 }
349 }
350 }
351 return 'varchar('.($defaultLength > 0? $defaultLength: 255).')';
352 }
353 }
354
358 public function getFieldByColumnType($name, $type, array $parameters = null)
359 {
360 switch($type)
361 {
362 case 4:
363 case 5:
364 case -6:
365 //int SQL_INTEGER (4)
366 //smallint SQL_SMALLINT (5)
367 //tinyint SQL_TINYINT (-6)
368 return new ORM\Fields\IntegerField($name);
369
370 case 2:
371 case 3:
372 case 6:
373 case 7:
374 //numeric SQL_NUMERIC (2)
375 //decimal SQL_DECIMAL (3)
376 //smallmoney SQL_DECIMAL (3)
377 //money SQL_DECIMAL (3)
378 //float SQL_FLOAT (6)
379 //real SQL_REAL (7)
380 return new ORM\Fields\FloatField($name, array("scale" => $parameters["scale"]));
381
382 case 93:
383 //datetime - SQL_TYPE_TIMESTAMP (93)
384 //datetime2 - SQL_TYPE_TIMESTAMP (93)
385 //smalldatetime - SQL_TYPE_TIMESTAMP (93)
387
388 case 91:
389 //date - SQL_TYPE_DATE (91)
390 return new ORM\Fields\DateField($name);
391 }
392 //bigint SQL_BIGINT (-5)
393 //binary SQL_BINARY (-2)
394 //bit SQL_BIT (-7)
395 //char SQL_CHAR (1)
396 //datetimeoffset SQL_SS_TIMESTAMPOFFSET (-155)
397 //image SQL_LONGVARBINARY (-4)
398 //nchar SQL_WCHAR (-8)
399 //ntext SQL_WLONGVARCHAR (-10)
400 //nvarchar SQL_WVARCHAR (-9)
401 //text SQL_LONGVARCHAR (-1)
402 //time SQL_SS_TIME2 (-154)
403 //timestamp SQL_BINARY (-2)
404 //udt SQL_SS_UDT (-151)
405 //uniqueidentifier SQL_GUID (-11)
406 //varbinary SQL_VARBINARY (-3)
407 //varchar SQL_VARCHAR (12)
408 //xml SQL_SS_XML (-152)
409 return new ORM\Fields\StringField($name, array("size" => $parameters["size"]));
410 }
411
415 public function getTopSql($sql, $limit, $offset = 0)
416 {
417 $offset = intval($offset);
418 $limit = intval($limit);
419
420 if ($offset > 0 && $limit <= 0)
421 throw new Main\ArgumentException("Limit must be set if offset is set");
422
423 if ($limit > 0)
424 {
425 if ($offset <= 0)
426 {
427 $sql = preg_replace("/^\\s*SELECT/i", "SELECT TOP ".$limit, $sql);
428 }
429 else
430 {
431 $orderBy = '';
432 $sqlTmp = $sql;
433
434 preg_match_all("#\\sorder\\s+by\\s#i", $sql, $matches, PREG_OFFSET_CAPTURE);
435 if (isset($matches[0]) && is_array($matches[0]) && !empty($matches[0]))
436 {
437 $idx = $matches[0][count($matches[0]) - 1][1];
438 $s = mb_substr($sql, $idx);
439 if (substr_count($s, '(') === substr_count($s, ')'))
440 {
441 $orderBy = $s;
442 $sqlTmp = mb_substr($sql, 0, $idx);
443 }
444 }
445
446 if ($orderBy === '')
447 {
448 $orderBy = "ORDER BY (SELECT 1)";
449 $sqlTmp = $sql;
450 }
451
452 // ROW_NUMBER() Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
453 $sqlTmp = preg_replace(
454 "/^\\s*SELECT/i",
455 "SELECT ROW_NUMBER() OVER (".$orderBy.") AS ROW_NUMBER_ALIAS,",
456 $sqlTmp
457 );
458
459 $sql =
460 "WITH ROW_NUMBER_QUERY_ALIAS AS (".$sqlTmp.") ".
461 "SELECT * ".
462 "FROM ROW_NUMBER_QUERY_ALIAS ".
463 "WHERE ROW_NUMBER_ALIAS BETWEEN ".($offset + 1)." AND ".($offset + $limit);
464 }
465 }
466 return $sql;
467 }
468
472 public function prepareMerge($tableName, array $primaryFields, array $insertFields, array $updateFields)
473 {
474 $insert = $this->prepareInsert($tableName, $insertFields);
475
476 $updateColumns = array();
477 $sourceSelectValues = array();
478 $sourceSelectColumns = array();
479 $targetConnectColumns = array();
480 $tableFields = $this->connection->getTableFields($tableName);
481 foreach($tableFields as $columnName => $tableField)
482 {
483 $quotedName = $this->quote($columnName);
484 if (in_array($columnName, $primaryFields))
485 {
486 $sourceSelectValues[] = $this->convertToDb($insertFields[$columnName], $tableField);
487 $sourceSelectColumns[] = $quotedName;
488 if($insertFields[$columnName] === null)
489 {
490 //can't just compare NULLs
491 $targetConnectColumns[] = "(source.".$quotedName." IS NULL AND target.".$quotedName." IS NULL)";
492 }
493 else
494 {
495 $targetConnectColumns[] = "(source.".$quotedName." = target.".$quotedName.")";
496 }
497 }
498
499 if (isset($updateFields[$columnName]) || array_key_exists($columnName, $updateFields))
500 {
501 $updateColumns[] = "target.".$quotedName.' = '.$this->convertToDb($updateFields[$columnName], $tableField);
502 }
503 }
504
505 if (
506 $insert && $insert[0] != "" && $insert[1] != ""
507 && $updateColumns
508 && $sourceSelectValues && $sourceSelectColumns && $targetConnectColumns
509 )
510 {
511 $sql = "
512 MERGE INTO ".$this->quote($tableName)." AS target USING (
513 SELECT ".implode(", ", $sourceSelectValues)."
514 ) AS source (
515 ".implode(", ", $sourceSelectColumns)."
516 )
517 ON
518 (
519 ".implode(" AND ", $targetConnectColumns)."
520 )
521 WHEN MATCHED THEN
522 UPDATE SET ".implode(", ", $updateColumns)."
523 WHEN NOT MATCHED THEN
524 INSERT (".$insert[0].")
525 VALUES (".$insert[1].")
526 ;
527 ";
528 }
529 else
530 {
531 $sql = "";
532 }
533
534 return array(
535 $sql
536 );
537 }
538}
$type
Определения options.php:106
softCastTextToChar($fieldName)
Определения mssqlsqlhelper.php:219
getTopSql($sql, $limit, $offset=0)
Определения mssqlsqlhelper.php:415
getIsNullFunction($expression, $result)
Определения mssqlsqlhelper.php:179
getDateToCharFunction($fieldName)
Определения mssqlsqlhelper.php:203
formatDate($format, $field=null)
Определения mssqlsqlhelper.php:98
getDatetimeToDateFunction($value)
Определения mssqlsqlhelper.php:90
convertFromDbString($value, $length=null)
Определения mssqlsqlhelper.php:276
castToChar($fieldName)
Определения mssqlsqlhelper.php:211
getFieldByColumnType($name, $type, array $parameters=null)
Определения mssqlsqlhelper.php:358
getColumnTypeByField(ScalarField $field)
Определения mssqlsqlhelper.php:292
getSubstrFunction($str, $from, $length=null)
Определения mssqlsqlhelper.php:156
getConverter(ScalarField $field)
Определения mssqlsqlhelper.php:227
getLengthFunction($field)
Определения mssqlsqlhelper.php:187
forSql($value, $maxLength=0)
Определения mssqlsqlhelper.php:47
convertFromDbDateTime($value)
Определения mssqlsqlhelper.php:250
addSecondsToDateTime($seconds, $from=null)
Определения mssqlsqlhelper.php:77
convertFromDbDate($value)
Определения mssqlsqlhelper.php:263
getCharToDateFunction($value)
Определения mssqlsqlhelper.php:195
prepareMerge($tableName, array $primaryFields, array $insertFields, array $updateFields)
Определения mssqlsqlhelper.php:472
prepareInsert($tableName, array $fields, $returnAsArray=false)
Определения sqlhelper.php:342
convertToDb($value, ORM\Fields\IReadable $field=null)
Определения sqlhelper.php:461
quote($identifier)
Определения sqlhelper.php:65
getValidators()
Определения field.php:236
Определения date.php:9
$str
Определения commerceml2.php:63
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$result
Определения get_property_values.php:14
$name
Определения menu_edit.php:35
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
</p ></td >< td valign=top style='border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;padding:0cm 2.0pt 0cm 2.0pt;height:9.0pt'>< p class=Normal align=center style='margin:0cm;margin-bottom:.0001pt;text-align:center;line-height:normal'>< a name=ТекстовоеПоле54 ></a ><?=($taxRate > count( $arTaxList) > 0) ? $taxRate."%"
Определения waybill.php:936
$matches
Определения index.php:22