Skip to content

Some fixes/improvements for sqlite #828

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1427,7 +1427,7 @@ This produces:
Contributing
------------

We welcome community contributions to |Brand|. Please see the `contributing guide <6_contributing.html>`_ to more info.
We welcome community contributions to |Brand|. Please see the `contributing guide <CONTRIBUTING.rst>`_ to more info.

.. _contributing_end:

Expand Down
16 changes: 15 additions & 1 deletion pypika/dialects.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,7 +950,9 @@ class SQLLiteQueryBuilder(QueryBuilder):
QUERY_CLS = SQLLiteQuery

def __init__(self, **kwargs: Any) -> None:
super().__init__(dialect=Dialects.SQLLITE, wrapper_cls=SQLLiteValueWrapper, **kwargs)
if kwargs.get("wrapper_cls") is None:
kwargs["wrapper_cls"] = SQLLiteValueWrapper
super().__init__(dialect=Dialects.SQLLITE, **kwargs)
self._insert_or_replace = False

@builder
Expand All @@ -962,3 +964,15 @@ def insert_or_replace(self, *terms: Any) -> "SQLLiteQueryBuilder":
def _replace_sql(self, **kwargs: Any) -> str:
prefix = "INSERT OR " if self._insert_or_replace else ""
return prefix + super()._replace_sql(**kwargs)

@builder
def for_update(
self, nowait: bool = False, skip_locked: bool = False, of: TypedTuple[str, ...] = ()
) -> "QueryBuilder":
self._for_update = False

def _insert_sql(self, **kwargs: Any) -> str:
return "INSERT {ignore}INTO {table}".format(
table=self._insert_table.get_sql(**kwargs),
ignore="OR IGNORE " if self._ignore else "",
)
8 changes: 8 additions & 0 deletions pypika/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,14 @@ class Now(Function):
def __init__(self, alias=None):
super(Now, self).__init__("NOW", alias=alias)

def get_function_sql(self, **kwargs):
# Handle SQLite compatibility - it uses CURRENT_TIMESTAMP instead of NOW()
from .enums import Dialects

if kwargs.get('dialect') == Dialects.SQLLITE:
return "CURRENT_TIMESTAMP"
return super(Now, self).get_function_sql(**kwargs)


class UtcTimestamp(Function):
def __init__(self, alias=None):
Expand Down
44 changes: 44 additions & 0 deletions pypika/terms.py
Original file line number Diff line number Diff line change
Expand Up @@ -1623,11 +1623,24 @@ class Interval(Node):
# Oracle and MySQL requires just single quotes around the expr
Dialects.ORACLE: "INTERVAL '{expr}' {unit}",
Dialects.MYSQL: "INTERVAL '{expr}' {unit}",
# SQLite doesn't have a direct INTERVAL type, use datetime functions instead
Dialects.SQLLITE: "{expr} {unit}",
}

units = ["years", "months", "days", "hours", "minutes", "seconds", "microseconds"]
labels = ["YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "SECOND", "MICROSECOND"]

# SQLite unit conversion mapping
sqlite_units = {
"YEAR": "years",
"MONTH": "months",
"DAY": "days",
"HOUR": "hours",
"MINUTE": "minutes",
"SECOND": "seconds",
"MICROSECOND": "microseconds",
}

trim_pattern = re.compile(r"(^0+\.)|(\.0+$)|(^[0\-.: ]+[\-: ])|([\-:. ][0\-.: ]+$)")

def __init__(
Expand Down Expand Up @@ -1675,6 +1688,9 @@ def __str__(self) -> str:
def get_sql(self, **kwargs: Any) -> str:
dialect = self.dialect or kwargs.get("dialect")

if dialect == Dialects.SQLLITE:
return self._get_sqlite_sql()

if self.largest == "MICROSECOND":
expr = getattr(self, "microseconds")
unit = "MICROSECOND"
Expand Down Expand Up @@ -1717,6 +1733,34 @@ def get_sql(self, **kwargs: Any) -> str:

return self.templates.get(dialect, "INTERVAL '{expr} {unit}'").format(expr=expr, unit=unit)

def _get_sqlite_sql(self) -> str:
"""Generate SQLite-compatible interval expression using datetime functions"""
if hasattr(self, "quarters"):
# Convert quarters to months for SQLite
value = getattr(self, "quarters") * 3
sign = "-" if self.is_negative else "+"
return f"datetime('now', '{sign}{value} months')"

if hasattr(self, "weeks"):
# Convert weeks to days for SQLite
value = getattr(self, "weeks") * 7
sign = "-" if self.is_negative else "+"
return f"datetime('now', '{sign}{value} days')"

# Construct datetime expression with each non-zero component
components = []
for unit, label in zip(self.units, self.labels):
if hasattr(self, unit) and getattr(self, unit):
value = getattr(self, unit)
sign = "-" if self.is_negative else "+"
sqlite_unit = self.sqlite_units.get(label, unit)
components.append(f"'{sign}{value} {sqlite_unit}'")

if not components:
return "datetime('now')"

return f"datetime('now', {', '.join(components)})"


class Pow(Function):
def __init__(self, term: Term, exponent: float, alias: Optional[str] = None) -> None:
Expand Down