Overview
Comment:Implement new '#list' section in Brindille skeletons Also implement new 'explain' parameter for '#sql' and children sections
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | dev
Files: files | file ages | folders
SHA3-256: 5e1c85998ae451f5af2872686179e39bb6fa48e6f9aee461c5fa0b43aff907d3
User & Date: bohwaz on 2023-02-02 01:19:18
Other Links: branch diff | manifest | tags
Context
2023-02-02
02:03
In '#list' section, use a column number to identify the column, not a hash that would not be usable then check-in: e9801f721b user: bohwaz tags: dev
01:19
Implement new '#list' section in Brindille skeletons Also implement new 'explain' parameter for '#sql' and children sections check-in: 5e1c85998a user: bohwaz tags: dev
01:17
New parameter 'capture' for ':include' function, new parameter ':assign_new_id' for ':save' function check-in: 35add00cf3 user: bohwaz tags: dev
Changes

Modified src/include/lib/Garradin/UserTemplate/Sections.php from [a3f153b168] to [2197634be7].

1
2
3
4
5
6


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41























42
43
44
45
46
47
48
<?php

namespace Garradin\UserTemplate;

use KD2\Brindille_Exception;
use Garradin\DB;


use Garradin\Utils;
use Garradin\UserException;
use Garradin\Users\Session;
use Garradin\Entities\Web\Page;
use Garradin\Web\Web;
use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\Users\DynamicFields;

use const Garradin\WWW_URL;

class Sections
{
	const SECTIONS_LIST = [
		'load',

		'categories',
		'articles',
		'pages',
		'images',
		'breadcrumbs',
		'documents',
		'files',
		'users',
		'subscriptions',
		'transactions',
		'transaction_lines',
		'transaction_users',
		'accounts',
		'balances',
		'sql',
		'restrict',
		'module',
	];

	static protected $_cache = [];
























