Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 33 additions & 37 deletions docs/compatibility/postgresql-18.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions include/sql_parser/compound_query_parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ class CompoundQueryParser {
// The classifier normally consumes SELECT. Pass the consumed keyword for
// TABLE/VALUES/'(', or TK_EOF to start at an unconsumed query operand.
AstNode* parse(TokenType first = TokenType::TK_SELECT) {
ParseDepthGuard<D> depth(tok_);
if (!depth) return nullptr;
const bool require_operands = require_complete_operands_ ||
first == TokenType::TK_VALUES || first == TokenType::TK_TABLE;
AstNode* result = parse_compound_expr(0, first);
Expand Down
28 changes: 28 additions & 0 deletions include/sql_parser/expression_parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,8 @@ class ExpressionParser {

// Parse an expression with minimum precedence 0
AstNode* parse(Precedence min_prec = Precedence::NONE) {
ParseDepthGuard<D> depth(tok_);
if (!depth) return nullptr;
// b_expr restrictions apply to this operator chain; parenthesized
// expressions and function arguments parsed by the atom remain a_expr.
bool restricted = json_xml_restricted_;
Expand Down Expand Up @@ -483,6 +485,30 @@ class ExpressionParser {
Token t = tok_.peek();
if constexpr (D == Dialect::MySQL) {
if (mysql_charset_introducer(t)) return parse_mysql_charset_literal();
if (keyword(t, "DATE") || keyword(t, "TIME") || keyword(t, "TIMESTAMP") ||
keyword(t, "N") || keyword(t, "BINARY")) {
auto look = tok_;
look.skip();
Token next = look.peek();
const bool temporal = keyword(t, "DATE") || keyword(t, "TIME") ||
keyword(t, "TIMESTAMP");
const bool national = keyword(t, "N") && next.type == TokenType::TK_STRING &&
t.source.ptr + t.source.len == next.source.ptr && next.source.ptr[0] == '\'';
const bool binary = keyword(t, "BINARY") &&
((mysql_identifier_word(next) && next.type != TokenType::TK_AS) ||
next.type == TokenType::TK_STRING ||
next.type == TokenType::TK_INTEGER || next.type == TokenType::TK_FLOAT ||
next.type == TokenType::TK_HEX_LITERAL || next.type == TokenType::TK_BIT_LITERAL ||
next.type == TokenType::TK_LPAREN || next.type == TokenType::TK_PLUS ||
next.type == TokenType::TK_MINUS || next.type == TokenType::TK_TILDE ||
next.type == TokenType::TK_EXCLAIM || next.type == TokenType::TK_QUESTION ||
next.type == TokenType::TK_USER_VARIABLE || next.type == TokenType::TK_DOUBLE_AT ||
next.type == TokenType::TK_NULL || next.type == TokenType::TK_TRUE ||
next.type == TokenType::TK_FALSE || next.type == TokenType::TK_CASE ||
next.type == TokenType::TK_INTERVAL || next.type == TokenType::TK_NOT);
if ((temporal && next.type == TokenType::TK_STRING) || national || binary)
return syntax_error();
}
}
if constexpr (D == Dialect::PostgreSQL) {
if ((t.type == TokenType::TK_IDENTIFIER || t.type == TokenType::TK_INTERVAL) &&
Expand Down Expand Up @@ -1467,6 +1493,8 @@ class ExpressionParser {
}
if constexpr (D == Dialect::MySQL) {
if (type == TokenType::TK_COLLATE) return Precedence::POSTFIX;
if (type == TokenType::TK_MYSQL_NULL_SAFE_EQUAL) return Precedence::COMPARISON;
if (type == TokenType::TK_MYSQL_LOGICAL_AND) return Precedence::AND;
}
switch (type) {
case TokenType::TK_OR: return Precedence::OR;
Expand Down
2 changes: 2 additions & 0 deletions include/sql_parser/parse_result.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ struct ParseResult {
StringRef remaining;
bool full_input = false;
bool has_user_variables = false;
bool has_executable_comments = false;
bool has_comments = false; // Recognized comments, including optimizer hints.

StringRef table_name;
StringRef schema_name;
Expand Down
1 change: 1 addition & 0 deletions include/sql_parser/parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ struct ParserConfig {
size_t arena_block_size = 65536; // 64KB
size_t arena_max_size = 1048576; // 1MB
size_t stmt_cache_capacity = 128;
size_t max_parse_depth = 128; // Capped at 128 to bound recursive parser stack use.
};

template <Dialect D>
Expand Down
3 changes: 2 additions & 1 deletion include/sql_parser/pg_integer_literal.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ inline bool pg_integer_literal(Tokenizer<Dialect::PostgreSQL>& tok, Token& resul
look.skip();
Token suffix = look.peek();
char next = suffix.source.len ? suffix.source.ptr[0] : '\0';
bool word_suffix = (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z') || next == '_';
bool word_suffix = (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z') || next == '_' ||
static_cast<unsigned char>(next) >= 0x80;
bool joined = suffix.source.ptr == first.source.ptr + first.source.len && word_suffix;
uint32_t length = first.source.len + (joined ? suffix.source.len : 0);
const char* text = first.source.ptr;
Expand Down
17 changes: 16 additions & 1 deletion include/sql_parser/select_parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class SelectParser {
}
}

// SELECT options: DISTINCT, ALL, SQL_CALC_FOUND_ROWS
// SELECT options precede the select item list.
AstNode* opts = parse_select_options();
if (opts) root->add_child(opts);

Expand Down Expand Up @@ -189,6 +189,18 @@ class SelectParser {
}
}
opts->add_child(make_node(arena_, NodeType::NODE_IDENTIFIER, ExpressionParser<D>::canonical_keyword(t)));
} else if (D == Dialect::MySQL &&
(ExpressionParser<D>::keyword(t, "HIGH_PRIORITY") ||
ExpressionParser<D>::keyword(t, "STRAIGHT_JOIN") ||
ExpressionParser<D>::keyword(t, "SQL_SMALL_RESULT") ||
ExpressionParser<D>::keyword(t, "SQL_BIG_RESULT") ||
ExpressionParser<D>::keyword(t, "SQL_BUFFER_RESULT") ||
ExpressionParser<D>::keyword(t, "SQL_CACHE") ||
ExpressionParser<D>::keyword(t, "SQL_NO_CACHE") ||
ExpressionParser<D>::keyword(t, "DISTINCTROW"))) {
if (!opts) opts = make_node(arena_, NodeType::NODE_SELECT_OPTIONS);
tok_.skip();
opts->add_child(make_node(arena_, NodeType::NODE_IDENTIFIER, t.source));
} else if (t.type == TokenType::TK_SQL_CALC_FOUND_ROWS) {
if (!opts) opts = make_node(arena_, NodeType::NODE_SELECT_OPTIONS);
tok_.skip();
Expand Down Expand Up @@ -244,8 +256,11 @@ class SelectParser {
AstNode* item = make_node(arena_, NodeType::NODE_SELECT_ITEM);
if (!item) return nullptr;

const char* expression_start = tok_.peek().source.ptr;
AstNode* expr = expr_parser_.parse();
if (!expr) return nullptr;
// Original expression spelling; like other source refs, input must outlive the AST.
item->set_source({expression_start, static_cast<uint32_t>(tok_.consumed_token_end() - expression_start)});

// Check for * EXCEPT(...) or * REPLACE(...)
bool is_star = (expr->type == NodeType::NODE_ASTERISK);
Expand Down
2 changes: 2 additions & 0 deletions include/sql_parser/token.h
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ enum class TokenType : uint16_t {
TK_NAMED_ARGUMENT, // =>, reserved for PostgreSQL named function arguments
TK_MYSQL_JSON_ARROW, // -> and ->>; spelling distinguishes unquoting
TK_MYSQL_OPTIMIZER_HINT, // complete comment in a native hint position
TK_MYSQL_NULL_SAFE_EQUAL,
TK_MYSQL_LOGICAL_AND,
};

struct Token {
Expand Down
109 changes: 99 additions & 10 deletions include/sql_parser/tokenizer.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,51 @@ class Tokenizer {
void reset(const char* input, size_t len) {
start_ = input;
cursor_ = input;
consumed_token_end_ = input;
end_ = input + len;
has_peeked_ = false;
has_error_ = false;
has_fatal_error_ = false;
has_user_variables_ = false;
has_executable_comments_ = false;
has_comments_ = false;
hint_allowed_ = false;
after_dot_ = false;
parse_depth_ = 0;
parse_depth_exceeded_ = false;
paren_depth_ = 0;
first_open_paren_ = nullptr;
error_source_ = {};
}

// Shared by expression and query parsers using this tokenizer. Lookahead
// copies retain a snapshot; parsing continues on the original tokenizer.
void set_max_parse_depth(size_t depth) { max_parse_depth_ = depth < 128 ? depth : 128; }
bool enter_parse() {
if (parse_depth_ >= max_parse_depth_) {
parse_depth_exceeded_ = true;
flag_fatal_error_at(peek().source);
return false;
}
++parse_depth_;
return true;
}
void leave_parse() { --parse_depth_; }
bool parse_depth_exceeded() const { return parse_depth_exceeded_; }

// True iff the tokenizer has emitted at least one TK_ERROR token since
// the last reset(). Lets callers distinguish "couldn't build an AST"
// from "the input was syntactically invalid" and surface the latter
// as ParseResult::ERROR rather than PARTIAL.
bool has_error() const { return has_error_; }
bool has_fatal_error() const { return has_fatal_error_; }
bool has_user_variables() const { return has_user_variables_; }
bool has_executable_comments() const { return has_executable_comments_; }
// Sticky since reset, including optimizer hints and executable comments.
bool has_comments() const { return has_comments_; }
// End of the last consumed token, or input_begin() before any consumption.
// Peeking and consuming EOF do not change this boundary.
const char* consumed_token_end() const { return consumed_token_end_; }
StringRef error_source() const { return error_source_; }

// Hook for parser-level (non-tokenizer) errors -- when the parser
Expand All @@ -49,11 +75,16 @@ class Tokenizer {
}

Token next_token() {
Token token;
if (has_peeked_) {
has_peeked_ = false;
return peeked_;
token = peeked_;
} else {
token = scan_token();
}
return scan_token();
if (token.type != TokenType::TK_EOF)
consumed_token_end_ = token.source.ptr + token.source.len;
return token;
}

Token peek() {
Expand All @@ -64,13 +95,7 @@ class Tokenizer {
return peeked_;
}

void skip() {
if (has_peeked_) {
has_peeked_ = false;
} else {
scan_token();
}
}
void skip() { (void)next_token(); }

// Expose start/end of input for remaining-input calculation and for
// safe lookback (e.g. detecting whether an identifier token was source-
Expand All @@ -81,6 +106,7 @@ class Tokenizer {
private:
const char* start_ = nullptr;
const char* cursor_ = nullptr;
const char* consumed_token_end_ = nullptr;
const char* end_ = nullptr;
Token peeked_;
bool has_peeked_ = false;
Expand All @@ -89,6 +115,11 @@ class Tokenizer {
bool has_error_ = false;
bool has_fatal_error_ = false;
bool has_user_variables_ = false;
bool has_executable_comments_ = false;
bool has_comments_ = false;
bool parse_depth_exceeded_ = false;
size_t parse_depth_ = 0;
size_t max_parse_depth_ = 128;
uint32_t paren_depth_ = 0;
const char* first_open_paren_ = nullptr;
StringRef error_source_;
Expand Down Expand Up @@ -126,6 +157,7 @@ class Tokenizer {
(static_cast<unsigned char>(peek_char(2)) <= 0x20 ||
static_cast<unsigned char>(peek_char(2)) == 0x7f)));
if (dash_comment) {
has_comments_ = true;
hint_allowed_ = false;
cursor_ += 2;
while (cursor_ < end_ && *cursor_ != '\n') ++cursor_;
Expand All @@ -135,6 +167,7 @@ class Tokenizer {
// # line comment (MySQL only)
if constexpr (D == Dialect::MySQL) {
if (c == '#') {
has_comments_ = true;
hint_allowed_ = false;
++cursor_;
while (cursor_ < end_ && *cursor_ != '\n') ++cursor_;
Expand All @@ -144,6 +177,7 @@ class Tokenizer {

// /* block comment */
if (c == '/' && peek_char(1) == '*') {
has_comments_ = true;
if constexpr (D == Dialect::MySQL) {
if (hint_allowed_ && peek_char(2) == '+') return;
}
Expand Down Expand Up @@ -173,6 +207,7 @@ class Tokenizer {
const bool executable = cursor_ < end_ &&
(*cursor_ == '!' ||
(cursor_ + 1 < end_ && cursor_[0] == 'M' && cursor_[1] == '!'));
if (executable) has_executable_comments_ = true;
bool has_user_variable_marker = false;
bool closed = false;
while (cursor_ < end_) {
Expand Down Expand Up @@ -236,10 +271,39 @@ class Tokenizer {
static_cast<uint32_t>(source_start - start_)};
}

// Validate one UTF-8 scalar without reading past the input. High bytes
// participate in identifiers; do not split a name into ASCII keyword tokens.
size_t utf8_identifier_char_length(const char* p) const {
const size_t left = static_cast<size_t>(end_ - p);
const auto c = static_cast<unsigned char>(*p);
size_t n = c >= 0xc2 && c <= 0xdf ? 2 :
c >= 0xe0 && c <= 0xef ? 3 :
c >= 0xf0 && c <= 0xf4 ? 4 : 0;
if (n == 0 || left < n) return 0;
for (size_t i = 1; i < n; ++i) {
const auto b = static_cast<unsigned char>(p[i]);
if (b < 0x80 || b > 0xbf) return 0;
}
const auto second = static_cast<unsigned char>(p[1]);
if ((c == 0xe0 && second < 0xa0) || (c == 0xed && second >= 0xa0) ||
(c == 0xf0 && second < 0x90) || (c == 0xf4 && second >= 0x90)) return 0;
return n;
}

Token scan_identifier_or_keyword() {
const char* start = cursor_;
while (cursor_ < end_) {
char c = *cursor_;
if (static_cast<unsigned char>(c) >= 0x80) {
const size_t n = utf8_identifier_char_length(cursor_);
if (n == 0) {
++cursor_;
return make_token(TokenType::TK_ERROR, start,
static_cast<uint32_t>(cursor_ - start));
}
cursor_ += n;
continue;
}
bool is_cont = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_';
// PostgreSQL allows `$` as an identifier continuation char (but
Expand Down Expand Up @@ -613,7 +677,8 @@ class Tokenizer {
}

// Identifiers and keywords
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_') {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' ||
static_cast<unsigned char>(c) >= 0x80) {
return scan_identifier_or_keyword();
}

Expand Down Expand Up @@ -705,6 +770,16 @@ class Tokenizer {
char c2 = peek_char(1);

if constexpr (D == Dialect::MySQL) {
if (c == '<' && c2 == '=' && peek_char(2) == '>') {
const char* start = cursor_;
cursor_ += 3;
return make_token(TokenType::TK_MYSQL_NULL_SAFE_EQUAL, start, 3);
}
if (c == '&' && c2 == '&') {
const char* start = cursor_;
cursor_ += 2;
return make_token(TokenType::TK_MYSQL_LOGICAL_AND, start, 2);
}
if (c == '-' && c2 == '>') {
const char* start = cursor_;
cursor_ += 2;
Expand Down Expand Up @@ -761,6 +836,20 @@ class Tokenizer {
}
};

template <Dialect D>
class ParseDepthGuard {
public:
explicit ParseDepthGuard(Tokenizer<D>& tokenizer)
: tokenizer_(tokenizer), entered_(tokenizer.enter_parse()) {}
~ParseDepthGuard() { if (entered_) tokenizer_.leave_parse(); }
explicit operator bool() const { return entered_; }
ParseDepthGuard(const ParseDepthGuard&) = delete;
ParseDepthGuard& operator=(const ParseDepthGuard&) = delete;
private:
Tokenizer<D>& tokenizer_;
bool entered_;
};

} // namespace sql_parser

#endif // SQL_PARSER_TOKENIZER_H
Loading
Loading