pg_parse 0.14.0

PostgreSQL parser that uses the actual PostgreSQL server source to parse SQL queries and return the internal PostgreSQL parse tree.
Documentation
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
#include "pg_query.h"
#include "pg_query_internal.h"
#include "pg_query_summary.h"

#include "nodes/pg_list.h"
#include "nodes/nodeFuncs.h"

#include "mb/pg_wchar.h"

enum TruncationAttr
{
	TRUNCATION_TARGET_LIST,
	TRUNCATION_WHERE_CLAUSE,
	TRUNCATION_VALUES_LISTS,
	TRUNCATION_COLS,
	TRUNCATION_CTE_QUERY,
};

typedef struct
{
	List	   *truncations;
	int32_t		depth;
}			TruncationState;

typedef struct
{
	enum TruncationAttr attr;
	Node	   *node;
	int32_t		depth;
	int32_t		length;
}			PossibleTruncation;

static bool generate_possible_truncations(Node *tree, TruncationState * state);
static void apply_truncations(Summary * summary, Node *tree, TruncationState * state, int truncate_limit);
static int	cmp_possible_truncations(const ListCell *a, const ListCell *b);

static int32_t select_target_list_len(List *nodes);
static int32_t select_values_lists_len(List *nodes);
static int32_t update_target_list_len(List *nodes);
static int32_t where_clause_len(Node *node);
static int32_t cols_len(List *nodes);

static ColumnRef *dummy_column(void);
static ResTarget *dummy_target(void);
static Node *dummy_select(List *targetList, Node *whereClause, List *valuesLists);
static Node *dummy_insert(List *cols);
static Node *dummy_update(List *targetList);

static size_t deparse_stmt_len(Node *node);
static StringInfo deparse_raw_stmt_list(List *stmts);

/*  Given a walked parse tree and summary, store the truncated version in `summary`. */
void
pg_query_summary_truncate(Summary * summary, Node *tree, int truncate_limit)
{
	TruncationState state = {NULL, 0};

	StringInfo	output = deparse_raw_stmt_list((List *) tree);

	if (output->len <= truncate_limit)
	{
		summary->truncated_query = output->data;
		return;
	}

	destroyStringInfo(output);

	generate_possible_truncations(tree, &state);

	list_sort(state.truncations, cmp_possible_truncations);
	apply_truncations(summary, tree, &state, truncate_limit);
}

static void
truncate_mbstr(char *mbstr, size_t max_chars)
{
	/* Determine the number of characters in mbstr. */
	int			n_chars = pg_mbstrlen(mbstr);

	/* If we don't need to truncate the string, return immediately. */
	if (n_chars <= max_chars)
		return;

	/* Determine how many bytes hold `max_chars - 3`. */
	int			n_bytes = pg_mbcharcliplen(mbstr, strlen(mbstr), max_chars - 3);

	/* Actually truncate it. */
	strncpy(mbstr + n_bytes, "...", 4);
	mbstr[n_bytes + 3] = '\0';
}

static void
add_truncation(TruncationState * state, enum TruncationAttr attr,
			   Node *node, int32_t length)
{
	/* Don't bother truncating if it won't become shorter. */
	if (length <= 3)
		return;

	PossibleTruncation *truncation = palloc(sizeof(PossibleTruncation));

	truncation->attr = attr;
	truncation->node = node;
	truncation->depth = state->depth;
	truncation->length = length;

	state->truncations = lappend(state->truncations, truncation);
}

static void
add_truncation_where_clause(TruncationState * state, Node *node, Node *whereClause)
{
	if (whereClause == NULL)
		return;

	add_truncation(state,
				   TRUNCATION_WHERE_CLAUSE,
				   node,
				   where_clause_len(whereClause));
}

