docudb  1.0
Loading...
Searching...
No Matches
sqlite_extensions.cpp
Go to the documentation of this file.
1#include "sqlite_extensions.h"
2#include <regex>
3#include <string>
4
5using namespace std::string_literals;
6
7/**
8 * @brief Implements the REGEXP operator for SQLite.
9 * Called by SQLite when expr REGEXP pattern is evaluated.
10 * @param context SQLite function context (for setting result).
11 * @param argc Number of arguments (should be 2).
12 * @param argv Array of SQLite value pointers (argv[0]=pattern, argv[1]=text).
13 */
14void sqlite_regexp_func(sqlite3_context* context, int argc, sqlite3_value** argv) {
15 if (argc != 2) {
16 const char* errorMsg = "REGEXP requires exactly two arguments.";
17 sqlite3_result_error(context, errorMsg, -1); // Use -1 for length to let SQLite calculate
18 return;
19 }
20
21 // Get pattern (arg 0) and text (arg 1) as C strings
22 // Use sqlite3_value_type to check for NULLs first
23 const unsigned char* pattern_uch = sqlite3_value_text(argv[0]);
24 const unsigned char* text_uch = sqlite3_value_text(argv[1]);
25
26 // If either pattern or text is NULL, the result of REGEXP is usually NULL or false (0)
27 // Let's return false (0) which seems safer in a boolean context.
28 if (!pattern_uch || !text_uch) {
29 sqlite3_result_int(context, 0); // Return 0 (false) for NULL inputs
30 return;
31 }
32
33 const char* pattern = reinterpret_cast<const char*>(pattern_uch);
34 const char* text = reinterpret_cast<const char*>(text_uch);
35
36 try {
37 // Use C++ std::regex for the matching logic
38 // NOTE: std::regex syntax is often ECMAScript by default. SQLite users
39 // might expect POSIX ERE or other syntax. Sticking to default for now.
40 std::regex regex_pattern(pattern); // Compile the pattern
41
42 // Use std::regex_search to see if the pattern matches anywhere in the text
43 bool match_found = std::regex_search(text, regex_pattern);
44
45 // Set the SQLite result: 1 for match, 0 for no match
46 sqlite3_result_int(context, match_found ? 1 : 0);
47
48 } catch (const std::regex_error& e) {
49 // Handle invalid regex patterns provided in the query
50 std::string errorMsg = "REGEXP pattern error: "s + e.what();
51 sqlite3_result_error(context, errorMsg.c_str(), errorMsg.length());
52 } catch (const std::exception& e) {
53 // Handle other unexpected errors
54 std::string errorMsg = "REGEXP unexpected error: "s + e.what();
55 sqlite3_result_error(context, errorMsg.c_str(), errorMsg.length());
56 }
57}
void sqlite_regexp_func(sqlite3_context *context, int argc, sqlite3_value **argv)
Implements the REGEXP operator for SQLite. Called by SQLite when expr REGEXP pattern is evaluated.