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