| 2113 | } |
| 2114 | |
| 2115 | int cbm_parse(const cbm_token_t *tokens, int token_count, cbm_parse_result_t *out) { |
| 2116 | memset(out, 0, sizeof(*out)); |
| 2117 | parser_t p = {.tokens = tokens, .count = token_count, .pos = 0}; |
| 2118 | |
| 2119 | /* The branches of a UNION are read one after another by this one parser |
| 2120 | * and linked as they come, so the number of branches is a loop count, not |
| 2121 | * a recursion depth, and one depth counter covers the whole query. */ |
| 2122 | cbm_query_t *q = NULL; |
| 2123 | cbm_query_t *tail = NULL; |
| 2124 | for (;;) { |
| 2125 | cbm_query_t *block = NULL; |
| 2126 | if (parse_query_block(&p, &block) < 0) { |
| 2127 | out->error = heap_strdup(p.error); |
| 2128 | cbm_query_free(q); |
| 2129 | return CBM_NOT_FOUND; |
| 2130 | } |
| 2131 | if (tail) { |
| 2132 | tail->union_next = block; |
| 2133 | } else { |
| 2134 | q = block; |
| 2135 | } |
| 2136 | tail = block; |
| 2137 | /* UNION [ALL]: the ALL flag sits on the branch before the keyword. */ |
| 2138 | if (!check(&p, TOK_UNION)) { |
| 2139 | break; |
| 2140 | } |
| 2141 | advance(&p); |
| 2142 | tail->union_all = match(&p, TOK_ALL); |
| 2143 | } |
| 2144 | |
| 2145 | /* Every token must be consumed. The grammar accepts at most one WITH and |
| 2146 | * treats RETURN as optional, so a query with a second WITH stage — or any |
| 2147 | * typo after RETURN — used to stop parsing there and succeed anyway. The |
| 2148 | * dropped tail took the filter and the RETURN with it, and the engine |
| 2149 | * answered from the fragment it had parsed, using its default projection. |
| 2150 | * That reported success and returned wrong rows, which is worse than a |
| 2151 | * refusal because nothing tells the caller to look. Refuse instead. */ |
| 2152 | if (peek(&p)->type != TOK_EOF) { |
| 2153 | /* Only mention the one-WITH limit when a standalone WITH really is |
| 2154 | * sitting in the part we could not read. Saying it every time points |
| 2155 | * a reader at WITH when the problem is a typo. A WITH straight after |
| 2156 | * STARTS is the STARTS WITH operator rather than a clause, the same |
| 2157 | * guard parse_post_where uses. */ |
| 2158 | const char *hint = ""; |
| 2159 | for (int i = p.pos; i < p.count; i++) { |
| 2160 | if (p.tokens[i].type == TOK_WITH && |
| 2161 | (i == 0 || p.tokens[i - SKIP_ONE].type != TOK_STARTS)) { |
| 2162 | hint = " Note that only one WITH clause is supported."; |
| 2163 | break; |
| 2164 | } |
| 2165 | } |
| 2166 | snprintf(p.error, sizeof(p.error), |
| 2167 | "unexpected input at pos %d ('%s') — the query was not fully " |
| 2168 | "parsed.%s", |
| 2169 | peek(&p)->pos, peek(&p)->text ? peek(&p)->text : "", hint); |
| 2170 | out->error = heap_strdup(p.error); |
| 2171 | cbm_query_free(q); |
| 2172 | return CBM_NOT_FOUND; |
no test coverage detected