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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
### Bug Fixes

- Expand `~` in configured log file paths before opening the log.
- Support the `REGEXP` operator when SQLite does not provide one. [(#139)](https://github.com/dbcli/litecli/issues/139)

### Internal

Expand Down
18 changes: 18 additions & 0 deletions litecli/sqlexecute.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import logging
import os.path
import re
from contextlib import closing
from typing import Any, Generator, Iterable, cast
from urllib.parse import urlparse
Expand All @@ -23,6 +24,22 @@

_logger = logging.getLogger(__name__)


def _regexp(pattern: str | None, value: Any) -> bool | None:
"""Implement SQLite's ``X REGEXP Y`` operator, which calls ``regexp(Y, X)``."""
if pattern is None or value is None:
return None
return re.search(pattern, str(value)) is not None


def _register_regexp(conn: Any) -> None:
"""Register a Python REGEXP function unless the connection already provides one (e.g. sqlean)."""
try:
conn.execute("SELECT 'a' REGEXP 'a'")
except sqlite3.OperationalError:
conn.create_function("REGEXP", 2, _regexp, deterministic=True)


# FIELD_TYPES = decoders.copy()
# FIELD_TYPES.update({
# FIELD_TYPE.NULL: type(None)
Expand Down Expand Up @@ -90,6 +107,7 @@ def connect(self, database: str | None = None) -> None:

conn = sqlite3.connect(database=db_name, isolation_level=None, uri=uri)
conn.text_factory = lambda x: x.decode("utf-8", "backslashreplace")
_register_regexp(conn)
if self.conn:
self.conn.close()

Expand Down
14 changes: 14 additions & 0 deletions tests/test_sqlexecute.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,3 +392,17 @@ def test_time_null(executor):
run(executor, """insert into time_null values(null)""")
results = run(executor, """select * from time_null""")
assert_result_equal(results, headers=["a"], rows=[(None,)])


@dbtest
def test_regexp_operator(executor):
run(executor, "create table regexp_test(t text)")
run(executor, "insert into regexp_test (t) values ('apple'), ('banana'), ('cherry'), (null)")
results = run(executor, "select t from regexp_test where t regexp '^b|y$' order by t")
assert_result_equal(results, headers=["t"], rows=[("banana",), ("cherry",)])


@dbtest
def test_regexp_null_and_non_text(executor):
results = run(executor, "select null regexp 'a', 'a' regexp null, 123 regexp '^1'")
assert results[0]["rows"] == [(None, None, 1)]