Skip to content

Commit

Permalink
implemented and expression
Browse files Browse the repository at this point in the history
  • Loading branch information
yukikaoru committed Dec 30, 2019
1 parent e51a708 commit c3f64b5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 9 deletions.
51 changes: 45 additions & 6 deletions csrestructuredquery/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,56 @@

import abc
import typing
from dataclasses import dataclass
from datetime import datetime

if typing.TYPE_CHECKING:
from csrestructuredquery.typing import Condition
from csrestructuredquery.typing import Expression, CsValue


class Query:
def __init__(self, *conditions: Condition):
...
def __init__(self, *expressions: Expression):
self.__expressions = expressions

def build(self) -> str:
return And(*self.__expressions).query()

class LogicalCondition(metaclass=abc.ABCMeta):
"""論理条件文の基底クラス"""

...
@dataclass(frozen=True)
class ExpressionValue:
value: CsValue

def __str__(self) -> str:
return format(self.value)

def __format__(self, format_spec) -> str:
if self.value is None:
return ""
if isinstance(self.value, datetime):
return f"'{self.value.isoformat()}'"
if isinstance(self.value, str):
return f"'{self.value}'"
return str(self.value)


class LogicalExpression(metaclass=abc.ABCMeta):
"""論理式の基底クラス"""

name: str

def __init__(self, *expressions: Expression):
self.__expressions = expressions

def query(self) -> str:
q = f"({self.name}"
for expr in self.__expressions:
if isinstance(expr, tuple):
q += f" {expr[0]}:{ExpressionValue(expr[1])}"
else:
q += expr.query()
q += ")"
return q


class And(LogicalExpression):
name = "and"
8 changes: 5 additions & 3 deletions csrestructuredquery/typing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import typing
from datetime import datetime
from typing import Tuple, Union

from csrestructuredquery.query import LogicalCondition
from csrestructuredquery.query import LogicalExpression

Condition = typing.Union[LogicalCondition]
CsValue = Union[int, str, datetime]
Expression = Union[LogicalExpression, Tuple]

0 comments on commit c3f64b5

Please sign in to comment.