static bool
generate_possible_truncations(Node *node, TruncationState * state)
{
	if (node == NULL)
		return false;

	switch (nodeTag(node))
	{
		case T_RawStmt:
			return generate_possible_truncations(castNode(RawStmt, node)->stmt, state);

		case T_SelectStmt:
			{
				SelectStmt *stmt = castNode(SelectStmt, node);

				if (stmt->targetList != NULL)
					add_truncation(state,
								   TRUNCATION_TARGET_LIST,
								   node,
								   select_target_list_len(stmt->targetList));

				add_truncation_where_clause(state, node, stmt->whereClause);

				if (stmt->valuesLists != NULL)
					add_truncation(state,
								   TRUNCATION_VALUES_LISTS,
								   node,
								   select_values_lists_len(stmt->valuesLists));

				break;
			}

		case T_InsertStmt:
			{
				InsertStmt *stmt = castNode(InsertStmt, node);

				if (stmt->cols != NULL)
					add_truncation(state, TRUNCATION_COLS, node, cols_len(stmt->cols));

				break;
			}

		case T_UpdateStmt:
			{
				UpdateStmt *stmt = castNode(UpdateStmt, node);

				if (stmt->targetList != NULL)
					add_truncation(state,
								   TRUNCATION_TARGET_LIST,
								   node,
								   update_target_list_len(stmt->targetList));

				add_truncation_where_clause(state, node, stmt->whereClause);

				break;
			}

		case T_DeleteStmt:
			{
				DeleteStmt *stmt = castNode(DeleteStmt, node);

				add_truncation_where_clause(state, node, stmt->whereClause);
				break;
			}

		case T_CopyStmt:
			{
				CopyStmt   *stmt = castNode(CopyStmt, node);

				add_truncation_where_clause(state, node, stmt->whereClause);
				break;
			}

		case T_IndexStmt:
			{
				IndexStmt  *stmt = castNode(IndexStmt, node);

				add_truncation_where_clause(state, node, stmt->whereClause);
				break;
			}

		case T_RuleStmt:
			{
				RuleStmt   *stmt = castNode(RuleStmt, node);

				add_truncation_where_clause(state, node, stmt->whereClause);
				break;
			}

		case T_CommonTableExpr:
			{
				CommonTableExpr *stmt = castNode(CommonTableExpr, node);

				if (stmt->ctequery != NULL)
				{
					size_t		query_len = deparse_stmt_len((Node *) stmt->ctequery);

					add_truncation(state,
								   TRUNCATION_CTE_QUERY,
								   node,
								   query_len);
				}

				break;
			}

		case T_InferClause:
			{
				InferClause *stmt = castNode(InferClause, node);

				add_truncation_where_clause(state, node, stmt->whereClause);
				break;
			}

		case T_OnConflictClause:
			{
				OnConflictClause *stmt = castNode(OnConflictClause, node);

				if (stmt->targetList != NULL)
					add_truncation(state,
								   TRUNCATION_TARGET_LIST,
								   node,
								   update_target_list_len(stmt->targetList));

				add_truncation_where_clause(state, node, stmt->whereClause);

				break;
			}

		default:
			break;
	}

	if (!pg_query_raw_tree_walker_supports(node))
		return false;

	int			old_depth = state->depth;

	state->depth++;

	bool		result = raw_expression_tree_walker(node, generate_possible_truncations, (void *) state);

	/* Restore old depth value, since the current node (or its parents) may */
	/* have sibling elements. */
	state->depth = old_depth;

	return result;
}

static int
cmp_possible_truncations(const ListCell *a, const ListCell *b)
{
	const		PossibleTruncation *pt_a = lfirst(a);
	const		PossibleTruncation *pt_b = lfirst(b);

	int			depth_cmp = pt_b->depth - pt_a->depth;

	if (depth_cmp != 0)
		return depth_cmp;

	return pt_b->length - pt_a->length;
}

static void
global_replace(char *str, char *pattern, char *replacement)
{
	size_t		plen = strlen(pattern);
	size_t		rlen = strlen(replacement);
	char	   *s = str;

	Assert(plen >= rlen);

	while ((s = strstr(s, pattern)) != NULL)
	{
		memcpy(s, replacement, rlen);

		/* Shift remainder of the string if needed */
		if (plen > rlen)
			memmove(s + rlen, s + plen, strlen(s + plen) + 1);

		s += rlen;
	}
}

