Merge pull request #14460 from eileenmcnaughton/ajax_test
[civicrm-core.git] / CRM / Utils / SQL / TempTable.php
CommitLineData
40c8b829
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
40c8b829
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
40c8b829
TO
32 *
33 * Table naming rules:
34 * - MySQL imposes a 64 char limit.
35 * - All temp tables start with "civicrm_tmp".
36 * - Durable temp tables: "civicrm_tmp_d_{12}_{32}"
37 * - Ephemeral temp tables: "civicrm_tmp_e_{12}_{32}"
38 *
0038409f
TO
39 * To use `TempTable`:
40 * - Begin by calling `CRM_Utils_SQL_TempTable::build()`.
41 * - Optionally, describe the table with `setDurable()`, `setCategory()`, `setId()`.
42 * - Finally, call `getName()` or `createWithQuery()` or `createWithColumns()`.
43 *
44 * Example 1: Just create a table name. You'll be responsible for CREATE/DROP actions.
40c8b829
TO
45 *
46 * $name = CRM_Utils_SQL_TempTable::build()->getName();
47 * $name = CRM_Utils_SQL_TempTable::build()->setDurable()->getName();
0038409f 48 * $name = CRM_Utils_SQL_TempTable::build()->setCategory('contactstats')->setId($contact['id'])->getName();
40c8b829
TO
49 *
50 * Example 2: Create a temp table using the results of a SELECT query.
51 *
52 * $tmpTbl = CRM_Utils_SQL_TempTable::build()->createWithQuery('SELECT id, display_name FROM civicrm_contact');
53 * $tmpTbl = CRM_Utils_SQL_TempTable::build()->createWithQuery(CRM_Utils_SQL_Select::from('civicrm_contact')->select('display_name'));
54 *
55 * Example 3: Create an empty temp table with list of columns.
56 *
0033aaaf 57 * $tmpTbl = CRM_Utils_SQL_TempTable::build()->setDurable()->createWithColumns('id int(10, name varchar(64)');
40c8b829
TO
58 *
59 * Example 4: Drop a table that you previously created.
60 *
61 * $tmpTbl->drop();
62 *
63 * Example 5: Auto-drop a temp table when $tmpTbl falls out of scope
64 *
65 * $tmpTbl->setAutodrop();
66 *
67 */
68class CRM_Utils_SQL_TempTable {
69
70 const UTF8 = 'DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
71 const CATEGORY_LENGTH = 12;
72 const CATEGORY_REGEXP = ';^[a-zA-Z0-9]+$;';
6714d8d2
SL
73 // MAX{64} - CATEGORY_LENGTH{12} - CONST_LENGHTH{15} = 37
74 const ID_LENGTH = 37;
40c8b829 75 const ID_REGEXP = ';^[a-zA-Z0-9_]+$;';
8ccee4bf 76 const INNODB = 'ENGINE=InnoDB';
77 const MEMORY = 'ENGINE=MEMORY';
40c8b829
TO
78
79 /**
80 * @var bool
81 */
6714d8d2
SL
82 protected $durable;
83
84 /**
85 * @var bool
86 */
87 protected $utf8;
40c8b829
TO
88
89 protected $category;
90
91 protected $id;
92
93 protected $autodrop;
94
8ccee4bf 95 protected $memory;
96
90e5222f 97 protected $createSql;
98
40c8b829
TO
99 /**
100 * @return CRM_Utils_SQL_TempTable
101 */
102 public static function build() {
103 $t = new CRM_Utils_SQL_TempTable();
104 $t->category = NULL;
105 $t->id = md5(uniqid('', TRUE));
106 // The constant CIVICRM_TEMP_FORCE_DURABLE is for local debugging.
107 $t->durable = CRM_Utils_Constant::value('CIVICRM_TEMP_FORCE_DURABLE', FALSE);
0033aaaf 108 $t->utf8 = TRUE;
40c8b829 109 $t->autodrop = FALSE;
8ccee4bf 110 $t->memory = FALSE;
40c8b829
TO
111 return $t;
112 }
113
114 public function __destruct() {
115 if ($this->autodrop) {
116 $this->drop();
117 }
118 }
119
120 /**
121 * Determine the full table name.
122 *
123 * @return string
124 * Ex: 'civicrm_tmp_d_foo_abcd1234abcd1234'
125 */
126 public function getName() {
127 $parts = ['civicrm', 'tmp'];
128 $parts[] = ($this->durable ? 'd' : 'e');
129 $parts[] = $this->category ? $this->category : 'dflt';
130 $parts[] = $this->id ? $this->id : 'dflt';
131 return implode('_', $parts);
132 }
133
134 /**
135 * Create the table using results from a SELECT query.
136 *
137 * @param string|CRM_Utils_SQL_Select $selectQuery
138 * @return CRM_Utils_SQL_TempTable
139 */
140 public function createWithQuery($selectQuery) {
8ccee4bf 141 $sql = sprintf('%s %s %s AS %s',
40c8b829 142 $this->toSQL('CREATE'),
8ccee4bf 143 $this->memory ? self::MEMORY : self::INNODB,
40c8b829
TO
144 $this->utf8 ? self::UTF8 : '',
145 ($selectQuery instanceof CRM_Utils_SQL_Select ? $selectQuery->toSQL() : $selectQuery)
146 );
be2fb01f 147 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE, FALSE);
90e5222f 148 $this->createSql = $sql;
40c8b829
TO
149 return $this;
150 }
151
152 /**
153 * Create the empty table.
154 *
155 * @parma string $columns
156 * SQL column listing.
157 * Ex: 'id int(10), name varchar(64)'.
158 * @return CRM_Utils_SQL_TempTable
159 */
160 public function createWithColumns($columns) {
8ccee4bf 161 $sql = sprintf('%s (%s) %s %s',
40c8b829
TO
162 $this->toSQL('CREATE'),
163 $columns,
8ccee4bf 164 $this->memory ? self::MEMORY : self::INNODB,
40c8b829
TO
165 $this->utf8 ? self::UTF8 : ''
166 );
be2fb01f 167 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE, FALSE);
90e5222f 168 $this->createSql = $sql;
40c8b829
TO
169 return $this;
170 }
171
172 /**
173 * Drop the table.
174 *
175 * @return CRM_Utils_SQL_TempTable
176 */
177 public function drop() {
178 $sql = $this->toSQL('DROP', 'IF EXISTS');
be2fb01f 179 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE, FALSE);
40c8b829
TO
180 return $this;
181 }
182
183 /**
184 * @param string $action
185 * Ex: 'CREATE', 'DROP'
186 * @param string|NULL $ifne
187 * Ex: 'IF EXISTS', 'IF NOT EXISTS'.
188 * @return string
189 * Ex: 'CREATE TEMPORARY TABLE `civicrm_tmp_e_foo_abcd1234`'
190 * Ex: 'CREATE TABLE IF NOT EXISTS `civicrm_tmp_d_foo_abcd1234`'
191 */
192 private function toSQL($action, $ifne = NULL) {
193 $parts = [];
194 $parts[] = $action;
195 if (!$this->durable) {
196 $parts[] = 'TEMPORARY';
197 }
198 $parts[] = 'TABLE';
199 if ($ifne) {
200 $parts[] = $ifne;
201 }
202 $parts[] = '`' . $this->getName() . '`';
203 return implode(' ', $parts);
204 }
205
206 /**
207 * @return string|NULL
208 */
209 public function getCategory() {
210 return $this->category;
211 }
212
213 /**
214 * @return string|NULL
215 */
216 public function getId() {
217 return $this->id;
218 }
219
90e5222f 220 /**
221 * @return string|NULL
222 */
223 public function getCreateSql() {
224 return $this->createSql;
225 }
226
40c8b829
TO
227 /**
228 * @return bool
229 */
230 public function isAutodrop() {
231 return $this->autodrop;
232 }
233
234 /**
235 * @return bool
236 */
237 public function isDurable() {
238 return $this->durable;
239 }
240
8ccee4bf 241 /**
242 * @return bool
243 */
244 public function isMemory() {
245 return $this->memory;
246 }
247
40c8b829
TO
248 /**
249 * @return bool
250 */
251 public function isUtf8() {
252 return $this->utf8;
253 }
254
255 /**
256 * @param bool $autodrop
257 * @return CRM_Utils_SQL_TempTable
258 */
259 public function setAutodrop($autodrop = TRUE) {
260 $this->autodrop = $autodrop;
261 return $this;
262 }
263
264 /**
265 * @param string|NULL $category
f0197a3d 266 *
40c8b829
TO
267 * @return CRM_Utils_SQL_TempTable
268 */
269 public function setCategory($category) {
270 if ($category && !preg_match(self::CATEGORY_REGEXP, $category) || strlen($category) > self::CATEGORY_LENGTH) {
271 throw new \RuntimeException("Malformed temp table category");
272 }
273 $this->category = $category;
274 return $this;
275 }
276
277 /**
f0197a3d 278 * Set whether the table should be durable.
279 *
280 * Durable tables are not TEMPORARY in the mysql sense.
281 *
282 * @param bool $durable
283 *
40c8b829
TO
284 * @return CRM_Utils_SQL_TempTable
285 */
286 public function setDurable($durable = TRUE) {
287 $this->durable = $durable;
288 return $this;
289 }
290
291 /**
f0197a3d 292 * Setter for id
293 *
40c8b829 294 * @param mixed $id
f0197a3d 295 *
40c8b829
TO
296 * @return CRM_Utils_SQL_TempTable
297 */
298 public function setId($id) {
299 if ($id && !preg_match(self::ID_REGEXP, $id) || strlen($id) > self::ID_LENGTH) {
300 throw new \RuntimeException("Malformed temp table id");
301 }
302 $this->id = $id;
303 return $this;
304 }
305
8ccee4bf 306 /**
307 * Set table engine to MEMORY.
308 *
309 * @param bool $value
310 *
311 * @return $this
312 */
313 public function setMemory($value = TRUE) {
314 $this->memory = $value;
315 return $this;
316 }
317
f0197a3d 318 /**
319 * Set table collation to UTF8.
320 *
0033aaaf 321 * @deprecated This method is deprecated as tables should be assumed to have
322 * UTF-8 as the default character set and collation; some other character set
323 * or collation may be specified in the column definition.
f0197a3d 324 *
325 * @param bool $value
326 *
327 * @return $this
328 */
40c8b829
TO
329 public function setUtf8($value = TRUE) {
330 $this->utf8 = $value;
331 return $this;
332 }
333
334}