Skip to content

Commit b0ed2d5

Browse files
committed
fix: invalid INSERT query when builder uses table alias
1 parent bc688d9 commit b0ed2d5

2 files changed

Lines changed: 44 additions & 2 deletions

File tree

system/Database/BaseBuilder.php

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1863,7 +1863,7 @@ public function getCompiledInsert(bool $reset = true)
18631863
}
18641864

18651865
$sql = $this->_insert(
1866-
$this->db->protectIdentifiers($this->QBFrom[0], true, null, false),
1866+
$this->db->protectIdentifiers($this->removeAlias($this->QBFrom[0]), true, null, false),
18671867
array_keys($this->QBSet),
18681868
array_values($this->QBSet)
18691869
);
@@ -1895,7 +1895,7 @@ public function insert($set = null, ?bool $escape = null)
18951895
}
18961896

18971897
$sql = $this->_insert(
1898-
$this->db->protectIdentifiers($this->QBFrom[0], true, $escape, false),
1898+
$this->db->protectIdentifiers($this->removeAlias($this->QBFrom[0]), true, $escape, false),
18991899
array_keys($this->QBSet),
19001900
array_values($this->QBSet)
19011901
);
@@ -1914,6 +1914,19 @@ public function insert($set = null, ?bool $escape = null)
19141914
return false;
19151915
}
19161916

1917+
protected function removeAlias(string $from): string
1918+
{
1919+
if (strpos($from, ' ') !== false) {
1920+
// if the alias is written with the AS keyword, remove it
1921+
$from = preg_replace('/\s+AS\s+/i', ' ', $from);
1922+
1923+
$parts = explode(' ', $from);
1924+
$from = $parts[0];
1925+
}
1926+
1927+
return $from;
1928+
}
1929+
19171930
/**
19181931
* This method is used by both insert() and getCompiledInsert() to
19191932
* validate that the there data is actually being set and that table

tests/system/Database/Builder/InsertTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,35 @@ public function testInsertObject()
8585
$this->assertSame($expectedBinds, $builder->getBinds());
8686
}
8787

88+
/**
89+
* @see https://github.com/codeigniter4/CodeIgniter4/issues/5365
90+
*/
91+
public function testInsertWithTableAlias()
92+
{
93+
$builder = $this->db->table('jobs as j');
94+
95+
$insertData = [
96+
'id' => 1,
97+
'name' => 'Grocery Sales',
98+
];
99+
$builder->testMode()->insert($insertData, true);
100+
101+
$expectedSQL = 'INSERT INTO "jobs" ("id", "name") VALUES (1, \'Grocery Sales\')';
102+
$expectedBinds = [
103+
'id' => [
104+
1,
105+
true,
106+
],
107+
'name' => [
108+
'Grocery Sales',
109+
true,
110+
],
111+
];
112+
113+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledInsert()));
114+
$this->assertSame($expectedBinds, $builder->getBinds());
115+
}
116+
88117
public function testThrowsExceptionOnNoValuesSet()
89118
{
90119
$builder = $this->db->table('jobs');

0 commit comments

Comments
 (0)