static void
apply_truncations(Summary * summary, Node *tree, TruncationState * state, int truncation_limit)
{
	List	   *truncations = state->truncations;
	StringInfo	output = NULL;
	ListCell   *lc;

	foreach(lc, state->truncations)
	{
		PossibleTruncation *truncation = lfirst(lc);

		Node	   *node = truncation->node;
		enum TruncationAttr attr = truncation->attr;

		if (IsA(node, SelectStmt) && attr == TRUNCATION_TARGET_LIST)
			castNode(SelectStmt, node)->targetList = list_make1(dummy_target());
		else if (IsA(node, SelectStmt) && attr == TRUNCATION_WHERE_CLAUSE)
			castNode(SelectStmt, node)->whereClause = (Node *) dummy_column();
		else if (IsA(node, SelectStmt) && attr == TRUNCATION_VALUES_LISTS)
			castNode(SelectStmt, node)->valuesLists = list_make1(list_make1(dummy_column()));
		else if (IsA(node, UpdateStmt) && attr == TRUNCATION_TARGET_LIST)
			castNode(UpdateStmt, node)->targetList = list_make1(dummy_target());
		else if (IsA(node, InsertStmt) && attr == TRUNCATION_COLS)
			castNode(InsertStmt, node)->cols = list_make1(dummy_target());
		else if (IsA(node, UpdateStmt) && attr == TRUNCATION_WHERE_CLAUSE)
			castNode(UpdateStmt, node)->whereClause = (Node *) dummy_column();
		else if (IsA(node, DeleteStmt) && attr == TRUNCATION_WHERE_CLAUSE)
			castNode(DeleteStmt, node)->whereClause = (Node *) dummy_column();
		else if (IsA(node, CopyStmt) && attr == TRUNCATION_WHERE_CLAUSE)
			castNode(CopyStmt, node)->whereClause = (Node *) dummy_column();
		else if (IsA(node, IndexStmt) && attr == TRUNCATION_WHERE_CLAUSE)
			castNode(IndexStmt, node)->whereClause = (Node *) dummy_column();
		else if (IsA(node, RuleStmt) && attr == TRUNCATION_WHERE_CLAUSE)
			castNode(RuleStmt, node)->whereClause = (Node *) dummy_column();
		else if (IsA(node, CommonTableExpr) && attr == TRUNCATION_CTE_QUERY)
			castNode(CommonTableExpr, node)->ctequery = dummy_select(NULL, (Node *) dummy_column(), NULL);
		else if (IsA(node, InferClause) && attr == TRUNCATION_WHERE_CLAUSE)
			castNode(InferClause, node)->whereClause = (Node *) dummy_column();
		else if (IsA(node, OnConflictClause) && attr == TRUNCATION_TARGET_LIST)
			castNode(OnConflictClause, node)->targetList = list_make1(dummy_target());
		else if (IsA(node, OnConflictClause) && attr == TRUNCATION_WHERE_CLAUSE)
			castNode(OnConflictClause, node)->whereClause = (Node *) dummy_column();
		else
			elog(ERROR, "apply_truncations() got unknown truncation type");

		if (output)
			destroyStringInfo(output);
		output = deparse_raw_stmt_list((List *) tree);

		global_replace(output->data, "SELECT \"\" AS \"\"", "SELECT \"\"");
		global_replace(output->data, "SELECT WHERE \"\"", "\"\"");
		global_replace(output->data, "\"\"", "...");

		if (strlen(output->data) <= truncation_limit)
		{
			summary->truncated_query = output->data;
			return;
		}
	}

	if (!output)
		output = deparse_raw_stmt_list((List *) tree);

	truncate_mbstr(output->data, truncation_limit);
	summary->truncated_query = output->data;
}

