(dev/core#183) Change temp table naming for CRM/Contact/Form/Search/Custom/DateAdded.php
[civicrm-core.git] / CRM / Utils / SQL / TempTable.php
CommitLineData
40c8b829
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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
31 * @copyright CiviCRM LLC (c) 2004-2018
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 *
39 * Example 1: Just create table name. You'll be responsible for CREATE/DROP actions.
40 *
41 * $name = CRM_Utils_SQL_TempTable::build()->getName();
42 * $name = CRM_Utils_SQL_TempTable::build()->setDurable()->getName();
43 *
44 * Example 2: Create a temp table using the results of a SELECT query.
45 *
46 * $tmpTbl = CRM_Utils_SQL_TempTable::build()->createWithQuery('SELECT id, display_name FROM civicrm_contact');
47 * $tmpTbl = CRM_Utils_SQL_TempTable::build()->createWithQuery(CRM_Utils_SQL_Select::from('civicrm_contact')->select('display_name'));
48 *
49 * Example 3: Create an empty temp table with list of columns.
50 *
51 * $tmpTbl = CRM_Utils_SQL_TempTable::build()->setDurable()->setUtf8()->createWithColumns('id int(10, name varchar(64)');
52 *
53 * Example 4: Drop a table that you previously created.
54 *
55 * $tmpTbl->drop();
56 *
57 * Example 5: Auto-drop a temp table when $tmpTbl falls out of scope
58 *
59 * $tmpTbl->setAutodrop();
60 *
61 */
62class CRM_Utils_SQL_TempTable {
63
64 const UTF8 = 'DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
65 const CATEGORY_LENGTH = 12;
66 const CATEGORY_REGEXP = ';^[a-zA-Z0-9]+$;';
67 const ID_LENGTH = 37; // MAX{64} - CATEGORY_LENGTH{12} - CONST_LENGHTH{15} = 37
68 const ID_REGEXP = ';^[a-zA-Z0-9_]+$;';
69
70 /**
71 * @var bool
72 */
73 protected $durable, $utf8;
74
75 protected $category;
76
77 protected $id;
78
79 protected $autodrop;
80
81 /**
82 * @return CRM_Utils_SQL_TempTable
83 */
84 public static function build() {
85 $t = new CRM_Utils_SQL_TempTable();
86 $t->category = NULL;
87 $t->id = md5(uniqid('', TRUE));
88 // The constant CIVICRM_TEMP_FORCE_DURABLE is for local debugging.
89 $t->durable = CRM_Utils_Constant::value('CIVICRM_TEMP_FORCE_DURABLE', FALSE);
90 // I suspect it would be better to just say utf8=true, but a lot of existing queries don't do the utf8 bit.
91 $t->utf8 = CRM_Utils_Constant::value('CIVICRM_TEMP_FORCE_UTF8', FALSE);
92 $t->autodrop = FALSE;
93 return $t;
94 }
95
96 public function __destruct() {
97 if ($this->autodrop) {
98 $this->drop();
99 }
100 }
101
102 /**
103 * Determine the full table name.
104 *
105 * @return string
106 * Ex: 'civicrm_tmp_d_foo_abcd1234abcd1234'
107 */
108 public function getName() {
109 $parts = ['civicrm', 'tmp'];
110 $parts[] = ($this->durable ? 'd' : 'e');
111 $parts[] = $this->category ? $this->category : 'dflt';
112 $parts[] = $this->id ? $this->id : 'dflt';
113 return implode('_', $parts);
114 }
115
116 /**
117 * Create the table using results from a SELECT query.
118 *
119 * @param string|CRM_Utils_SQL_Select $selectQuery
120 * @return CRM_Utils_SQL_TempTable
121 */
122 public function createWithQuery($selectQuery) {
123 $sql = sprintf('%s %s AS %s',
124 $this->toSQL('CREATE'),
125 $this->utf8 ? self::UTF8 : '',
126 ($selectQuery instanceof CRM_Utils_SQL_Select ? $selectQuery->toSQL() : $selectQuery)
127 );
128 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE, FALSE);
129 return $this;
130 }
131
132 /**
133 * Create the empty table.
134 *
135 * @parma string $columns
136 * SQL column listing.
137 * Ex: 'id int(10), name varchar(64)'.
138 * @return CRM_Utils_SQL_TempTable
139 */
140 public function createWithColumns($columns) {
141 $sql = sprintf('%s (%s) %s',
142 $this->toSQL('CREATE'),
143 $columns,
144 $this->utf8 ? self::UTF8 : ''
145 );
146 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE, FALSE);
147 return $this;
148 }
149
150 /**
151 * Drop the table.
152 *
153 * @return CRM_Utils_SQL_TempTable
154 */
155 public function drop() {
156 $sql = $this->toSQL('DROP', 'IF EXISTS');
157 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE, FALSE);
158 return $this;
159 }
160
161 /**
162 * @param string $action
163 * Ex: 'CREATE', 'DROP'
164 * @param string|NULL $ifne
165 * Ex: 'IF EXISTS', 'IF NOT EXISTS'.
166 * @return string
167 * Ex: 'CREATE TEMPORARY TABLE `civicrm_tmp_e_foo_abcd1234`'
168 * Ex: 'CREATE TABLE IF NOT EXISTS `civicrm_tmp_d_foo_abcd1234`'
169 */
170 private function toSQL($action, $ifne = NULL) {
171 $parts = [];
172 $parts[] = $action;
173 if (!$this->durable) {
174 $parts[] = 'TEMPORARY';
175 }
176 $parts[] = 'TABLE';
177 if ($ifne) {
178 $parts[] = $ifne;
179 }
180 $parts[] = '`' . $this->getName() . '`';
181 return implode(' ', $parts);
182 }
183
184 /**
185 * @return string|NULL
186 */
187 public function getCategory() {
188 return $this->category;
189 }
190
191 /**
192 * @return string|NULL
193 */
194 public function getId() {
195 return $this->id;
196 }
197
198 /**
199 * @return bool
200 */
201 public function isAutodrop() {
202 return $this->autodrop;
203 }
204
205 /**
206 * @return bool
207 */
208 public function isDurable() {
209 return $this->durable;
210 }
211
212 /**
213 * @return bool
214 */
215 public function isUtf8() {
216 return $this->utf8;
217 }
218
219 /**
220 * @param bool $autodrop
221 * @return CRM_Utils_SQL_TempTable
222 */
223 public function setAutodrop($autodrop = TRUE) {
224 $this->autodrop = $autodrop;
225 return $this;
226 }
227
228 /**
229 * @param string|NULL $category
230 * @return CRM_Utils_SQL_TempTable
231 */
232 public function setCategory($category) {
233 if ($category && !preg_match(self::CATEGORY_REGEXP, $category) || strlen($category) > self::CATEGORY_LENGTH) {
234 throw new \RuntimeException("Malformed temp table category");
235 }
236 $this->category = $category;
237 return $this;
238 }
239
240 /**
241 * @parma bool $value
242 * @return CRM_Utils_SQL_TempTable
243 */
244 public function setDurable($durable = TRUE) {
245 $this->durable = $durable;
246 return $this;
247 }
248
249 /**
250 * @param mixed $id
251 * @return CRM_Utils_SQL_TempTable
252 */
253 public function setId($id) {
254 if ($id && !preg_match(self::ID_REGEXP, $id) || strlen($id) > self::ID_LENGTH) {
255 throw new \RuntimeException("Malformed temp table id");
256 }
257 $this->id = $id;
258 return $this;
259 }
260
261 public function setUtf8($value = TRUE) {
262 $this->utf8 = $value;
263 return $this;
264 }
265
266}