Skip to content

Commit 53b9446

Browse files
committed
Fix multi inserts in SQLite.
1 parent 0f690e8 commit 53b9446

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

laravel/database/query/grammars/sqlite.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,50 @@ protected function orderings(Query $query)
2121
return 'ORDER BY '.implode(', ', $sql);
2222
}
2323

24+
/**
25+
* Compile a SQL INSERT statement from a Query instance.
26+
*
27+
* This method handles the compilation of single row inserts and batch inserts.
28+
*
29+
* @param Query $query
30+
* @param array $values
31+
* @return string
32+
*/
33+
public function insert(Query $query, $values)
34+
{
35+
// Essentially we will force every insert to be treated as a batch insert which
36+
// simply makes creating the SQL easier for us since we can utilize the same
37+
// basic routine regardless of an amount of records given to us to insert.
38+
$table = $this->wrap_table($query->from);
39+
40+
if ( ! is_array(reset($values)))
41+
{
42+
$values = array($values);
43+
}
44+
45+
// If there is only one record being inserted, we will just use the usual query
46+
// grammar insert builder because no special syntax is needed for the single
47+
// row inserts in SQLite. However, if there are multiples, we'll continue.
48+
if (count($values) == 1)
49+
{
50+
return parent::insert($query, $values[0]);
51+
}
52+
53+
$names = $this->columnize(array_keys($values[0]));
54+
55+
$columns = array();
56+
57+
// SQLite requires us to build the multi-row insert as a listing of select with
58+
// unions joining them together. So we'll build out this list of columns and
59+
// then join them all together with select unions to complete the queries.
60+
foreach (array_keys($values[0]) as $column)
61+
{
62+
$columns[] = '? AS '.$this->wrap($column);
63+
}
64+
65+
$columns = array_fill(9, count($values), implode(', ', $columns));
66+
67+
return "INSERT INTO $table ($names) SELECT ".implode(' UNION SELECT ', $columns);
68+
}
69+
2470
}

0 commit comments

Comments
 (0)