-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertQuery.php
More file actions
91 lines (77 loc) · 2.79 KB
/
InsertQuery.php
File metadata and controls
91 lines (77 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
/*
* Opulence
*
* @link https://www.opulencephp.com
* @copyright Copyright (C) 2021 David Young
* @license https://github.com/opulencephp/Opulence/blob/1.2/LICENSE.md
*/
namespace Opulence\QueryBuilders;
/**
* Builds an insert query
*/
class InsertQuery extends Query
{
/** @var AugmentingQueryBuilder Handles functionality common to augmenting queries */
protected $augmentingQueryBuilder = null;
/**
* @param string $tableName The name of the table we're inserting into
* @param array $columnNamesToValues The mapping of column names to their respective values
* @throws InvalidQueryException Thrown if the query is invalid
*/
public function __construct(string $tableName, array $columnNamesToValues)
{
$this->tableName = $tableName;
$this->augmentingQueryBuilder = new AugmentingQueryBuilder();
$this->addColumnValues($columnNamesToValues);
}
/**
* Adds column values to the query
*
* @param array $columnNamesToValues The mapping of column names to their respective values
* Optionally, the values can be contained in an array whose first item is the value and whose second value is
* the PDO constant indicating the type of data the value represents
* @return self For method chaining
* @throws InvalidQueryException Thrown if the query is invalid
*/
public function addColumnValues(array $columnNamesToValues) : self
{
$this->addUnnamedPlaceholderValues(array_values($columnNamesToValues));
// The augmenting query doesn't care about the data type, so get rid of it
$columnNamesToValuesWithoutDataTypes = [];
foreach ($columnNamesToValues as $name => $value) {
if (is_array($value)) {
$columnNamesToValuesWithoutDataTypes[$name] = $value[0];
} else {
$columnNamesToValuesWithoutDataTypes[$name] = $value;
}
}
$this->augmentingQueryBuilder->addColumnValues($columnNamesToValuesWithoutDataTypes);
return $this;
}
/**
* @inheritdoc
*/
public function getSql() : string
{
$namesToValues = $this->augmentingQueryBuilder->getColumnNamesToValues();
$sql = 'INSERT INTO ' . $this->tableName . ' (' . implode(', ', array_keys($namesToValues)) . ') VALUES (';
$values = [];
foreach ($namesToValues as $value) {
if ($value instanceof Expression) {
$values[] = $value->getSql();
} else {
$values[] = '?';
}
}
$sql .= implode(', ', $values) . ')';
return $sql;
}
/**
* @inheritdoc
*/
public function setTable(string $tableName, string $tableAlias = '')
{
parent::setTable($tableName);
}
}