Skip to content
Open
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
89 changes: 85 additions & 4 deletions include/sql_parser/digest.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,29 @@ struct DigestResult {
uint64_t hash; // 64-bit FNV-1a hash
};

// A literal the token-level digest replaced with '?': its token type and where
// its source spelling (quotes and prefixes included) sits in the input.
struct DigestLiteral {
TokenType type;
uint32_t offset;
uint32_t length;
};

// What the token-level digest replaced, dropped or could not represent. It is
// for a caller that wants to treat two statements with the same normalized
// text as the same statement with different literal values: that holds only
// when none of the flags is set and the non-value literals are compared too.
struct DigestTrace {
static constexpr uint32_t max_literals = 16;
DigestLiteral literals[max_literals];
uint32_t literal_count = 0; // all literals seen; only the first max_literals are recorded
uint32_t consumed = 0; // input bytes up to and including the terminating ';', else all
bool collapsed = false; // an IN list or VALUES rows were collapsed (tokens dropped)
bool delimited_identifier = false; // a quoted identifier lost its delimiters in the text
bool comments = false; // a comment was skipped
bool errors = false; // the tokenizer returned an error token
};

// FNV-1a 64-bit hash -- simple, fast, no external dependency
struct FnvHash {
static constexpr uint64_t FNV_OFFSET_BASIS = 14695981039346656037ULL;
Expand Down Expand Up @@ -58,8 +81,22 @@ class Digest {
return compute_token_level(sql, len);
}

// The same token-level digest, also reporting in 'trace' what the
// normalized text no longer shows. One tokenizer pass either way.
DigestResult compute(const char* sql, size_t len, DigestTrace& trace) {
trace.literal_count = 0;
trace.consumed = 0;
trace.collapsed = trace.delimited_identifier = trace.comments = trace.errors = false;
trace_ = &trace;
const DigestResult result = compute_token_level(sql, len);
trace_ = nullptr;
return result;
}

private:
Arena& arena_;
DigestTrace* trace_ = nullptr;
const char* input_ = nullptr;

// Helper: check if a token type is a keyword (not an identifier, literal, or operator)
static bool is_keyword_token(TokenType type) {
Expand All @@ -83,8 +120,10 @@ class Digest {

// Append token text uppercased to StringBuilder
static void append_upper(StringBuilder& sb, const char* ptr, uint32_t len) {
char* out = sb.extend(len);
if (!out) return;
for (uint32_t i = 0; i < len; ++i) {
sb.append_char(to_upper(ptr[i]));
out[i] = to_upper(ptr[i]);
}
}

Expand All @@ -104,8 +143,32 @@ class Digest {
return true;
}

// Report a literal that the normalized text shows as '?'.
void trace_literal(const Token& t) {
if (!trace_) return;
if (trace_->literal_count < DigestTrace::max_literals) {
trace_->literals[trace_->literal_count] = DigestLiteral{
t.type, static_cast<uint32_t>(t.source.ptr - input_), t.source.len};
}
++trace_->literal_count;
}
// Report that tokens were left out of the normalized text.
void trace_collapsed() {
if (trace_) trace_->collapsed = true;
}

// Emit a single token to the string builder, uppercasing keywords, replacing literals with ?
void emit_token(StringBuilder& sb, const Token& t, TokenType prev) {
emit_token_inline(sb, t, prev);
}

// The body of emit_token(), expanded in place where the caller is the
// per-token loop of an ordinary statement: there the call and passing the
// token through memory cost more than the work itself.
#if defined(__GNUC__) || defined(__clang__)
__attribute__((always_inline))
#endif
inline void emit_token_inline(StringBuilder& sb, const Token& t, TokenType prev) {
bool quoted_user_after_account = t.type == TokenType::TK_USER_VARIABLE &&
t.source.len >= 2 &&
(t.source.ptr[1] == '\'' || t.source.ptr[1] == '"' || t.source.ptr[1] == '`') &&
Expand All @@ -116,9 +179,11 @@ class Digest {

if (is_literal_token(t.type)) {
sb.append_char('?');
trace_literal(t);
} else if (is_keyword_token(t.type)) {
append_upper(sb, t.text.ptr, t.text.len);
} else if (t.type == TokenType::TK_IDENTIFIER) {
if (trace_ && t.source.len != t.text.len) trace_->delimited_identifier = true;
sb.append(t.text.ptr, t.text.len);
} else if (t.type == TokenType::TK_QUESTION) {
sb.append_char('?');
Expand Down Expand Up @@ -152,6 +217,7 @@ class Digest {
DigestResult compute_token_level(const char* sql, size_t len) {
Tokenizer<D> tok;
tok.reset(sql, len);
input_ = sql;
StringBuilder sb(arena_);
TokenType prev = TokenType::TK_EOF;

Expand All @@ -172,6 +238,7 @@ class Digest {
// Emit " ("
emit_token(sb, next, prev);
prev = next.type;
trace_collapsed();
// Collapse contents to single ?
bool emitted_q = false;
int depth = 1;
Expand Down Expand Up @@ -214,13 +281,16 @@ class Digest {
emit_token(sb, next, prev);
prev = next.type;

// Emit first row contents with ? for each value slot
// Emit first row contents with ? for each value slot. A
// row of plain literals loses nothing; any other token in
// it is left out of the text and reported as collapsed.
int depth = 1;
while (depth > 0) {
Token inner = tok.next_token();
if (inner.type == TokenType::TK_EOF) break;
if (inner.type == TokenType::TK_EOF) { trace_collapsed(); break; }
if (inner.type == TokenType::TK_LPAREN) {
depth++;
trace_collapsed();
continue;
}
if (inner.type == TokenType::TK_RPAREN) {
Expand All @@ -243,8 +313,11 @@ class Digest {
if (prev == TokenType::TK_LPAREN || prev == TokenType::TK_COMMA) {
sb.append_char('?');
prev = TokenType::TK_QUESTION;
if (is_literal_token(inner.type)) trace_literal(inner);
continue;
}
}
trace_collapsed();
}

// Skip additional rows: , (...)
Expand All @@ -254,6 +327,7 @@ class Digest {
Token peek2 = tok.next_token();
if (peek2.type == TokenType::TK_LPAREN) {
// Skip this entire row
trace_collapsed();
skip_paren_contents(tok);
continue;
} else {
Expand Down Expand Up @@ -281,14 +355,21 @@ class Digest {
// Check if we've reached the end (can happen after VALUES/IN lookahead)
if (t.type == TokenType::TK_EOF || t.type == TokenType::TK_SEMICOLON) break;

emit_token(sb, t, prev);
emit_token_inline(sb, t, prev);
prev = t.type;
// For literal tokens, record as TK_QUESTION since we emitted ?
if (is_literal_token(t.type)) prev = TokenType::TK_QUESTION;

t = tok.next_token();
}

if (trace_) {
trace_->consumed = t.type == TokenType::TK_SEMICOLON
? static_cast<uint32_t>(t.source.ptr + t.source.len - sql)
: static_cast<uint32_t>(len);
trace_->comments = tok.has_comments();
trace_->errors = tok.has_error();
}
StringRef normalized = sb.finish();
FnvHash hasher;
hasher.update(normalized.ptr, normalized.len);
Expand Down
34 changes: 30 additions & 4 deletions include/sql_parser/keyword_hash.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ inline uint32_t hash_keyword(const char* text, uint32_t len) {
return h;
}

// hash_keyword() one byte at a time, for a scanner that already walks the
// text: hash_keyword(text, len) equals folding hash_keyword_step() over the
// bytes of text starting from HASH_SEED.
static constexpr uint32_t HASH_SEED = 0x811c9dc5u;
inline uint32_t hash_keyword_step(uint32_t h, uint8_t c) {
if (c >= 'A' && c <= 'Z') c += 32;
h ^= c;
h *= 0x01000193u;
return h;
}

// Hash table entry
struct HashEntry {
const char* text; // uppercase keyword text (nullptr = empty slot)
Expand Down Expand Up @@ -67,10 +78,10 @@ inline void build_table(const KeywordEntry (&keywords)[N], HashEntry (&table)[TA
}
}

// Lookup a keyword in a pre-built hash table.
inline TokenType lookup_in_table(const HashEntry (&table)[TABLE_SIZE],
const char* text, uint32_t len) {
uint32_t idx = hash_keyword(text, len) & TABLE_MASK;
// Lookup a keyword in a pre-built hash table, given hash_keyword(text, len).
inline TokenType lookup_in_table_hashed(const HashEntry (&table)[TABLE_SIZE],
const char* text, uint32_t len, uint32_t hash) {
uint32_t idx = hash & TABLE_MASK;
for (uint32_t probe = 0; probe <= MAX_PROBE; ++probe) {
const HashEntry& e = table[idx];
if (e.text == nullptr) return TokenType::TK_IDENTIFIER;
Expand All @@ -80,6 +91,21 @@ inline TokenType lookup_in_table(const HashEntry (&table)[TABLE_SIZE],
return TokenType::TK_IDENTIFIER;
}

// Lookup a keyword in a pre-built hash table.
inline TokenType lookup_in_table(const HashEntry (&table)[TABLE_SIZE],
const char* text, uint32_t len) {
return lookup_in_table_hashed(table, text, len, hash_keyword(text, len));
}

// Length of the longest keyword of an array: a longer word is not a keyword.
template <typename KeywordEntry, size_t N>
constexpr uint32_t max_keyword_length(const KeywordEntry (&keywords)[N]) {
uint32_t longest = 0;
for (size_t k = 0; k < N; ++k)
if (keywords[k].len > longest) longest = keywords[k].len;
return longest;
}

} // namespace keyword_hash
} // namespace sql_parser

Expand Down
9 changes: 9 additions & 0 deletions include/sql_parser/keywords_mysql.h
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,15 @@ inline TokenType lookup(const char* text, uint32_t len) {
return keyword_hash::lookup_in_table(HASH_TABLE, text, len);
}

inline constexpr uint32_t MAX_KEYWORD_LENGTH = keyword_hash::max_keyword_length(KEYWORDS);

// lookup() for a caller that computed keyword_hash::hash_keyword(text, len)
// while scanning the word.
inline TokenType lookup_hashed(const char* text, uint32_t len, uint32_t hash) {
if (len > MAX_KEYWORD_LENGTH) return TokenType::TK_IDENTIFIER;
return keyword_hash::lookup_in_table_hashed(HASH_TABLE, text, len, hash);
}

} // namespace mysql_keywords
} // namespace sql_parser

Expand Down
9 changes: 9 additions & 0 deletions include/sql_parser/keywords_pgsql.h
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,15 @@ inline TokenType lookup(const char* text, uint32_t len) {
return keyword_hash::lookup_in_table(HASH_TABLE, text, len);
}

inline constexpr uint32_t MAX_KEYWORD_LENGTH = keyword_hash::max_keyword_length(KEYWORDS);

// lookup() for a caller that computed keyword_hash::hash_keyword(text, len)
// while scanning the word.
inline TokenType lookup_hashed(const char* text, uint32_t len, uint32_t hash) {
if (len > MAX_KEYWORD_LENGTH) return TokenType::TK_IDENTIFIER;
return keyword_hash::lookup_in_table_hashed(HASH_TABLE, text, len, hash);
}

} // namespace pgsql_keywords
} // namespace sql_parser

Expand Down
11 changes: 11 additions & 0 deletions include/sql_parser/string_builder.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ class StringBuilder {
}
}

// Room for n more bytes, already counted in the length, for a caller that
// writes them itself. Null when the arena is exhausted, as append() then
// appends nothing.
char* extend(size_t n) {
ensure_capacity(n);
if (!buf_) return nullptr;
char* at = buf_ + len_;
len_ += n;
return at;
}

void append(StringRef ref) {
if (ref.ptr && ref.len > 0) {
append(ref.ptr, ref.len);
Expand Down
Loading
Loading