4 * Dear God Why Do I Have To Write This (Dumb SQL Builder)
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();
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.
18 * - No knowledge of the underlying SQL API (except for escaping -- CRM_Core_DAO::escapeString)
19 * - No knowledge of the underlying data model
21 * - SQL clauses correspond to PHP functions ($select->where("foo_id=123"))
23 class CRM_Utils_SQL_Insert
{
25 private $verb = 'INSERT INTO';
38 * Array<string> list of column names
43 * Create a new INSERT query.
45 * @param string $table
46 * Table-name and optional alias.
47 * @return CRM_Utils_SQL_Insert
49 public static function into($table) {
50 return new self($table);
54 * Create a new SELECT query.
56 * @param string $table
57 * Table-name and optional alias.
59 public function __construct($table) {
60 $this->table
= $table;
61 $this->rows
= array();
67 * @param array $columns
70 * @throws \CRM_Core_Exception
72 public function columns($columns) {
73 if ($this->columns
!== NULL) {
74 throw new CRM_Core_Exception("Column order already specified.");
76 $this->columns
= $columns;
85 * @return CRM_Utils_SQL_Insert
87 public function rows($rows) {
88 foreach ($rows as $row) {
99 * @return CRM_Utils_SQL_Insert
100 * @throws CRM_Core_Exception
102 public function row($row) {
103 $columns = array_keys($row);
105 if ($this->columns
=== NULL) {
107 $this->columns
= $columns;
109 elseif (array_diff($this->columns
, $columns) !== array()) {
110 throw new CRM_Core_Exception("Inconsistent column names");
113 $escapedRow = array();
114 foreach ($this->columns
as $column) {
115 $escapedRow[$column] = $this->escapeString($row[$column]);
117 $this->rows
[] = $escapedRow;
123 * Use REPLACE INTO instead of INSERT INTO.
125 * @param bool $asReplace
127 * @return CRM_Utils_SQL_Insert
129 public function usingReplace($asReplace = TRUE) {
130 $this->verb
= $asReplace ?
'REPLACE INTO' : 'INSERT INTO';
137 * @param string|NULL $value
140 * SQL expression, e.g. "it\'s great" (with-quotes) or NULL (without-quotes)
142 protected function escapeString($value) {
143 return $value === NULL ?
'NULL' : '"' . CRM_Core_DAO
::escapeString($value) . '"';
152 public function toSQL() {
153 $columns = "`" . implode('`,`', $this->columns
) . "`";
154 $sql = "{$this->verb} {$this->table} ({$columns}) VALUES";
157 foreach ($this->rows
as $row) {
158 $sql .= "{$nextDelim}\n(" . implode(',', $row) . ")";