Merge pull request #13915 from colemanw/shortCRM
[civicrm-core.git] / CRM / Utils / SQL / Insert.php
1 <?php
2
3 /**
4 * Dear God Why Do I Have To Write This (Dumb SQL Builder)
5 *
6 * Usage:
7 * $insert = CRM_Utils_SQL_Insert::into('mytable')
8 * ->row(array('col1' => '1', 'col2' => '2' ))
9 * ->row(array('col1' => '2b', 'col2' => '1b'));
10 * echo $insert->toSQL();
11 *
12 * Note: In MySQL, numeric values may be escaped. Except for NULL values,
13 * it's reasonable for us to simply escape all values by default -- without
14 * any knowledge of the underlying schema.
15 *
16 * Design principles:
17 * - Portable
18 * - No knowledge of the underlying SQL API (except for escaping -- CRM_Core_DAO::escapeString)
19 * - No knowledge of the underlying data model
20 * - Single file
21 * - SQL clauses correspond to PHP functions ($select->where("foo_id=123"))
22 */
23 class CRM_Utils_SQL_Insert {
24
25 private $verb = 'INSERT INTO';
26
27 /**
28 * @var string
29 */
30 private $table;
31
32 /**
33 * @var array
34 */
35 private $rows;
36
37 /**
38 * Array<string> list of column names
39 */
40 private $columns;
41
42 /**
43 * Create a new INSERT query.
44 *
45 * @param string $table
46 * Table-name and optional alias.
47 * @return CRM_Utils_SQL_Insert
48 */
49 public static function into($table) {
50 return new self($table);
51 }
52
53 /**
54 * Insert a record based on a DAO.
55 *
56 * @param \CRM_Core_DAO $dao
57 * @return \CRM_Utils_SQL_Insert
58 * @throws \CRM_Core_Exception
59 */
60 public static function dao(CRM_Core_DAO $dao) {
61 $table = CRM_Core_DAO::getLocaleTableName($dao->getTableName());
62 $row = [];
63 foreach ((array) $dao as $key => $value) {
64 if ($value === 'null') {
65 $value = NULL; // Blerg!!!
66 }
67 // Skip '_foobar' and '{\u00}*_options' and 'N'.
68 if (preg_match('/[a-zA-Z]/', $key{0}) && $key !== 'N') {
69 $row[$key] = $value;
70 }
71 }
72 return self::into($table)->row($row);
73 }
74
75 /**
76 * Create a new SELECT query.
77 *
78 * @param string $table
79 * Table-name and optional alias.
80 */
81 public function __construct($table) {
82 $this->table = $table;
83 $this->rows = [];
84 }
85
86 /**
87 * Get columns.
88 *
89 * @param array $columns
90 *
91 * @return CRM_Utils_SQL_Insert
92 * @throws \CRM_Core_Exception
93 */
94 public function columns($columns) {
95 if ($this->columns !== NULL) {
96 throw new CRM_Core_Exception("Column order already specified.");
97 }
98 $this->columns = $columns;
99 return $this;
100 }
101
102 /**
103 * Get rows.
104 *
105 * @param array $rows
106 *
107 * @return CRM_Utils_SQL_Insert
108 */
109 public function rows($rows) {
110 foreach ($rows as $row) {
111 $this->row($row);
112 }
113 return $this;
114 }
115
116 /**
117 * Get row.
118 *
119 * @param array $row
120 *
121 * @return CRM_Utils_SQL_Insert
122 * @throws CRM_Core_Exception
123 */
124 public function row($row) {
125 $columns = array_keys($row);
126
127 if ($this->columns === NULL) {
128 sort($columns);
129 $this->columns = $columns;
130 }
131 elseif (array_diff($this->columns, $columns) !== []) {
132 throw new CRM_Core_Exception("Inconsistent column names");
133 }
134
135 $escapedRow = [];
136 foreach ($this->columns as $column) {
137 $escapedRow[$column] = $this->escapeString($row[$column]);
138 }
139 $this->rows[] = $escapedRow;
140
141 return $this;
142 }
143
144 /**
145 * Use REPLACE INTO instead of INSERT INTO.
146 *
147 * @param bool $asReplace
148 *
149 * @return CRM_Utils_SQL_Insert
150 */
151 public function usingReplace($asReplace = TRUE) {
152 $this->verb = $asReplace ? 'REPLACE INTO' : 'INSERT INTO';
153 return $this;
154 }
155
156 /**
157 * Escape string.
158 *
159 * @param string|NULL $value
160 *
161 * @return string
162 * SQL expression, e.g. "it\'s great" (with-quotes) or NULL (without-quotes)
163 */
164 protected function escapeString($value) {
165 return $value === NULL ? 'NULL' : '"' . CRM_Core_DAO::escapeString($value) . '"';
166 }
167
168 /**
169 * Convert to SQL.
170 *
171 * @return string
172 * SQL statement
173 */
174 public function toSQL() {
175 $columns = "`" . implode('`,`', $this->columns) . "`";
176 $sql = "{$this->verb} {$this->table} ({$columns}) VALUES";
177
178 $nextDelim = '';
179 foreach ($this->rows as $row) {
180 $sql .= "{$nextDelim}\n(" . implode(',', $row) . ")";
181 $nextDelim = ',';
182 }
183 $sql .= "\n";
184
185 return $sql;
186 }
187
188 }