-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconditionals.py
More file actions
95 lines (75 loc) · 2.48 KB
/
conditionals.py
File metadata and controls
95 lines (75 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# This file is part of python-sql. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from sql import CombiningQuery, Expression, Flavor, Select
__all__ = ['Case', 'Coalesce', 'NullIf', 'Greatest', 'Least']
class Conditional(Expression):
__slots__ = ()
_sql = ''
table = ''
name = ''
@staticmethod
def _format(value):
if isinstance(value, Expression):
return str(value)
elif isinstance(value, (Select, CombiningQuery)):
return '(%s)' % value
else:
return Flavor().get().param
class Case(Conditional):
__slots__ = ('whens', 'else_')
def __init__(self, *whens, **kwargs):
self.whens = whens
self.else_ = kwargs.get('else_')
def __str__(self):
case = 'CASE '
for cond, result in self.whens:
case += 'WHEN %s THEN %s ' % (
self._format(cond), self._format(result))
if self.else_ is not None:
case += 'ELSE %s ' % self._format(self.else_)
case += 'END'
return case
@property
def params(self):
p = []
for cond, result in self.whens:
if isinstance(cond, (Expression, Select, CombiningQuery)):
p.extend(cond.params)
else:
p.append(cond)
if isinstance(result, (Expression, Select, CombiningQuery)):
p.extend(result.params)
else:
p.append(result)
if self.else_ is not None:
if isinstance(self.else_, (Expression, Select, CombiningQuery)):
p.extend(self.else_.params)
else:
p.append(self.else_)
return tuple(p)
class Coalesce(Conditional):
__slots__ = ('values')
_conditional = 'COALESCE'
def __init__(self, *values):
self.values = values
def __str__(self):
return (self._conditional
+ '(' + ', '.join(map(self._format, self.values)) + ')')
@property
def params(self):
p = []
for value in self.values:
if isinstance(value, (Expression, Select, CombiningQuery)):
p.extend(value.params)
else:
p.append(value)
return tuple(p)
class NullIf(Coalesce):
__slots__ = ()
_conditional = 'NULLIF'
class Greatest(Coalesce):
__slots__ = ()
_conditional = 'GREATEST'
class Least(Coalesce):
__slots__ = ()
_conditional = 'LEAST'