Branch data Line data Source code
1 : : %top{
2 : : /*-------------------------------------------------------------------------
3 : : *
4 : : * psqlscan.l
5 : : * lexical scanner for SQL commands
6 : : *
7 : : * This lexer used to be part of psql, and that heritage is reflected in
8 : : * the file name as well as function and typedef names, though it can now
9 : : * be used by other frontend programs as well. It's also possible to extend
10 : : * this lexer with a compatible add-on lexer to handle program-specific
11 : : * backslash commands.
12 : : *
13 : : * This code is mainly concerned with determining where the end of a SQL
14 : : * statement is: we are looking for semicolons that are not within quotes,
15 : : * comments, or parentheses. The most reliable way to handle this is to
16 : : * borrow the backend's flex lexer rules, lock, stock, and barrel. The rules
17 : : * below are (except for a few) the same as the backend's, but their actions
18 : : * are just ECHO whereas the backend's actions generally do other things.
19 : : *
20 : : * XXX The rules in this file must be kept in sync with the backend lexer!!!
21 : : *
22 : : * XXX Avoid creating backtracking cases --- see the backend lexer for info.
23 : : *
24 : : * See psqlscan_int.h for additional commentary.
25 : : *
26 : : *
27 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
28 : : * Portions Copyright (c) 1994, Regents of the University of California
29 : : *
30 : : * IDENTIFICATION
31 : : * src/fe_utils/psqlscan.l
32 : : *
33 : : *-------------------------------------------------------------------------
34 : : */
35 : : #include "postgres_fe.h"
36 : :
37 : : #include "common/logging.h"
38 : : #include "fe_utils/psqlscan.h"
39 : :
40 : : #include "libpq-fe.h"
41 : : }
42 : :
43 : : %{
44 : :
45 : : /* LCOV_EXCL_START */
46 : :
47 : : #include "fe_utils/psqlscan_int.h"
48 : :
49 : : /*
50 : : * We must have a typedef YYSTYPE for yylex's first argument, but this lexer
51 : : * doesn't presently make use of that argument, so just declare it as int.
52 : : */
53 : : typedef int YYSTYPE;
54 : :
55 : :
56 : : /* Return values from yylex() */
57 : : #define LEXRES_EOL 0 /* end of input */
58 : : #define LEXRES_SEMI 1 /* command-terminating semicolon found */
59 : : #define LEXRES_BACKSLASH 2 /* backslash command start */
60 : :
61 : :
62 : : #define ECHO psqlscan_emit(cur_state, yytext, yyleng)
63 : :
64 : : static bool psqlscan_is_copy_from_stdin(PsqlScanState state);
65 : : static void psqlscan_track_identifier(PsqlScanState state,
66 : : const char *identifier);
67 : :
68 : : %}
69 : :
70 : : %option reentrant
71 : : %option bison-bridge
72 : : %option 8bit
73 : : %option never-interactive
74 : : %option nodefault
75 : : %option noinput
76 : : %option nounput
77 : : %option noyywrap
78 : : %option warn
79 : : %option prefix="psql_yy"
80 : :
81 : : /*
82 : : * Set the type of yyextra; we use it as a pointer back to the containing
83 : : * PsqlScanState.
84 : : */
85 : : %option extra-type="PsqlScanState"
86 : :
87 : : /*
88 : : * All of the following definitions and rules should exactly match
89 : : * src/backend/parser/scan.l so far as the flex patterns are concerned.
90 : : * The rule bodies are just ECHO as opposed to what the backend does,
91 : : * however. (But be sure to duplicate code that affects the lexing process,
92 : : * such as BEGIN() and yyless().) Also, psqlscan uses a single <<EOF>> rule
93 : : * whereas scan.l has a separate one for each exclusive state.
94 : : */
95 : :
96 : : /*
97 : : * OK, here is a short description of lex/flex rules behavior.
98 : : * The longest pattern which matches an input string is always chosen.
99 : : * For equal-length patterns, the first occurring in the rules list is chosen.
100 : : * INITIAL is the starting state, to which all non-conditional rules apply.
101 : : * Exclusive states change parsing rules while the state is active. When in
102 : : * an exclusive state, only those rules defined for that state apply.
103 : : *
104 : : * We use exclusive states for quoted strings, extended comments,
105 : : * and to eliminate parsing troubles for numeric strings.
106 : : * Exclusive states:
107 : : * <xb> bit string literal
108 : : * <xc> extended C-style comments
109 : : * <xd> delimited identifiers (double-quoted identifiers)
110 : : * <xh> hexadecimal byte string
111 : : * <xq> standard quoted strings
112 : : * <xqs> quote stop (detect continued strings)
113 : : * <xe> extended quoted strings (support backslash escape sequences)
114 : : * <xdolq> $foo$ quoted strings
115 : : * <xui> quoted identifier with Unicode escapes
116 : : * <xus> quoted string with Unicode escapes
117 : : *
118 : : * Note: we intentionally don't mimic the backend's <xeu> state; we have
119 : : * no need to distinguish it from <xe> state, and no good way to get out
120 : : * of it in error cases. The backend just throws yyerror() in those
121 : : * cases, but that's not an option here.
122 : : */
123 : :
124 : : %x xb
125 : : %x xc
126 : : %x xd
127 : : %x xh
128 : : %x xq
129 : : %x xqs
130 : : %x xe
131 : : %x xdolq
132 : : %x xui
133 : : %x xus
134 : :
135 : : /*
136 : : * In order to make the world safe for Windows and Mac clients as well as
137 : : * Unix ones, we accept either \n or \r as a newline. A DOS-style \r\n
138 : : * sequence will be seen as two successive newlines, but that doesn't cause
139 : : * any problems. Comments that start with -- and extend to the next
140 : : * newline are treated as equivalent to a single whitespace character.
141 : : *
142 : : * NOTE a fine point: if there is no newline following --, we will absorb
143 : : * everything to the end of the input as a comment. This is correct. Older
144 : : * versions of Postgres failed to recognize -- as a comment if the input
145 : : * did not end with a newline.
146 : : *
147 : : * non_newline_space tracks all space characters except newlines.
148 : : *
149 : : * XXX if you change the set of whitespace characters, fix scanner_isspace()
150 : : * to agree.
151 : : */
152 : :
153 : : space [ \t\n\r\f\v]
154 : : non_newline_space [ \t\f\v]
155 : : newline [\n\r]
156 : : non_newline [^\n\r]
157 : :
158 : : comment ("--"{non_newline}*)
159 : :
160 : : whitespace ({space}+|{comment})
161 : :
162 : : /*
163 : : * SQL requires at least one newline in the whitespace separating
164 : : * string literals that are to be concatenated. Silly, but who are we
165 : : * to argue? Note that {whitespace_with_newline} should not have * after
166 : : * it, whereas {whitespace} should generally have a * after it...
167 : : */
168 : :
169 : : special_whitespace ({space}+|{comment}{newline})
170 : : non_newline_whitespace ({non_newline_space}|{comment})
171 : : whitespace_with_newline ({non_newline_whitespace}*{newline}{special_whitespace}*)
172 : :
173 : : quote '
174 : : /* If we see {quote} then {quotecontinue}, the quoted string continues */
175 : : quotecontinue {whitespace_with_newline}{quote}
176 : :
177 : : /*
178 : : * {quotecontinuefail} is needed to avoid lexer backup when we fail to match
179 : : * {quotecontinue}. It might seem that this could just be {whitespace}*,
180 : : * but if there's a dash after {whitespace_with_newline}, it must be consumed
181 : : * to see if there's another dash --- which would start a {comment} and thus
182 : : * allow continuation of the {quotecontinue} token.
183 : : */
184 : : quotecontinuefail {whitespace}*"-"?
185 : :
186 : : /* Bit string
187 : : * It is tempting to scan the string for only those characters
188 : : * which are allowed. However, this leads to silently swallowed
189 : : * characters if illegal characters are included in the string.
190 : : * For example, if xbinside is [01] then B'ABCD' is interpreted
191 : : * as a zero-length string, and the ABCD' is lost!
192 : : * Better to pass the string forward and let the input routines
193 : : * validate the contents.
194 : : */
195 : : xbstart [bB]{quote}
196 : : xbinside [^']*
197 : :
198 : : /* Hexadecimal byte string */
199 : : xhstart [xX]{quote}
200 : : xhinside [^']*
201 : :
202 : : /* National character */
203 : : xnstart [nN]{quote}
204 : :
205 : : /* Quoted string that allows backslash escapes */
206 : : xestart [eE]{quote}
207 : : xeinside [^\\']+
208 : : xeescape [\\][^0-7]
209 : : xeoctesc [\\][0-7]{1,3}
210 : : xehexesc [\\]x[0-9A-Fa-f]{1,2}
211 : : xeunicode [\\](u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})
212 : : xeunicodefail [\\](u[0-9A-Fa-f]{0,3}|U[0-9A-Fa-f]{0,7})
213 : :
214 : : /* Extended quote
215 : : * xqdouble implements embedded quote, ''''
216 : : */
217 : : xqstart {quote}
218 : : xqdouble {quote}{quote}
219 : : xqinside [^']+
220 : :
221 : : /* $foo$ style quotes ("dollar quoting")
222 : : * The quoted string starts with $foo$ where "foo" is an optional string
223 : : * in the form of an identifier, except that it may not contain "$",
224 : : * and extends to the first occurrence of an identical string.
225 : : * There is *no* processing of the quoted text.
226 : : *
227 : : * {dolqfailed} is an error rule to avoid scanner backup when {dolqdelim}
228 : : * fails to match its trailing "$".
229 : : */
230 : : dolq_start [A-Za-z\200-\377_]
231 : : dolq_cont [A-Za-z\200-\377_0-9]
232 : : dolqdelim \$({dolq_start}{dolq_cont}*)?\$
233 : : dolqfailed \${dolq_start}{dolq_cont}*
234 : : dolqinside [^$]+
235 : :
236 : : /* Double quote
237 : : * Allows embedded spaces and other special characters into identifiers.
238 : : */
239 : : dquote \"
240 : : xdstart {dquote}
241 : : xdstop {dquote}
242 : : xddouble {dquote}{dquote}
243 : : xdinside [^"]+
244 : :
245 : : /* Quoted identifier with Unicode escapes */
246 : : xuistart [uU]&{dquote}
247 : :
248 : : /* Quoted string with Unicode escapes */
249 : : xusstart [uU]&{quote}
250 : :
251 : : /* error rule to avoid backup */
252 : : xufailed [uU]&
253 : :
254 : :
255 : : /* C-style comments
256 : : *
257 : : * The "extended comment" syntax closely resembles allowable operator syntax.
258 : : * The tricky part here is to get lex to recognize a string starting with
259 : : * slash-star as a comment, when interpreting it as an operator would produce
260 : : * a longer match --- remember lex will prefer a longer match! Also, if we
261 : : * have something like plus-slash-star, lex will think this is a 3-character
262 : : * operator whereas we want to see it as a + operator and a comment start.
263 : : * The solution is two-fold:
264 : : * 1. append {op_chars}* to xcstart so that it matches as much text as
265 : : * {operator} would. Then the tie-breaker (first matching rule of same
266 : : * length) ensures xcstart wins. We put back the extra stuff with yyless()
267 : : * in case it contains a star-slash that should terminate the comment.
268 : : * 2. In the operator rule, check for slash-star within the operator, and
269 : : * if found throw it back with yyless(). This handles the plus-slash-star
270 : : * problem.
271 : : * Dash-dash comments have similar interactions with the operator rule.
272 : : */
273 : : xcstart \/\*{op_chars}*
274 : : xcstop \*+\/
275 : : xcinside [^*/]+
276 : :
277 : : ident_start [A-Za-z\200-\377_]
278 : : ident_cont [A-Za-z\200-\377_0-9\$]
279 : :
280 : : identifier {ident_start}{ident_cont}*
281 : :
282 : : /* Assorted special-case operators and operator-like tokens */
283 : : typecast "::"
284 : : dot_dot \.\.
285 : : colon_equals ":="
286 : :
287 : : /*
288 : : * These operator-like tokens (unlike the above ones) also match the {operator}
289 : : * rule, which means that they might be overridden by a longer match if they
290 : : * are followed by a comment start or a + or - character. Accordingly, if you
291 : : * add to this list, you must also add corresponding code to the {operator}
292 : : * block to return the correct token in such cases. (This is not needed in
293 : : * psqlscan.l since the token value is ignored there.)
294 : : */
295 : : equals_greater "=>"
296 : : less_equals "<="
297 : : greater_equals ">="
298 : : less_greater "<>"
299 : : not_equals "!="
300 : :
301 : : /*
302 : : * "self" is the set of chars that should be returned as single-character
303 : : * tokens. "op_chars" is the set of chars that can make up "Op" tokens,
304 : : * which can be one or more characters long (but if a single-char token
305 : : * appears in the "self" set, it is not to be returned as an Op). Note
306 : : * that the sets overlap, but each has some chars that are not in the other.
307 : : *
308 : : * If you change either set, adjust the character lists appearing in the
309 : : * rule for "operator"!
310 : : */
311 : : self [,()\[\].;\:\+\-\*\/\%\^\<\>\=]
312 : : op_chars [\~\!\@\#\^\&\|\`\?\+\-\*\/\%\<\>\=]
313 : : operator {op_chars}+
314 : :
315 : : /*
316 : : * Numbers
317 : : *
318 : : * Unary minus is not part of a number here. Instead we pass it separately to
319 : : * the parser, and there it gets coerced via doNegate().
320 : : *
321 : : * {numericfail} is used because we would like "1..10" to lex as 1, dot_dot, 10.
322 : : *
323 : : * {realfail} is added to prevent the need for scanner
324 : : * backup when the {real} rule fails to match completely.
325 : : */
326 : : decdigit [0-9]
327 : : hexdigit [0-9A-Fa-f]
328 : : octdigit [0-7]
329 : : bindigit [0-1]
330 : :
331 : : decinteger {decdigit}(_?{decdigit})*
332 : : hexinteger 0[xX](_?{hexdigit})+
333 : : octinteger 0[oO](_?{octdigit})+
334 : : bininteger 0[bB](_?{bindigit})+
335 : :
336 : : hexfail 0[xX]_?
337 : : octfail 0[oO]_?
338 : : binfail 0[bB]_?
339 : :
340 : : numeric (({decinteger}\.{decinteger}?)|(\.{decinteger}))
341 : : numericfail {decinteger}\.\.
342 : :
343 : : real ({decinteger}|{numeric})[Ee][-+]?{decinteger}
344 : : realfail ({decinteger}|{numeric})[Ee][-+]
345 : :
346 : : /* Positional parameters don't accept underscores. */
347 : : param \${decdigit}+
348 : :
349 : : /*
350 : : * An identifier immediately following an integer literal is disallowed because
351 : : * in some cases it's ambiguous what is meant: for example, 0x1234 could be
352 : : * either a hexinteger or a decinteger "0" and an identifier "x1234". We can
353 : : * detect such problems by seeing if integer_junk matches a longer substring
354 : : * than any of the XXXinteger patterns (decinteger, hexinteger, octinteger,
355 : : * bininteger). One "junk" pattern is sufficient because
356 : : * {decinteger}{identifier} will match all the same strings we'd match with
357 : : * {hexinteger}{identifier} etc.
358 : : *
359 : : * Note that the rule for integer_junk must appear after the ones for
360 : : * XXXinteger to make this work correctly: 0x1234 will match both hexinteger
361 : : * and integer_junk, and we need hexinteger to be chosen in that case.
362 : : *
363 : : * Also disallow strings matched by numeric_junk, real_junk and param_junk
364 : : * for consistency.
365 : : */
366 : : integer_junk {decinteger}{identifier}
367 : : numeric_junk {numeric}{identifier}
368 : : real_junk {real}{identifier}
369 : : param_junk \${decdigit}+{identifier}
370 : :
371 : : /* psql-specific: characters allowed in variable names */
372 : : variable_char [A-Za-z\200-\377_0-9]
373 : :
374 : : other .
375 : :
376 : : /*
377 : : * Dollar quoted strings are totally opaque, and no escaping is done on them.
378 : : * Other quoted strings must allow some special characters such as single-quote
379 : : * and newline.
380 : : * Embedded single-quotes are implemented both in the SQL standard
381 : : * style of two adjacent single quotes "''" and in the Postgres/Java style
382 : : * of escaped-quote "\'".
383 : : * Other embedded escaped characters are matched explicitly and the leading
384 : : * backslash is dropped from the string.
385 : : * Note that xcstart must appear before operator, as explained above!
386 : : * Also whitespace (comment) must appear before operator.
387 : : */
388 : :
389 : : %%
390 : :
391 : : %{
392 : : /* Declare some local variables inside yylex(), for convenience */
393 : : PsqlScanState cur_state = yyextra;
394 : 798387 : PQExpBuffer output_buf = cur_state->output_buf;
395 : 798387 :
396 : : /*
397 : : * Force flex into the state indicated by start_state. This has a
398 : : * couple of purposes: it lets some of the functions below set a new
399 : : * starting state without ugly direct access to flex variables, and it
400 : : * allows us to transition from one flex lexer to another so that we
401 : : * can lex different parts of the source string using separate lexers.
402 : : */
403 : : BEGIN(cur_state->start_state);
404 : 798387 : %}
405 : :
406 : : {whitespace} {
407 : : /*
408 : : * Note that the whitespace rule includes both true
409 : : * whitespace and single-line ("--" style) comments.
410 : : * We suppress whitespace until we have collected some
411 : : * non-whitespace data. (This interacts with some
412 : : * decisions in MainLoop(); see there for details.)
413 : : */
414 : : if (output_buf->len > 0)
415 [ + + ]: 1900800 : ECHO;
416 : 1787858 : }
417 : :
418 : 1900800 : {xcstart} {
419 : 483 : cur_state->xcdepth = 0;
420 : 483 : BEGIN(xc);
421 : 483 : /* Put back any characters past slash-star; see above */
422 : : yyless(2);
423 : 483 : ECHO;
424 : 483 : }
425 : :
426 : 483 : <xc>{
427 : : {xcstart} {
428 : 12 : cur_state->xcdepth++;
429 : 12 : /* Put back any characters past slash-star; see above */
430 : : yyless(2);
431 : 12 : ECHO;
432 : 12 : }
433 : :
434 : 12 : {xcstop} {
435 : 495 : if (cur_state->xcdepth <= 0)
436 [ + + ]: 495 : BEGIN(INITIAL);
437 : 483 : else
438 : : cur_state->xcdepth--;
439 : 12 : ECHO;
440 : 495 : }
441 : :
442 : 495 : {xcinside} {
443 : 1147 : ECHO;
444 : 1147 : }
445 : :
446 : 1147 : {op_chars} {
447 : 352 : ECHO;
448 : 352 : }
449 : :
450 : 352 : \*+ {
451 : 0 : ECHO;
452 : 0 : }
453 : : } /* <xc> */
454 : 0 :
455 : : {xbstart} {
456 : 508 : BEGIN(xb);
457 : 508 : ECHO;
458 : 508 : }
459 : : <xh>{xhinside} |
460 : 508 : <xb>{xbinside} {
461 : 2703 : ECHO;
462 : 2703 : }
463 : :
464 : 2703 : {xhstart} {
465 : 2215 : /* Hexadecimal bit type.
466 : : * At some point we should simply pass the string
467 : : * forward to the parser and label it there.
468 : : * In the meantime, place a leading "x" on the string
469 : : * to mark it for the input routine as a hex string.
470 : : */
471 : : BEGIN(xh);
472 : 2215 : ECHO;
473 : 2215 : }
474 : :
475 : 2215 : {xnstart} {
476 : 0 : yyless(1); /* eat only 'n' this time */
477 : 0 : ECHO;
478 : 0 : }
479 : :
480 : 0 : {xqstart} {
481 : 156701 : if (cur_state->std_strings)
482 [ + - ]: 156701 : BEGIN(xq);
483 : 156701 : else
484 : : BEGIN(xe);
485 : 0 : ECHO;
486 : 156701 : }
487 : : {xestart} {
488 : 156701 : BEGIN(xe);
489 : 933 : ECHO;
490 : 933 : }
491 : : {xusstart} {
492 : 933 : BEGIN(xus);
493 : 468 : ECHO;
494 : 468 : }
495 : :
496 : 468 : <xb,xh,xq,xe,xus>{quote} {
497 : 160825 : /*
498 : : * When we are scanning a quoted string and see an end
499 : : * quote, we must look ahead for a possible continuation.
500 : : * If we don't see one, we know the end quote was in fact
501 : : * the end of the string. To reduce the lexer table size,
502 : : * we use a single "xqs" state to do the lookahead for all
503 : : * types of strings.
504 : : */
505 : : cur_state->state_before_str_stop = YYSTATE;
506 : 160825 : BEGIN(xqs);
507 : 160825 : ECHO;
508 : 160825 : }
509 : : <xqs>{quotecontinue} {
510 : 160825 : /*
511 : 0 : * Found a quote continuation, so return to the in-quote
512 : : * state and continue scanning the literal. Nothing is
513 : : * added to the literal's contents.
514 : : */
515 : : BEGIN(cur_state->state_before_str_stop);
516 : 0 : ECHO;
517 : 0 : }
518 : : <xqs>{quotecontinuefail} |
519 : 0 : <xqs>{other} {
520 : 159998 : /*
521 : : * Failed to see a quote continuation. Throw back
522 : : * everything after the end quote, and handle the string
523 : : * according to the state we were in previously.
524 : : */
525 : : yyless(0);
526 : 159998 : BEGIN(INITIAL);
527 : 159998 : /* There's nothing to echo ... */
528 : : }
529 : :
530 : 159998 : <xq,xe,xus>{xqdouble} {
531 : 4129 : ECHO;
532 : 4129 : }
533 : : <xq,xus>{xqinside} {
534 : 4129 : ECHO;
535 : 164483 : }
536 : : <xe>{xeinside} {
537 : 164483 : ECHO;
538 : 1691 : }
539 : : <xe>{xeunicode} {
540 : 1691 : ECHO;
541 : 132 : }
542 : : <xe>{xeunicodefail} {
543 : 132 : ECHO;
544 : 8 : }
545 : : <xe>{xeescape} {
546 : 8 : ECHO;
547 : 1018 : }
548 : : <xe>{xeoctesc} {
549 : 1018 : ECHO;
550 : 14 : }
551 : : <xe>{xehexesc} {
552 : 14 : ECHO;
553 : 6 : }
554 : : <xe>. {
555 : 6 : /* This is only needed for \ just before EOF */
556 : 0 : ECHO;
557 : 0 : }
558 : :
559 : 0 : {dolqdelim} {
560 : 4647 : cur_state->dolqstart = pg_strdup(yytext);
561 : 4647 : BEGIN(xdolq);
562 : 4647 : ECHO;
563 : 4647 : }
564 : : {dolqfailed} {
565 : 4647 : /* throw back all but the initial "$" */
566 : 0 : yyless(1);
567 : 0 : ECHO;
568 : 0 : }
569 : : <xdolq>{dolqdelim} {
570 : 0 : if (strcmp(yytext, cur_state->dolqstart) == 0)
571 [ + + ]: 4863 : {
572 : : free(cur_state->dolqstart);
573 : 4647 : cur_state->dolqstart = NULL;
574 : 4647 : BEGIN(INITIAL);
575 : 4647 : }
576 : : else
577 : : {
578 : : /*
579 : : * When we fail to match $...$ to dolqstart, transfer
580 : : * the $... part to the output, but put back the final
581 : : * $ for rescanning. Consider $delim$...$junk$delim$
582 : : */
583 : : yyless(yyleng - 1);
584 : 216 : }
585 : : ECHO;
586 : 4863 : }
587 : : <xdolq>{dolqinside} {
588 : 4863 : ECHO;
589 : 24731 : }
590 : : <xdolq>{dolqfailed} {
591 : 24731 : ECHO;
592 : 669 : }
593 : : <xdolq>. {
594 : 669 : /* This is only needed for $ inside the quoted text */
595 : 1630 : ECHO;
596 : 1630 : }
597 : :
598 : 1630 : {xdstart} {
599 : 7440 : BEGIN(xd);
600 : 7440 : ECHO;
601 : 7440 : }
602 : : {xuistart} {
603 : 7440 : BEGIN(xui);
604 : 16 : ECHO;
605 : 16 : }
606 : : <xd>{xdstop} {
607 : 16 : BEGIN(INITIAL);
608 : 7440 : ECHO;
609 : 7440 : }
610 : : <xui>{dquote} {
611 : 7440 : BEGIN(INITIAL);
612 : 16 : ECHO;
613 : 16 : }
614 : : <xd,xui>{xddouble} {
615 : 16 : ECHO;
616 : 75 : }
617 : : <xd,xui>{xdinside} {
618 : 75 : ECHO;
619 : 7521 : }
620 : :
621 : 7521 : {xufailed} {
622 : 0 : /* throw back all but the initial u/U */
623 : : yyless(1);
624 : 0 : ECHO;
625 : 0 : }
626 : :
627 : 0 : {typecast} {
628 : 37697 : ECHO;
629 : 37697 : }
630 : :
631 : 37697 : {dot_dot} {
632 : 0 : ECHO;
633 : 0 : }
634 : :
635 : 0 : {colon_equals} {
636 : 1675 : ECHO;
637 : 1675 : }
638 : :
639 : 1675 : {equals_greater} {
640 : 1567 : ECHO;
641 : 1567 : }
642 : :
643 : 1567 : {less_equals} {
644 : 1496 : ECHO;
645 : 1496 : }
646 : :
647 : 1496 : {greater_equals} {
648 : 4307 : ECHO;
649 : 4307 : }
650 : :
651 : 4307 : {less_greater} {
652 : 921 : ECHO;
653 : 921 : }
654 : :
655 : 921 : {not_equals} {
656 : 1490 : ECHO;
657 : 1490 : }
658 : :
659 : 1490 : /*
660 : : * These rules are specific to psql --- they implement parenthesis
661 : : * counting and detection of command-ending semicolon. These must
662 : : * appear before the {self} rule so that they take precedence over it.
663 : : */
664 : :
665 : 255632 : "(" {
666 : : cur_state->paren_depth++;
667 : 255632 : ECHO;
668 : 255632 : }
669 : :
670 : 255632 : ")" {
671 : 255623 : if (cur_state->paren_depth > 0)
672 [ + - ]: 255623 : cur_state->paren_depth--;
673 : 255623 : ECHO;
674 : 255623 : }
675 : :
676 : 255623 : ";" {
677 : 244729 : ECHO;
678 : 244729 : if (cur_state->paren_depth == 0 &&
679 [ + + ]: 244729 : cur_state->begin_depth == 0)
680 [ + + ]: 244693 : {
681 : : /* Remember if this subcommand was COPY FROM STDIN */
682 : : if (psqlscan_is_copy_from_stdin(cur_state))
683 [ + + ]: 244579 : cur_state->copy_stdin_count++;
684 : 882 : /* Terminate lexing temporarily */
685 : : cur_state->start_state = YY_START;
686 : 244579 : cur_state->init_idents_count = 0;
687 : 244579 : return LEXRES_SEMI;
688 : 244579 : }
689 : : }
690 : :
691 : 150 : /*
692 : : * psql-specific rules to handle backslash commands and variable
693 : : * substitution. We want these before {self}, also.
694 : : */
695 : :
696 : 512 : "\\"[;:] {
697 : : /* Force a semi-colon or colon into the query buffer */
698 : : psqlscan_emit(cur_state, yytext + 1, 1);
699 : 512 : /* Reset BEGIN/END/COPY tracking if semi at outer level */
700 : : if (yytext[1] == ';' &&
701 [ + - ]: 512 : cur_state->paren_depth == 0 &&
702 [ + - ]: 512 : cur_state->begin_depth == 0)
703 [ + - ]: 512 : {
704 : : /* Remember if this subcommand was COPY FROM STDIN */
705 : : if (psqlscan_is_copy_from_stdin(cur_state))
706 [ + + ]: 512 : cur_state->copy_stdin_count++;
707 : 12 : cur_state->init_idents_count = 0;
708 : 512 : }
709 : : }
710 : :
711 : 512 : "\\" {
712 : 32932 : /* Terminate lexing temporarily */
713 : : cur_state->start_state = YY_START;
714 : 32932 : return LEXRES_BACKSLASH;
715 : 32932 : }
716 : :
717 : : :{variable_char}+ {
718 : 1908 : /* Possible psql variable substitution */
719 : : char *varname;
720 : : char *value;
721 : :
722 : : varname = psqlscan_extract_substring(cur_state,
723 : 1908 : yytext + 1,
724 : 1908 : yyleng - 1);
725 : 1908 : if (cur_state->callbacks->get_variable)
726 [ + + ]: 1908 : value = cur_state->callbacks->get_variable(varname,
727 : 1312 : PQUOTE_PLAIN,
728 : : cur_state->cb_passthrough);
729 : : else
730 : : value = NULL;
731 : 596 :
732 : : if (value)
733 [ + + ]: 1908 : {
734 : : /* It is a variable, check for recursion */
735 : : if (psqlscan_var_is_current_source(cur_state, varname))
736 [ - + ]: 1004 : {
737 : : /* Recursive expansion --- don't go there */
738 : : pg_log_warning("skipping recursive expansion of variable \"%s\"",
739 : 0 : varname);
740 : : /* Instead copy the string as is */
741 : : ECHO;
742 : 0 : }
743 : : else
744 : : {
745 : : /* OK, perform substitution */
746 : : psqlscan_push_new_buffer(cur_state, value, varname);
747 : 1004 : /* yy_scan_string already made buffer active */
748 : : }
749 : : free(value);
750 : 1004 : }
751 : : else
752 : : {
753 : : /*
754 : : * if the variable doesn't exist we'll copy the string
755 : : * as is
756 : : */
757 : : ECHO;
758 : 904 : }
759 : :
760 : : free(varname);
761 : 1908 : }
762 : :
763 : 1908 : :'{variable_char}+' {
764 : 680 : psqlscan_escape_variable(cur_state, yytext, yyleng,
765 : 680 : PQUOTE_SQL_LITERAL);
766 : : }
767 : :
768 : 680 : :\"{variable_char}+\" {
769 : 21 : psqlscan_escape_variable(cur_state, yytext, yyleng,
770 : 21 : PQUOTE_SQL_IDENT);
771 : : }
772 : :
773 : 21 : :\{\?{variable_char}+\} {
774 : 8 : psqlscan_test_variable(cur_state, yytext, yyleng);
775 : 8 : }
776 : :
777 : 8 : /*
778 : : * These rules just avoid the need for scanner backup if one of the
779 : : * three rules above fails to match completely.
780 : : */
781 : :
782 : 0 : :'{variable_char}* {
783 : : /* Throw back everything but the colon */
784 : : yyless(1);
785 : 0 : ECHO;
786 : 0 : }
787 : :
788 : 0 : :\"{variable_char}* {
789 : 0 : /* Throw back everything but the colon */
790 : : yyless(1);
791 : 0 : ECHO;
792 : 0 : }
793 : :
794 : 0 : :\{\?{variable_char}* {
795 : 0 : /* Throw back everything but the colon */
796 : : yyless(1);
797 : 0 : ECHO;
798 : 0 : }
799 : : :\{ {
800 : 0 : /* Throw back everything but the colon */
801 : 0 : yyless(1);
802 : 0 : ECHO;
803 : 0 : }
804 : :
805 : 0 : /*
806 : : * Back to backend-compatible rules.
807 : : */
808 : :
809 : 450811 : {self} {
810 : : ECHO;
811 : 450811 : }
812 : :
813 : 450811 : {operator} {
814 : 13413 : /*
815 : : * Check for embedded slash-star or dash-dash; those
816 : : * are comment starts, so operator must stop there.
817 : : * Note that slash-star or dash-dash at the first
818 : : * character will match a prior rule, not this one.
819 : : */
820 : : int nchars = yyleng;
821 : 13413 : char *slashstar = strstr(yytext, "/*");
822 : 13413 : char *dashdash = strstr(yytext, "--");
823 : 13413 :
824 : : if (slashstar && dashdash)
825 [ + + - + ]: 13413 : {
826 : : /* if both appear, take the first one */
827 : : if (slashstar > dashdash)
828 [ # # ]: 0 : slashstar = dashdash;
829 : 0 : }
830 : : else if (!slashstar)
831 [ + + ]: 13413 : slashstar = dashdash;
832 : 13373 : if (slashstar)
833 [ + + ]: 13413 : nchars = slashstar - yytext;
834 : 48 :
835 : : /*
836 : : * For SQL compatibility, '+' and '-' cannot be the
837 : : * last char of a multi-char operator unless the operator
838 : : * contains chars that are not in SQL operators.
839 : : * The idea is to lex '=-' as two operators, but not
840 : : * to forbid operator names like '?-' that could not be
841 : : * sequences of SQL operators.
842 : : */
843 : : if (nchars > 1 &&
844 [ + + ]: 13413 : (yytext[nchars - 1] == '+' ||
845 [ + + ]: 12310 : yytext[nchars - 1] == '-'))
846 [ + + ]: 12306 : {
847 : : int ic;
848 : :
849 : : for (ic = nchars - 2; ic >= 0; ic--)
850 [ + + ]: 369 : {
851 : : char c = yytext[ic];
852 : 318 : if (c == '~' || c == '!' || c == '@' ||
853 [ + - + + : 318 : c == '#' || c == '^' || c == '&' ||
+ - + + ]
854 [ + - + - : 262 : c == '|' || c == '`' || c == '?' ||
+ + ]
855 [ + - + + : 98 : c == '%')
+ - ]
856 : : break;
857 : : }
858 : : if (ic < 0)
859 [ + + ]: 283 : {
860 : : /*
861 : : * didn't find a qualifying character, so remove
862 : : * all trailing [+-]
863 : : */
864 : : do {
865 : : nchars--;
866 : 51 : } while (nchars > 1 &&
867 [ + + ]: 51 : (yytext[nchars - 1] == '+' ||
868 [ - + ]: 23 : yytext[nchars - 1] == '-'));
869 [ - + ]: 23 : }
870 : : }
871 : :
872 : : if (nchars < yyleng)
873 [ + + ]: 13413 : {
874 : : /* Strip the unwanted chars from the token */
875 : : yyless(nchars);
876 : 99 : }
877 : : ECHO;
878 : 13413 : }
879 : :
880 : 13413 : {param} {
881 : 1376 : ECHO;
882 : 1376 : }
883 : : {param_junk} {
884 : 1376 : ECHO;
885 : 8 : }
886 : :
887 : 8 : {decinteger} {
888 : 141447 : ECHO;
889 : 141447 : }
890 : : {hexinteger} {
891 : 141447 : ECHO;
892 : 83 : }
893 : : {octinteger} {
894 : 83 : ECHO;
895 : 40 : }
896 : : {bininteger} {
897 : 40 : ECHO;
898 : 40 : }
899 : : {hexfail} {
900 : 40 : ECHO;
901 : 4 : }
902 : : {octfail} {
903 : 4 : ECHO;
904 : 4 : }
905 : : {binfail} {
906 : 4 : ECHO;
907 : 4 : }
908 : : {numeric} {
909 : 4 : ECHO;
910 : 5471 : }
911 : : {numericfail} {
912 : 5471 : /* throw back the .., and treat as integer */
913 : 0 : yyless(yyleng - 2);
914 : 0 : ECHO;
915 : 0 : }
916 : : {real} {
917 : 0 : ECHO;
918 : 506 : }
919 : : {realfail} {
920 : 506 : ECHO;
921 : 4 : }
922 : : {integer_junk} {
923 : 4 : ECHO;
924 : 44 : }
925 : : {numeric_junk} {
926 : 44 : ECHO;
927 : 32 : }
928 : : {real_junk} {
929 : 32 : ECHO;
930 : 0 : }
931 : :
932 : 0 :
933 : 1858181 : {identifier} {
934 : : psqlscan_track_identifier(cur_state, yytext);
935 : 1858181 : ECHO;
936 : 1858181 : }
937 : :
938 : 1858181 : {other} {
939 : 0 : ECHO;
940 : 0 : }
941 : :
942 : 0 : <<EOF>> {
943 : 521880 : if (cur_state->buffer_stack == NULL)
944 [ + + ]: 521880 : {
945 : : cur_state->start_state = YY_START;
946 : 520876 : return LEXRES_EOL; /* end of input reached */
947 : 520876 : }
948 : :
949 : : /*
950 : : * We were expanding a variable, so pop the inclusion
951 : : * stack and keep lexing
952 : : */
953 : : psqlscan_pop_buffer_stack(cur_state);
954 : 1004 : psqlscan_select_top_buffer(cur_state);
955 : 1004 : }
956 : :
957 : 1004 : %%
958 : 0 :
959 : : /* LCOV_EXCL_STOP */
960 : :
961 : : /*
962 : : * Record the first few keywords/identifiers of a statement
963 : : * in the idents[] array, of length idents_size.
964 : : * *idents_count is the number of entries filled so far.
965 : : *
966 : : * We record the interesting keywords using their first character, which
967 : : * works so long as those are all different. We could switch to an enum
968 : : * if that stops being true, but for now this is easy and compact.
969 : : */
970 : : static void
971 : : psqlscan_record_initial_keyword(const char *identifier,
972 : 1397516 : char *idents,
973 : : int idents_size,
974 : : int *idents_count)
975 : : {
976 : : if (*idents_count < idents_size)
977 [ + + ]: 1397516 : {
978 : : /*
979 : : * What we need to recognize is CREATE [OR REPLACE] FUNCTION/PROCEDURE.
980 : : * We record these keywords in lower case. We also need to recognize
981 : : * COPY ... FROM STDIN. (Note: the backend grammar doesn't
982 : : * distinguish STDIN from STDOUT, so we should not do so here either.)
983 : : * We record these keywords in upper case, to avoid conflicting with
984 : : * the first set.
985 : : */
986 : : if (pg_strcasecmp(identifier, "create") == 0 ||
987 [ + + + + ]: 2263926 : pg_strcasecmp(identifier, "function") == 0 ||
988 [ + + ]: 2214200 : pg_strcasecmp(identifier, "procedure") == 0 ||
989 [ + + ]: 2206800 : pg_strcasecmp(identifier, "or") == 0 ||
990 [ + + ]: 2204085 : pg_strcasecmp(identifier, "replace") == 0)
991 : 1100882 : idents[*idents_count] = pg_tolower((unsigned char) identifier[0]);
992 : 53932 : else if (pg_strcasecmp(identifier, "copy") == 0 ||
993 [ + + + + ]: 2196880 : pg_strcasecmp(identifier, "from") == 0 ||
994 [ + + ]: 2131561 : pg_strcasecmp(identifier, "stdin") == 0 ||
995 [ + + ]: 2067252 : pg_strcasecmp(identifier, "stdout") == 0)
996 : 1033180 : idents[*idents_count] = pg_toupper((unsigned char) identifier[0]);
997 : 66951 : /* For other keywords or identifiers, leave '\0' in the array entry */
998 : : (*idents_count)++;
999 : 1153323 : }
1000 : : }
1001 : 1397516 :
1002 : : /*
1003 : : * Does the current input match CREATE [OR REPLACE] {FUNCTION|PROCEDURE}?
1004 : : */
1005 : : static bool
1006 : : psqlscan_is_create_routine(const char *idents)
1007 : 1397516 : {
1008 : : return idents[0] == 'c' &&
1009 [ + + ]: 1688778 : (idents[1] == 'f' || idents[1] == 'p' ||
1010 [ + + + + ]: 291262 : (idents[1] == 'o' && idents[2] == 'r' &&
1011 [ + + + + ]: 260266 : (idents[3] == 'f' || idents[3] == 'p')));
1012 [ + + + + ]: 12406 : }
1013 : :
1014 : : /*
1015 : : * Does the current input match COPY ... FROM STDIN?
1016 : : */
1017 : : static bool
1018 : : psqlscan_is_copy_from_stdin(PsqlScanState state)
1019 : 252904 : {
1020 : : const char *idents = state->init_idents;
1021 : 252904 :
1022 : : /*
1023 : : * The first word must be COPY, but after that there could be up to four
1024 : : * identifiers (BINARY database.schema.table) before FROM. Since some of
1025 : : * the words we track are not reserved words, don't assume the intervening
1026 : : * array entries are '\0'. Life is simplified here by the fact that
1027 : : * psqlscan_track_identifier ignores everything within parens: we won't
1028 : : * see column lists nor the query in COPY (query).
1029 : : */
1030 : : if (idents[0] != 'C')
1031 [ + + ]: 252904 : return false;
1032 : 251013 : for (int i = 1; i < lengthof(state->init_idents) - 1; i++)
1033 [ + + ]: 7721 : {
1034 : : /* Scan to find FROM; if not seen within range, it's not valid COPY */
1035 : : if (idents[i] != 'F')
1036 [ + + ]: 6934 : continue;
1037 : 5830 : /* It's COPY FROM STDIN only if the next word is STDIN */
1038 : : return (idents[i + 1] == 'S');
1039 : 1104 : }
1040 : : return false;
1041 : 787 : }
1042 : :
1043 : : /*
1044 : : * This function is called each time the lexer recognizes an unquoted
1045 : : * identifier (which could also be a keyword, and indeed keywords are the
1046 : : * only case we really care about here). It presently has two tasks:
1047 : : *
1048 : : * 1. Track whether we are inside BEGIN .. END in a function definition,
1049 : : * so that semicolons contained therein don't terminate the whole statement.
1050 : : * Short of writing a full parser here, the following heuristic should work.
1051 : : *
1052 : : * We track whether the beginning of the statement matches CREATE [OR REPLACE]
1053 : : * {FUNCTION|PROCEDURE}. If so, count BEGIN and END pairs. We also have to
1054 : : * account for CASE ... END.
1055 : : *
1056 : : * 2. Record enough information for psqlscan_is_copy_from_stdin() to recognize
1057 : : * COPY FROM STDIN commands.
1058 : : */
1059 : : static void
1060 : : psqlscan_track_identifier(PsqlScanState state, const char *identifier)
1061 : 1858181 : {
1062 : : /* None of this needs to happen when we're inside parentheses */
1063 : : if (state->paren_depth != 0)
1064 [ + + ]: 1858181 : return;
1065 : 460665 :
1066 : : /* Reset all my state at the start of each new statement */
1067 : : if (state->init_idents_count == 0)
1068 [ + + ]: 1397516 : memset(state->init_idents, 0, sizeof(state->init_idents));
1069 : 253734 :
1070 : : /* Record initial keywords if init_idents_count is small enough */
1071 : : psqlscan_record_initial_keyword(identifier,
1072 : 1397516 : state->init_idents,
1073 : 1397516 : lengthof(state->init_idents),
1074 : : &state->init_idents_count);
1075 : :
1076 : : /*
1077 : : * Track BEGIN/CASE/END only when within an appropriate statement.
1078 : : */
1079 : : if (psqlscan_is_create_routine(state->init_idents))
1080 [ + + ]: 1397516 : {
1081 : : if (pg_strcasecmp(identifier, "begin") == 0)
1082 [ + + ]: 38867 : state->begin_depth++;
1083 : 98 : else if (pg_strcasecmp(identifier, "case") == 0)
1084 [ + + ]: 38769 : {
1085 : : /*
1086 : : * CASE also ends with END. We only need to track this if we are
1087 : : * already inside a BEGIN.
1088 : : */
1089 : : if (state->begin_depth >= 1)
1090 [ + - ]: 4 : state->begin_depth++;
1091 : 4 : }
1092 : : else if (pg_strcasecmp(identifier, "end") == 0)
1093 [ + + ]: 38765 : {
1094 : : if (state->begin_depth > 0)
1095 [ + - ]: 106 : state->begin_depth--;
1096 : 106 : }
1097 : : }
1098 : : }
1099 : :
1100 : : /*
1101 : : * Create a lexer working state struct.
1102 : : *
1103 : : * callbacks is a struct of function pointers that encapsulate some
1104 : : * behavior we need from the surrounding program. This struct must
1105 : : * remain valid for the lifespan of the PsqlScanState.
1106 : : */
1107 : : PsqlScanState
1108 : : psql_scan_create(const PsqlScanCallbacks *callbacks)
1109 : 13410 : {
1110 : : PsqlScanState state;
1111 : :
1112 : : state = pg_malloc0_object(PsqlScanStateData);
1113 : 13410 :
1114 : : state->callbacks = callbacks;
1115 : 13410 :
1116 : : yylex_init(&state->scanner);
1117 : 13410 :
1118 : : yyset_extra(state, state->scanner);
1119 : 13410 :
1120 : : psql_scan_reset(state);
1121 : 13410 :
1122 : : return state;
1123 : 13410 : }
1124 : :
1125 : : /*
1126 : : * Destroy a lexer working state struct, releasing all resources.
1127 : : */
1128 : : void
1129 : : psql_scan_destroy(PsqlScanState state)
1130 : 13354 : {
1131 : : psql_scan_finish(state);
1132 : 13354 :
1133 : : psql_scan_reset(state);
1134 : 13354 :
1135 : : yylex_destroy(state->scanner);
1136 : 13354 :
1137 : : free(state);
1138 : 13354 : }
1139 : 13354 :
1140 : : /*
1141 : : * Set the callback passthrough pointer for the lexer.
1142 : : *
1143 : : * This could have been integrated into psql_scan_create, but keeping it
1144 : : * separate allows the application to change the pointer later, which might
1145 : : * be useful.
1146 : : */
1147 : : void
1148 : : psql_scan_set_passthrough(PsqlScanState state, void *passthrough)
1149 : 10629 : {
1150 : : state->cb_passthrough = passthrough;
1151 : 10629 : }
1152 : 10629 :
1153 : : /*
1154 : : * Set up to perform lexing of the given input line.
1155 : : *
1156 : : * The text at *line, extending for line_len bytes, will be scanned by
1157 : : * subsequent calls to the psql_scan routines. psql_scan_finish should
1158 : : * be called when scanning is complete. Note that the lexer retains
1159 : : * a pointer to the storage at *line --- this string must not be altered
1160 : : * or freed until after psql_scan_finish is called.
1161 : : *
1162 : : * encoding is the libpq identifier for the character encoding in use,
1163 : : * and std_strings says whether standard_conforming_strings is on.
1164 : : */
1165 : : void
1166 : : psql_scan_setup(PsqlScanState state,
1167 : 521257 : const char *line, int line_len,
1168 : : int encoding, bool std_strings)
1169 : : {
1170 : : /* Mustn't be scanning already */
1171 : : Assert(state->scanbufhandle == NULL);
1172 : : Assert(state->buffer_stack == NULL);
1173 : :
1174 : : /* Do we need to hack the character set encoding? */
1175 : : state->encoding = encoding;
1176 : 521257 : state->safe_encoding = pg_valid_server_encoding_id(encoding);
1177 : 521257 :
1178 : : /* Save standard-strings flag as well */
1179 : : state->std_strings = std_strings;
1180 : 521257 :
1181 : : /* Set up flex input buffer with appropriate translation and padding */
1182 : : state->scanbufhandle = psqlscan_prepare_buffer(state, line, line_len,
1183 : 521257 : &state->scanbuf);
1184 : : state->scanline = line;
1185 : 521257 :
1186 : : /* Set lookaside data in case we have to map unsafe encoding */
1187 : : state->curline = state->scanbuf;
1188 : 521257 : state->refline = state->scanline;
1189 : 521257 :
1190 : : /* Initialize state for psql_scan_get_location() */
1191 : : state->cur_line_no = 0; /* yylex not called yet */
1192 : 521257 : state->cur_line_ptr = state->scanbuf;
1193 : 521257 : }
1194 : 521257 :
1195 : : /*
1196 : : * Do lexical analysis of SQL command text.
1197 : : *
1198 : : * The text previously passed to psql_scan_setup is scanned, and appended
1199 : : * (possibly with transformation) to query_buf.
1200 : : *
1201 : : * The return value indicates the condition that stopped scanning:
1202 : : *
1203 : : * PSCAN_SEMICOLON: found a command-ending semicolon. (The semicolon is
1204 : : * transferred to query_buf.) The command accumulated in query_buf should
1205 : : * be executed, then clear query_buf and call again to scan the remainder
1206 : : * of the line.
1207 : : *
1208 : : * PSCAN_BACKSLASH: found a backslash that starts a special command.
1209 : : * Any previous data on the line has been transferred to query_buf.
1210 : : * The caller will typically next apply a separate flex lexer to scan
1211 : : * the special command.
1212 : : *
1213 : : * PSCAN_INCOMPLETE: the end of the line was reached, but we have an
1214 : : * incomplete SQL command. *prompt is set to the appropriate prompt type.
1215 : : *
1216 : : * PSCAN_EOL: the end of the line was reached, and there is no lexical
1217 : : * reason to consider the command incomplete. The caller may or may not
1218 : : * choose to send it. *prompt is set to the appropriate prompt type if
1219 : : * the caller chooses to collect more input.
1220 : : *
1221 : : * In the PSCAN_INCOMPLETE and PSCAN_EOL cases, psql_scan_finish() should
1222 : : * be called next, then the cycle may be repeated with a fresh input line.
1223 : : *
1224 : : * In all cases, *prompt is set to an appropriate prompt type code for the
1225 : : * next line-input operation.
1226 : : */
1227 : : PsqlScanResult
1228 : : psql_scan(PsqlScanState state,
1229 : 798387 : PQExpBuffer query_buf,
1230 : : promptStatus_t *prompt)
1231 : : {
1232 : : PsqlScanResult result;
1233 : : int lexresult;
1234 : :
1235 : : /* Must be scanning already */
1236 : : Assert(state->scanbufhandle != NULL);
1237 : :
1238 : : /* Set current output target */
1239 : : state->output_buf = query_buf;
1240 : 798387 :
1241 : : /* Set input source */
1242 : : if (state->buffer_stack != NULL)
1243 [ + + ]: 798387 : yy_switch_to_buffer(state->buffer_stack->buf, state->scanner);
1244 : 60 : else
1245 : : yy_switch_to_buffer(state->scanbufhandle, state->scanner);
1246 : 798327 :
1247 : : /* And lex. */
1248 : : lexresult = yylex(NULL, state->scanner);
1249 : 798387 :
1250 : : /* Notify psql_scan_get_location() that a yylex call has been made. */
1251 : : if (state->cur_line_no == 0)
1252 [ + + ]: 798387 : state->cur_line_no = 1;
1253 : 521255 :
1254 : : /*
1255 : : * Check termination state and return appropriate result info.
1256 : : */
1257 : : switch (lexresult)
1258 [ + + + - ]: 798387 : {
1259 : : case LEXRES_EOL: /* end of input */
1260 : 520876 : switch (state->start_state)
1261 [ + - + + : 520876 : {
- + + + -
- - ]
1262 : : case INITIAL:
1263 : 488737 : case xqs: /* we treat this like INITIAL */
1264 : : if (state->paren_depth > 0)
1265 [ + + ]: 488737 : {
1266 : : result = PSCAN_INCOMPLETE;
1267 : 42583 : *prompt = PROMPT_PAREN;
1268 : 42583 : }
1269 : : else if (state->begin_depth > 0)
1270 [ + + ]: 446154 : {
1271 : : result = PSCAN_INCOMPLETE;
1272 : 609 : *prompt = PROMPT_CONTINUE;
1273 : 609 : }
1274 : : else if (query_buf->len > 0)
1275 [ + + ]: 445545 : {
1276 : : result = PSCAN_EOL;
1277 : 95607 : *prompt = PROMPT_CONTINUE;
1278 : 95607 : }
1279 : : else
1280 : : {
1281 : : /* never bother to send an empty buffer */
1282 : : result = PSCAN_INCOMPLETE;
1283 : 349938 : *prompt = PROMPT_READY;
1284 : 349938 : }
1285 : : break;
1286 : 488737 : case xb:
1287 : 0 : result = PSCAN_INCOMPLETE;
1288 : 0 : *prompt = PROMPT_SINGLEQUOTE;
1289 : 0 : break;
1290 : 0 : case xc:
1291 : 525 : result = PSCAN_INCOMPLETE;
1292 : 525 : *prompt = PROMPT_COMMENT;
1293 : 525 : break;
1294 : 525 : case xd:
1295 : 23 : result = PSCAN_INCOMPLETE;
1296 : 23 : *prompt = PROMPT_DOUBLEQUOTE;
1297 : 23 : break;
1298 : 23 : case xh:
1299 : 0 : result = PSCAN_INCOMPLETE;
1300 : 0 : *prompt = PROMPT_SINGLEQUOTE;
1301 : 0 : break;
1302 : 0 : case xe:
1303 : 301 : result = PSCAN_INCOMPLETE;
1304 : 301 : *prompt = PROMPT_SINGLEQUOTE;
1305 : 301 : break;
1306 : 301 : case xq:
1307 : 7087 : result = PSCAN_INCOMPLETE;
1308 : 7087 : *prompt = PROMPT_SINGLEQUOTE;
1309 : 7087 : break;
1310 : 7087 : case xdolq:
1311 : 24203 : result = PSCAN_INCOMPLETE;
1312 : 24203 : *prompt = PROMPT_DOLLARQUOTE;
1313 : 24203 : break;
1314 : 24203 : case xui:
1315 : 0 : result = PSCAN_INCOMPLETE;
1316 : 0 : *prompt = PROMPT_DOUBLEQUOTE;
1317 : 0 : break;
1318 : 0 : case xus:
1319 : 0 : result = PSCAN_INCOMPLETE;
1320 : 0 : *prompt = PROMPT_SINGLEQUOTE;
1321 : 0 : break;
1322 : 0 : default:
1323 : 0 : /* can't get here */
1324 : : fprintf(stderr, "invalid YY_START\n");
1325 : 0 : exit(1);
1326 : 0 : }
1327 : : break;
1328 : 520876 : case LEXRES_SEMI: /* semicolon */
1329 : 244579 : result = PSCAN_SEMICOLON;
1330 : 244579 : *prompt = PROMPT_READY;
1331 : 244579 : break;
1332 : 244579 : case LEXRES_BACKSLASH: /* backslash */
1333 : 32932 : result = PSCAN_BACKSLASH;
1334 : 32932 : *prompt = PROMPT_READY;
1335 : 32932 : break;
1336 : 32932 : default:
1337 : 0 : /* can't get here */
1338 : : fprintf(stderr, "invalid yylex result\n");
1339 : 0 : exit(1);
1340 : 0 : }
1341 : :
1342 : : return result;
1343 : 798387 : }
1344 : :
1345 : : /*
1346 : : * Clean up after scanning a string. This flushes any unread input and
1347 : : * releases resources (but not the PsqlScanState itself). Note however
1348 : : * that this does not reset the lexer scan state; that can be done by
1349 : : * psql_scan_reset(), which is an orthogonal operation.
1350 : : *
1351 : : * It is legal to call this when not scanning anything (makes it easier
1352 : : * to deal with error recovery).
1353 : : */
1354 : : void
1355 : : psql_scan_finish(PsqlScanState state)
1356 : 532059 : {
1357 : : /* Drop any incomplete variable expansions. */
1358 : : while (state->buffer_stack != NULL)
1359 [ - + ]: 532059 : psqlscan_pop_buffer_stack(state);
1360 : 0 :
1361 : : /* Done with the outer scan buffer, too */
1362 : : if (state->scanbufhandle)
1363 [ + + ]: 532059 : yy_delete_buffer(state->scanbufhandle, state->scanner);
1364 : 521202 : state->scanbufhandle = NULL;
1365 : 532059 : if (state->scanbuf)
1366 [ + + ]: 532059 : free(state->scanbuf);
1367 : 521202 : state->scanbuf = NULL;
1368 : 532059 : }
1369 : 532059 :
1370 : : /*
1371 : : * Reset lexer scanning state to start conditions. This is appropriate
1372 : : * for executing \r psql commands (or any other time that we discard the
1373 : : * prior contents of query_buf). Do not call this between psql_scan()
1374 : : * calls that are scanning successive chunks of a single query string;
1375 : : * do call it when preparing to process a new query string.
1376 : : *
1377 : : * Note that this is unrelated to flushing unread input; that task is
1378 : : * done by psql_scan_finish().
1379 : : */
1380 : : void
1381 : : psql_scan_reset(PsqlScanState state)
1382 : 272498 : {
1383 : : state->start_state = INITIAL;
1384 : 272498 : state->paren_depth = 0;
1385 : 272498 : state->xcdepth = 0; /* not really necessary */
1386 : 272498 : if (state->dolqstart)
1387 [ - + ]: 272498 : free(state->dolqstart);
1388 : 0 : state->dolqstart = NULL;
1389 : 272498 : state->begin_depth = 0;
1390 : 272498 : state->copy_stdin_count = 0;
1391 : 272498 : state->init_idents_count = 0;
1392 : 272498 : }
1393 : 272498 :
1394 : : /*
1395 : : * Reselect this lexer (psqlscan.l) after using another one.
1396 : : *
1397 : : * Currently and for foreseeable uses, it's sufficient to reset to INITIAL
1398 : : * state, because we'd never switch to another lexer in a different state.
1399 : : * However, we don't want to reset e.g. paren_depth, so this can't be
1400 : : * the same as psql_scan_reset().
1401 : : *
1402 : : * Note: psql setjmp error recovery just calls psql_scan_reset(), so that
1403 : : * must be a superset of this.
1404 : : *
1405 : : * Note: it seems likely that other lexers could just assign INITIAL for
1406 : : * themselves, since that probably has the value zero in every flex-generated
1407 : : * lexer. But let's not assume that.
1408 : : */
1409 : : void
1410 : : psql_scan_reselect_sql_lexer(PsqlScanState state)
1411 : 156182 : {
1412 : : state->start_state = INITIAL;
1413 : 156182 : }
1414 : 156182 :
1415 : : /*
1416 : : * Return the number of COPY ... FROM STDIN commands in the input string.
1417 : : *
1418 : : * This should be called only after we've finished parsing a complete
1419 : : * string and are ready to send it to the backend.
1420 : : */
1421 : : int
1422 : : psql_scan_count_copy_from_stdin(PsqlScanState state)
1423 : 251406 : {
1424 : : if (state->init_idents_count > 0)
1425 [ + + ]: 251406 : {
1426 : : /* Count any COPY FROM STDIN following the last semicolon */
1427 : : if (psqlscan_is_copy_from_stdin(state))
1428 [ + + ]: 7813 : state->copy_stdin_count++;
1429 : 1 : /* ... but do so only once */
1430 : : state->init_idents_count = 0;
1431 : 7813 : }
1432 : : return state->copy_stdin_count;
1433 : 251406 : }
1434 : :
1435 : : /*
1436 : : * Return true if lexer is currently in an "inside quotes" state.
1437 : : *
1438 : : * This is pretty grotty but is needed to preserve the old behavior
1439 : : * that mainloop.c drops blank lines not inside quotes without even
1440 : : * echoing them.
1441 : : */
1442 : : bool
1443 : : psql_scan_in_quote(PsqlScanState state)
1444 : 99208 : {
1445 : : return state->start_state != INITIAL &&
1446 [ + + ]: 99815 : state->start_state != xqs;
1447 [ + + ]: 607 : }
1448 : :
1449 : : /*
1450 : : * Return the current scanning location (end+1 of last scanned token),
1451 : : * as a line number counted from 1 and an offset from string start.
1452 : : *
1453 : : * This considers only the outermost input string, and therefore is of
1454 : : * limited use for programs that use psqlscan_push_new_buffer().
1455 : : *
1456 : : * It would be a bit easier probably to use "%option yylineno" to count
1457 : : * lines, but the flex manual says that has a performance cost, and only
1458 : : * a minority of programs using psqlscan have need for this functionality.
1459 : : * So we implement it ourselves without adding overhead to the lexer itself.
1460 : : */
1461 : : void
1462 : : psql_scan_get_location(PsqlScanState state,
1463 : 1745 : int *lineno, int *offset)
1464 : : {
1465 : : const char *line_end;
1466 : :
1467 : : /*
1468 : : * We rely on flex's having stored a NUL after the current token in
1469 : : * scanbuf. Therefore we must specially handle the state before yylex()
1470 : : * has been called, when obviously that won't have happened yet.
1471 : : */
1472 : : if (state->cur_line_no == 0)
1473 [ - + ]: 1745 : {
1474 : : *lineno = 1;
1475 : 0 : *offset = 0;
1476 : 0 : return;
1477 : 0 : }
1478 : :
1479 : : /*
1480 : : * Advance cur_line_no/cur_line_ptr past whatever has been lexed so far.
1481 : : * Doing this prevents repeated calls from being O(N^2) for long inputs.
1482 : : */
1483 : : while ((line_end = strchr(state->cur_line_ptr, '\n')) != NULL)
1484 [ + + ]: 2221 : {
1485 : : state->cur_line_no++;
1486 : 476 : state->cur_line_ptr = line_end + 1;
1487 : 476 : }
1488 : : state->cur_line_ptr += strlen(state->cur_line_ptr);
1489 : 1745 :
1490 : : /* Report current location. */
1491 : : *lineno = state->cur_line_no;
1492 : 1745 : *offset = state->cur_line_ptr - state->scanbuf;
1493 : 1745 : }
1494 : :
1495 : : /*
1496 : : * Push the given string onto the stack of stuff to scan.
1497 : : *
1498 : : * NOTE SIDE EFFECT: the new buffer is made the active flex input buffer.
1499 : : */
1500 : : void
1501 : : psqlscan_push_new_buffer(PsqlScanState state, const char *newstr,
1502 : 1004 : const char *varname)
1503 : : {
1504 : : StackElem *stackelem;
1505 : :
1506 : : stackelem = pg_malloc_object(StackElem);
1507 : 1004 :
1508 : : /*
1509 : : * In current usage, the passed varname points at the current flex input
1510 : : * buffer; we must copy it before calling psqlscan_prepare_buffer()
1511 : : * because that will change the buffer state.
1512 : : */
1513 : : stackelem->varname = varname ? pg_strdup(varname) : NULL;
1514 [ + - ]: 1004 :
1515 : : stackelem->buf = psqlscan_prepare_buffer(state, newstr, strlen(newstr),
1516 : 1004 : &stackelem->bufstring);
1517 : : state->curline = stackelem->bufstring;
1518 : 1004 : if (state->safe_encoding)
1519 [ + - ]: 1004 : {
1520 : : stackelem->origstring = NULL;
1521 : 1004 : state->refline = stackelem->bufstring;
1522 : 1004 : }
1523 : : else
1524 : : {
1525 : : stackelem->origstring = pg_strdup(newstr);
1526 : 0 : state->refline = stackelem->origstring;
1527 : 0 : }
1528 : : stackelem->next = state->buffer_stack;
1529 : 1004 : state->buffer_stack = stackelem;
1530 : 1004 : }
1531 : 1004 :
1532 : : /*
1533 : : * Pop the topmost buffer stack item (there must be one!)
1534 : : *
1535 : : * NB: after this, the flex input state is unspecified; caller must
1536 : : * switch to an appropriate buffer to continue lexing.
1537 : : * See psqlscan_select_top_buffer().
1538 : : */
1539 : : void
1540 : : psqlscan_pop_buffer_stack(PsqlScanState state)
1541 : 1004 : {
1542 : : StackElem *stackelem = state->buffer_stack;
1543 : 1004 :
1544 : : state->buffer_stack = stackelem->next;
1545 : 1004 : yy_delete_buffer(stackelem->buf, state->scanner);
1546 : 1004 : free(stackelem->bufstring);
1547 : 1004 : if (stackelem->origstring)
1548 [ - + ]: 1004 : free(stackelem->origstring);
1549 : 0 : if (stackelem->varname)
1550 [ + - ]: 1004 : free(stackelem->varname);
1551 : 1004 : free(stackelem);
1552 : 1004 : }
1553 : 1004 :
1554 : : /*
1555 : : * Select the topmost surviving buffer as the active input.
1556 : : */
1557 : : void
1558 : : psqlscan_select_top_buffer(PsqlScanState state)
1559 : 1004 : {
1560 : : StackElem *stackelem = state->buffer_stack;
1561 : 1004 :
1562 : : if (stackelem != NULL)
1563 [ - + ]: 1004 : {
1564 : : yy_switch_to_buffer(stackelem->buf, state->scanner);
1565 : 0 : state->curline = stackelem->bufstring;
1566 : 0 : state->refline = stackelem->origstring ? stackelem->origstring : stackelem->bufstring;
1567 [ # # ]: 0 : }
1568 : : else
1569 : : {
1570 : : yy_switch_to_buffer(state->scanbufhandle, state->scanner);
1571 : 1004 : state->curline = state->scanbuf;
1572 : 1004 : state->refline = state->scanline;
1573 : 1004 : }
1574 : : }
1575 : 1004 :
1576 : : /*
1577 : : * Check if specified variable name is the source for any string
1578 : : * currently being scanned
1579 : : */
1580 : : bool
1581 : : psqlscan_var_is_current_source(PsqlScanState state, const char *varname)
1582 : 1004 : {
1583 : : StackElem *stackelem;
1584 : :
1585 : : for (stackelem = state->buffer_stack;
1586 : 1004 : stackelem != NULL;
1587 [ - + ]: 1004 : stackelem = stackelem->next)
1588 : 0 : {
1589 : : if (stackelem->varname && strcmp(stackelem->varname, varname) == 0)
1590 [ # # # # ]: 0 : return true;
1591 : 0 : }
1592 : : return false;
1593 : 1004 : }
1594 : :
1595 : : /*
1596 : : * Set up a flex input buffer to scan the given data. We always make a
1597 : : * copy of the data. If working in an unsafe encoding, the copy has
1598 : : * multibyte sequences replaced by FFs to avoid fooling the lexer rules.
1599 : : *
1600 : : * NOTE SIDE EFFECT: the new buffer is made the active flex input buffer.
1601 : : */
1602 : : YY_BUFFER_STATE
1603 : : psqlscan_prepare_buffer(PsqlScanState state, const char *txt, int len,
1604 : 522261 : char **txtcopy)
1605 : : {
1606 : : char *newtxt;
1607 : :
1608 : : /* Flex wants two \0 characters after the actual data */
1609 : : newtxt = pg_malloc_array(char, (len + 2));
1610 : 522261 : *txtcopy = newtxt;
1611 : 522261 : newtxt[len] = newtxt[len + 1] = YY_END_OF_BUFFER_CHAR;
1612 : 522261 :
1613 : : if (state->safe_encoding)
1614 [ + + ]: 522261 : memcpy(newtxt, txt, len);
1615 : 522121 : else
1616 : : {
1617 : : /* Gotta do it the hard way */
1618 : : int i = 0;
1619 : 140 :
1620 : : while (i < len)
1621 [ + + ]: 808 : {
1622 : : int thislen = PQmblen(txt + i, state->encoding);
1623 : 668 :
1624 : : /* first byte should always be okay... */
1625 : : newtxt[i] = txt[i];
1626 : 668 : i++;
1627 : 668 : while (--thislen > 0 && i < len)
1628 [ + + + - ]: 808 : newtxt[i++] = (char) 0xFF;
1629 : 140 : }
1630 : : }
1631 : :
1632 : : return yy_scan_buffer(newtxt, len + 2, state->scanner);
1633 : 522261 : }
1634 : :
1635 : : /*
1636 : : * psqlscan_emit() --- body for ECHO macro
1637 : : *
1638 : : * NB: this must be used for ALL and ONLY the text copied from the flex
1639 : : * input data. If you pass it something that is not part of the yytext
1640 : : * string, you are making a mistake. Internally generated text can be
1641 : : * appended directly to state->output_buf.
1642 : : */
1643 : : void
1644 : : psqlscan_emit(PsqlScanState state, const char *txt, int len)
1645 : 6613668 : {
1646 : : PQExpBuffer output_buf = state->output_buf;
1647 : 6613668 :
1648 : : if (state->safe_encoding)
1649 [ + + ]: 6613668 : appendBinaryPQExpBuffer(output_buf, txt, len);
1650 : 6613192 : else
1651 : : {
1652 : : /* Gotta do it the hard way */
1653 : : const char *reference = state->refline;
1654 : 476 : int i;
1655 : :
1656 : : reference += (txt - state->curline);
1657 : 476 :
1658 : : for (i = 0; i < len; i++)
1659 [ + + ]: 1277 : {
1660 : : char ch = txt[i];
1661 : 801 :
1662 : : if (ch == (char) 0xFF)
1663 [ + + ]: 801 : ch = reference[i];
1664 : 140 : appendPQExpBufferChar(output_buf, ch);
1665 : 801 : }
1666 : : }
1667 : : }
1668 : 6613668 :
1669 : : /*
1670 : : * psqlscan_extract_substring --- fetch value of (part of) the current token
1671 : : *
1672 : : * This is like psqlscan_emit(), except that the data is returned as a
1673 : : * malloc'd string rather than being pushed directly to state->output_buf.
1674 : : */
1675 : : char *
1676 : : psqlscan_extract_substring(PsqlScanState state, const char *txt, int len)
1677 : 3536 : {
1678 : : char *result = pg_malloc_array(char, (len + 1));
1679 : 3536 :
1680 : : if (state->safe_encoding)
1681 [ + - ]: 3536 : memcpy(result, txt, len);
1682 : 3536 : else
1683 : : {
1684 : : /* Gotta do it the hard way */
1685 : : const char *reference = state->refline;
1686 : 0 : int i;
1687 : :
1688 : : reference += (txt - state->curline);
1689 : 0 :
1690 : : for (i = 0; i < len; i++)
1691 [ # # ]: 0 : {
1692 : : char ch = txt[i];
1693 : 0 :
1694 : : if (ch == (char) 0xFF)
1695 [ # # ]: 0 : ch = reference[i];
1696 : 0 : result[i] = ch;
1697 : 0 : }
1698 : : }
1699 : : result[len] = '\0';
1700 : 3536 : return result;
1701 : 3536 : }
1702 : :
1703 : : /*
1704 : : * psqlscan_escape_variable --- process :'VARIABLE' or :"VARIABLE"
1705 : : *
1706 : : * If the variable name is found, escape its value using the appropriate
1707 : : * quoting method and emit the value to output_buf. (Since the result is
1708 : : * surely quoted, there is never any reason to rescan it.) If we don't
1709 : : * find the variable or escaping fails, emit the token as-is.
1710 : : */
1711 : : void
1712 : : psqlscan_escape_variable(PsqlScanState state, const char *txt, int len,
1713 : 745 : PsqlScanQuoteType quote)
1714 : : {
1715 : : char *varname;
1716 : : char *value;
1717 : :
1718 : : /* Variable lookup. */
1719 : : varname = psqlscan_extract_substring(state, txt + 2, len - 3);
1720 : 745 : if (state->callbacks->get_variable)
1721 [ + - ]: 745 : value = state->callbacks->get_variable(varname, quote,
1722 : 745 : state->cb_passthrough);
1723 : : else
1724 : : value = NULL;
1725 : 0 : free(varname);
1726 : 745 :
1727 : : if (value)
1728 [ + + ]: 745 : {
1729 : : /* Emit the suitably-escaped value */
1730 : : appendPQExpBufferStr(state->output_buf, value);
1731 : 708 : free(value);
1732 : 708 : }
1733 : : else
1734 : : {
1735 : : /* Emit original token as-is */
1736 : : psqlscan_emit(state, txt, len);
1737 : 37 : }
1738 : : }
1739 : 745 :
1740 : : void
1741 : : psqlscan_test_variable(PsqlScanState state, const char *txt, int len)
1742 : 21 : {
1743 : : char *varname;
1744 : : char *value;
1745 : :
1746 : : varname = psqlscan_extract_substring(state, txt + 3, len - 4);
1747 : 21 : if (state->callbacks->get_variable)
1748 [ + - ]: 21 : value = state->callbacks->get_variable(varname, PQUOTE_PLAIN,
1749 : 21 : state->cb_passthrough);
1750 : : else
1751 : : value = NULL;
1752 : 0 : free(varname);
1753 : 21 :
1754 : : if (value != NULL)
1755 [ + + ]: 21 : {
1756 : : appendPQExpBufferStr(state->output_buf, "TRUE");
1757 : 9 : free(value);
1758 : 9 : }
1759 : : else
1760 : : {
1761 : : appendPQExpBufferStr(state->output_buf, "FALSE");
1762 : 12 : }
1763 : : }
1764 : 21 : /* END: function "psqlscan_test_variable" */
|