static ColumnRef *
dummy_column(void)
{
	ColumnRef  *colref = makeNode(ColumnRef);

	colref->fields = list_make1(makeString(pstrdup("")));
	colref->location = 0;

	return colref;
}

static ResTarget *
dummy_target(void)
{
	ResTarget  *target = makeNode(ResTarget);

	target->name = pstrdup("");
	target->val = (Node *) dummy_column();

	/*
	 * TODO:docs for ResTarget say "-1 if unknown"-- would that be more
	 * correct ? (see also, dummy_column())
	 */
	target->location = 0;

	return target;
}

static Node *
dummy_select(List *targetList, Node *whereClause, List *valuesLists)
{
	SelectStmt *stmt = makeNode(SelectStmt);

	stmt->targetList = targetList;
	stmt->whereClause = whereClause;
	stmt->valuesLists = valuesLists;

	return (Node *) stmt;
}

static Node *
dummy_insert(List *cols)
{
	RangeVar   *rv = makeNode(RangeVar);

	rv->relname = pstrdup("x");
	rv->inh = true;
	rv->relpersistence = 'p';
	rv->location = 0;

	InsertStmt *stmt = makeNode(InsertStmt);

	stmt->relation = rv;
	stmt->cols = cols;
	stmt->override = 1;

	return (Node *) stmt;
}

static Node *
dummy_update(List *targetList)
{
	RangeVar   *rv = makeNode(RangeVar);

	rv->relname = pstrdup("x");
	rv->inh = true;
	rv->relpersistence = 'p';
	rv->location = 0;

	UpdateStmt *stmt = makeNode(UpdateStmt);

	stmt->relation = rv;
	stmt->targetList = targetList;

	return (Node *) stmt;
}

static int32_t
select_target_list_len(List *nodes)
{
	size_t		result_len = deparse_stmt_len(dummy_select(nodes, NULL, NULL));
	size_t		dummy_len = 7;	/* "SELECT " */

	return (int32_t) result_len - dummy_len;
}

static int32_t
select_values_lists_len(List *nodes)
{
	size_t		result_len = deparse_stmt_len(dummy_select(NULL, NULL, nodes));
	size_t		dummy_len = 9;	/* "VALUES ()" */

	return (int32_t) result_len - dummy_len;
}

static int32_t
update_target_list_len(List *nodes)
{
	size_t		result_len = deparse_stmt_len(dummy_update(nodes));
	size_t		dummy_len = 13; /* "UPDATE x SET " */

	return (int32_t) result_len - dummy_len;
}

static int32_t
where_clause_len(Node *node)
{
	size_t		result_len = deparse_stmt_len(dummy_select(NULL, node, NULL));
	size_t		dummy_len = 13; /* "SELECT WHERE " */

	return (int32_t) result_len - dummy_len;
}

static int32_t
cols_len(List *nodes)
{
	size_t		result_len = deparse_stmt_len(dummy_insert(nodes));
	size_t		dummy_len = 31; /* "INSERT INTO x () DEFAULT VALUES" */

	return (int32_t) result_len - dummy_len;
}

static size_t
deparse_stmt_len(Node *node)
{
	if (!IsA(node, RawStmt))
	{
		RawStmt    *raw = makeNode(RawStmt);

		raw->stmt = node;
		raw->stmt_location = -1;
		raw->stmt_len = 0;
		node = (Node *) raw;
	}

	StringInfo	str = deparse_raw_stmt_list(list_make1(node));
	size_t		len = str->len;

	destroyStringInfo(str);
	return len;
}

static StringInfo
deparse_raw_stmt_list(List *stmts)
{
	PostgresDeparseOpts opts = {0};
	StringInfo	str = makeStringInfo();
	ListCell   *lc;

	foreach(lc, stmts)
	{
		deparseRawStmtOpts(str, castNode(RawStmt, lfirst(lc)), &opts);
		if (lnext(stmts, lc))
			appendStringInfoString(str, "; ");
	}

	return str;
}