	static protected function cache(string $id, callable $callback)
	{
		if (!array_key_exists($id, self::$_cache)) {
			self::$_cache[$id] = $callback();
		}







>
>















>




















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php

namespace Garradin\UserTemplate;

use KD2\Brindille_Exception;
use Garradin\DB;
use Garradin\DynamicList;
use Garradin\Template;
use Garradin\Utils;
use Garradin\UserException;
use Garradin\Users\Session;
use Garradin\Entities\Web\Page;
use Garradin\Web\Web;
use Garradin\Files\Files;
use Garradin\Entities\Files\File;
use Garradin\Users\DynamicFields;

use const Garradin\WWW_URL;

class Sections
{
	const SECTIONS_LIST = [
		'load',
		'list',
		'categories',
		'articles',
		'pages',
		'images',
		'breadcrumbs',
		'documents',
		'files',
		'users',
		'subscriptions',
		'transactions',
		'transaction_lines',
		'transaction_users',
		'accounts',
		'balances',
		'sql',
		'restrict',
		'module',
	];

	static protected $_cache = [];

	static protected function _debug(string $str): void
	{
		echo sprintf('<pre style="padding: 5px; margin: 5px; background: yellow; white-space: pre;">%s</pre>', htmlspecialchars($str));
	}

	static protected function _debugExplain(string $sql): void
	{
		$explain = '';

		try {
			$r = DB::getInstance()->get('EXPLAIN QUERY PLAN ' . $sql);

			foreach ($r as $e) {
				$explain .= $e->detail . "\n";
			}
		}
		catch (DB_Exception $e) {
			$explain = 'Error: ' . $e->getMessage();
		}

		self::_debug($explain);
	}

	static protected function cache(string $id, callable $callback)
	{
		if (!array_key_exists($id, self::$_cache)) {
			self::$_cache[$id] = $callback();
		}

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
			return;
		}

		if (!isset($params['where'])) {
			$params['where'] = '1';
		}
		else {
			$params['where'] = preg_replace_callback(
				'/\$(\$[\[\.][^=\s]+)/',
				fn ($m) => sprintf('json_extract(document, %s)', $db->quote($m[1])),
				$params['where']
			);
		}

		if (isset($params['key'])) {
			$params['where'] .= ' AND key = :key';
			$params['limit'] = 1;
			$params[':key'] = $params['key'];
			unset($params['key']);







<
<
<
|
<







126
127
128
129
130
131
132



133

134
135
136
137
138
139
140
			return;
		}

		if (!isset($params['where'])) {
			$params['where'] = '1';
		}
		else {



			$params['where'] = self::_moduleReplaceJSONExtract($params['where']);

		}

		if (isset($params['key'])) {
			$params['where'] .= ' AND key = :key';
			$params['limit'] = 1;
			$params[':key'] = $params['key'];
			unset($params['key']);
132
133
134
135
136
137
138
139












140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158










































































































































































159
160
161
162
163
164
165

			$hash = sha1($key);
			$params['where'] .= sprintf(' AND json_extract(document, %s) = :quick_%s', $db->quote($key), $hash);
			$params[':quick_' . $hash] = $value;
			unset($params[$key]);
		}

		$params['select'] = isset($params['select']) ? $params['select'] : 'document AS json';













		// Try to create an index if required
		self::_createModuleIndexes($params['tables'], $params['where']);

		$query = self::sql($params, $tpl, $line);

		foreach ($query as $row) {
			if (isset($row['json'])) {
				$json = json_decode($row['json'], true);

				if (is_array($json)) {
					unset($row['json']);
					$row = array_merge($row, $json);
				}
			}

			yield $row;
		}
	}











































































































































































	static public function balances(array $params, UserTemplate $tpl, int $line): \Generator
	{
		$db = DB::getInstance();

		if (!array_key_exists('where', $params)) {
			$params['where'] = '';







|
>
>
>
>
>
>
>
>
>
>
>
>



















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369

			$hash = sha1($key);
			$params['where'] .= sprintf(' AND json_extract(document, %s) = :quick_%s', $db->quote($key), $hash);
			$params[':quick_' . $hash] = $value;
			unset($params[$key]);
		}

		$params['select'] = isset($params['select']) ? self::_moduleReplaceJSONExtract($params['select']) : 'id, key, document AS json';

		if (isset($params['group'])) {
			$params['group'] = self::_moduleReplaceJSONExtract($params['group']);
		}

		if (isset($params['having'])) {
			$params['having'] = self::_moduleReplaceJSONExtract($params['having']);
		}

		if (isset($params['order'])) {
			$params['order'] = self::_moduleReplaceJSONExtract($params['order']);
		}

		// Try to create an index if required
		self::_createModuleIndexes($params['tables'], $params['where']);

		$query = self::sql($params, $tpl, $line);

		foreach ($query as $row) {
			if (isset($row['json'])) {
				$json = json_decode($row['json'], true);

				if (is_array($json)) {
					unset($row['json']);
					$row = array_merge($row, $json);
				}
			}

			yield $row;
		}
	}

	static protected function _getModuleColumnsFromSchema(string $schema, ?string $columns, UserTemplate $tpl, int $line): array
	{
		$schema = Functions::read(['file' => $schema], $tpl, $line);
		$schema = json_decode($schema, true);

		if (!$schema) {
			throw new Brindille_Exception(sprintf("ligne %d: impossible de lire le schéma:\n%s",
				$line, json_last_error_msg()));
		}

		if (empty($schema['properties'])) {
			return [];
		}

		$out = [];

		$out['id'] = [];
		$out['key'] = [];

		if (null !== $columns) {
			$columns = explode(',', $columns);
			$columns = array_map('trim', $columns);
		}
		else {
			$columns = array_keys($schema['properties']);
		}

		foreach ($columns as $key) {
			$rule = $schema['properties'][$key] ?? null;

			// This column is not in the schema
			if (!$rule) {
				continue;
			}

			$types = is_array($rule['type']) ? $rule['type'] : [$rule['type']];

			// Only "simple" types are supported
			if (in_array('array', $types) || in_array('object', $types)) {
				continue;
			}

			$out[$key] = [
				'label' => $rule['description'] ?? null,
				'select' => sprintf('json_extract(document, \'$.%s\')', $key),
			];
		}

		return $out;
	}

	static public function _moduleReplaceJSONExtract(string $str): string
	{
		if (!strstr($str, '$')) {
			return $str;
		}

		return preg_replace_callback(
			'/\$(\$[\[\.][\w\d\.\[\]#]+)/',
			fn ($m) => sprintf('json_extract(document, %s)', DB::getInstance()->quote($m[1])),
			$str
		);
	}

	static public function list(array $params, UserTemplate $tpl, int $line): \Generator
	{
		if (empty($params['schema']) && empty($params['select'])) {
			throw new Brindille_Exception('Missing schema parameter');
		}

		$name = $params['module'] ?? Utils::basename(Utils::dirname($tpl->_tpl_path));

		if (!$name) {
			throw new Brindille_Exception('Unique module name could not be found');
		}

		$table = 'module_data_' . $name;

		$db = DB::getInstance();
		$has_table = $db->test('sqlite_master', 'type = \'table\' AND name = ?', $table);

		if (!$has_table) {
			return;
		}

		if (!isset($params['where'])) {
			$where = '1';
		}
		else {
			$where = self::_moduleReplaceJSONExtract($params['where']);
		}

		$columns = [];

		if (!empty($params['select'])) {
			foreach (explode(',', $params['select']) as $c) {
				$c = trim($c);
				$name = trim(strtok($c, ' AS '));
				$alias = strtok(false);

				$hash = md5($c);
				$columns[$hash] = [
					'label' => $alias ? trim($alias, ' \'"') : $name,
					'select' => $this->_moduleReplaceJSONExtract($name),
				];
			}

			if (!empty($params['order'])) {
				$params['order'] = md5($this->_moduleReplaceJSONExtract($params['order']));
			}
		}
		else {
			$columns = self::_getModuleColumnsFromSchema($params['schema'], $params['columns'] ?? null, $tpl, $line);
		}

		$columns['document'] = [];

		$list = new DynamicList($columns, $table);

		foreach ($params as $key => $value) {
			$f = substr($key, 0, 1);

			if ($f == ':' && strstr($where, $key)) {
				$list->setParameter(substr($key, 1), $value);
			}
			elseif ($f == '$') {
				// Replace '$.name = "value"' parameters with json_extract
				$hash = sha1($key);
				$where .= sprintf(' AND json_extract(document, %s) = :quick_%s', $db->quote($key), $hash);
				$list->setParameter('quick_' . $hash, $value);
			}
		}

		$list->setConditions($where);
		$list->setPageSize((int) ($params['max'] ?? 50));

		if (isset($params['order'])) {
			$list->orderBy($params['order'], $params['desc'] ?? false);
		}

		$list->setModifier(function(&$row) {
			$row = array_merge(json_decode($row->document, true), (array)$row);
		});

		// Try to create an index if required
		self::_createModuleIndexes($table, $where);

		$list->loadFromQueryString();

		if (!empty($params['debug'])) {
			self::_debug($list->SQL());
		}

		if (!empty($params['explain'])) {
			self::_debugExplain($list->SQL());
		}

		$tpl = Template::getInstance();
		$tpl->assign(compact('list'));
		$tpl->assign('check', $params['check'] ?? false);
		$tpl->display('common/dynamic_list_head.tpl');

		yield from $list->iterate();

		echo '</tbody>';
		echo '</table>';

		echo $list->getHTMLPagination();
	}

	static public function balances(array $params, UserTemplate $tpl, int $line): \Generator
	{
		$db = DB::getInstance();

		if (!array_key_exists('where', $params)) {
			$params['where'] = '';
230
231
232
233
234
235
236

237



238
239
240
241
242
243
244
			$params['where'] = '';
		}

		$id_field = DynamicFields::getNameFieldsSQL();
		$login_field = DynamicFields::getLoginField();
		$number_field = DynamicFields::getNumberField();


		$params['select'] = sprintf('*, %s AS user_name, %s AS user_login, %s AS user_number',



			$id_field, $login_field, $number_field);
		$params['tables'] = 'users';

		if (isset($params['id'])) {
			$params['where'] .= ' AND id = :id';
			$params[':id'] = (int) $params['id'];
			unset($params['id']);







>
|
>
>
>







434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
			$params['where'] = '';
		}

		$id_field = DynamicFields::getNameFieldsSQL();
		$login_field = DynamicFields::getLoginField();
		$number_field = DynamicFields::getNumberField();

		if (empty($params['select'])) {
			$params['select'] = '1';
		}

		$params['select'] .= sprintf(', %s AS _name, %s AS _login, %s AS _number',
			$id_field, $login_field, $number_field);
		$params['tables'] = 'users';

		if (isset($params['id'])) {
			$params['where'] .= ' AND id = :id';
			$params[':id'] = (int) $params['id'];
			unset($params['id']);
718
719
720
721
722
723
724


725


726
727
728
729
730
731
732
			}

			foreach ($args as $key => $value) {
				$statement->bindValue($key, $value, $db->getArgType($value));
			}

			if (!empty($params['debug'])) {


				echo sprintf('<pre style="padding: 5px; background: yellow; white-space: normal;">%s</pre>', htmlspecialchars($statement->getSQL(true)));


			}

			$result = $statement->execute();
		}
		catch (\KD2\DB\DB_Exception $e) {
			throw new Brindille_Exception(sprintf("à la ligne %d erreur SQL :\n%s\n\nRequête exécutée :\n%s", $line, $db->lastErrorMsg(), $sql));
		}







>
>
|
>
>







926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
			}

			foreach ($args as $key => $value) {
				$statement->bindValue($key, $value, $db->getArgType($value));
			}

			if (!empty($params['debug'])) {
				self::_debug($statement->getSQL(true));
			}

			if (!empty($params['explain'])) {
				self::_debugExplain($statement->getSQL(true));
			}

			$result = $statement->execute();
		}
		catch (\KD2\DB\DB_Exception $e) {
			throw new Brindille_Exception(sprintf("à la ligne %d erreur SQL :\n%s\n\nRequête exécutée :\n%s", $line, $db->lastErrorMsg(), $sql));
		}