Skip to content

Commit e831c46

Browse files
committed
Fix alias and RawSql for SQLSRV
1 parent bb8fc35 commit e831c46

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

system/Database/SQLSRV/Builder.php

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -685,13 +685,15 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri
685685
return ''; // @codeCoverageIgnore
686686
}
687687

688+
$alias = $this->QBOptions['alias'] ?? '"_upsert"';
689+
688690
$updateFields = $this->QBOptions['updateFields'] ?? $this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ?? [];
689691

690692
$sql = 'MERGE INTO ' . $fullTableName . "\nUSING (\n";
691693

692694
$sql .= '{:_table_:}';
693695

694-
$sql .= ') "_upsert" (';
696+
$sql .= ") {$alias} (";
695697

696698
$sql .= implode(', ', $keys);
697699

@@ -702,9 +704,20 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri
702704
$sql .= implode(
703705
' AND ',
704706
array_map(
705-
static fn ($key) => ($key instanceof RawSql ?
706-
$key :
707-
$fullTableName . '.' . $key . ' = "_upsert".' . $key),
707+
static fn ($key, $value) => (
708+
($value instanceof RawSql && is_string($key))
709+
?
710+
$fullTableName . '.' . $key . ' = ' . $value
711+
:
712+
(
713+
$value instanceof RawSql
714+
?
715+
$value
716+
:
717+
$fullTableName . '.' . $value . ' = ' . $alias . '.' . $value
718+
)
719+
),
720+
array_keys($constraints),
708721
$constraints
709722
)
710723
) . ")\n";
@@ -716,7 +729,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri
716729
array_map(
717730
static fn ($key, $value) => $key . ($value instanceof RawSql ?
718731
' = ' . $value :
719-
' = "_upsert".' . $value),
732+
" = {$alias}.{$value}"),
720733
array_keys($updateFields),
721734
$updateFields
722735
)
@@ -729,10 +742,10 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri
729742
', ',
730743
array_map(
731744
static fn ($columnName) => $columnName === $tableIdentity
732-
? 'CASE WHEN "_upsert".' . $columnName . ' IS NULL THEN (SELECT '
745+
? "CASE WHEN {$alias}.{$columnName} IS NULL THEN (SELECT "
733746
. 'isnull(IDENT_CURRENT(\'' . $fullTableName . '\')+IDENT_INCR(\''
734-
. $fullTableName . '\'),1)) ELSE "_upsert".' . $columnName . ' END'
735-
: '"_upsert".' . $columnName,
747+
. $fullTableName . "'),1)) ELSE {$alias}.{$columnName} END"
748+
: "{$alias}.{$columnName}",
736749
$keys
737750
)
738751
) . ');'

0 commit comments

Comments
 (0)