Skip to content

Commit 6c276e1

Browse files
committed
cleanup wip
1 parent 16da469 commit 6c276e1

File tree

15 files changed

+262
-304
lines changed

15 files changed

+262
-304
lines changed

dev-requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
ipdb==0.11
22
ipython==7.1.1
33
twine==1.12.1
4-
mypy==0.710
4+
mypy==0.720

piccolo/columns/base.py

Lines changed: 65 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
from __future__ import annotations
12
import typing as t
2-
import warnings
33

4-
from .operators import (
4+
from piccolo.columns.operators import (
55
Equal,
66
GreaterEqualThan,
77
GreaterThan,
@@ -13,36 +13,39 @@
1313
NotEqual,
1414
NotIn,
1515
NotLike,
16-
Operator
16+
Operator,
1717
)
18-
from .combination import Where
19-
from ..custom_types import Iterable
20-
from ..querystring import QueryString
18+
from piccolo.columns.combination import Where
19+
from piccolo.custom_types import Iterable
20+
from piccolo.querystring import QueryString
21+
from piccolo.utils.warnings import colored_warning
2122

2223
if t.TYPE_CHECKING:
23-
from ..table import Table # noqa
24+
from piccolo.table import Table # noqa
2425
from .column_types import ForeignKey # noqa
2526

2627

27-
class Column():
28+
class Column:
2829

2930
value_type: t.Type = int
3031

32+
# Set by Table metaclass:
33+
_name: t.Optional[str] = None
34+
_table: t.Optional[Table] = None
35+
3136
def __init__(
3237
self,
3338
null: bool = True,
3439
primary: bool = False,
3540
key: bool = False,
36-
unique: bool = False
41+
unique: bool = False,
3742
) -> None:
3843
self.null = null
3944
self.primary = primary
4045
self.key = key
4146
self.unique = unique
42-
# Set by Table metaclass:
43-
self._name: t.Optional[str] = None
4447
# Used by foreign keys:
45-
self.call_chain: t.List['ForeignKey'] = []
48+
self.call_chain: t.List["ForeignKey"] = []
4649
self.table_alias: t.Optional[str] = None
4750

4851
def is_in(self, values: Iterable) -> Where:
@@ -52,25 +55,25 @@ def not_in(self, values: Iterable) -> Where:
5255
return Where(column=self, values=values, operator=NotIn)
5356

5457
def like(self, value: str) -> Where:
55-
if '%' not in value:
56-
raise ValueError('% is required for like operators')
58+
if "%" not in value:
59+
raise ValueError("% is required for like operators")
5760
return Where(column=self, value=value, operator=Like)
5861

5962
def ilike(self, value: str) -> Where:
60-
if '%' not in value:
61-
raise ValueError('% is required for ilike operators')
62-
if self._table.Meta.db.engine_type == 'postgres':
63+
if "%" not in value:
64+
raise ValueError("% is required for ilike operators")
65+
if self.engine_type == "postgres":
6366
operator: t.Type[Operator] = ILike
6467
else:
65-
warnings.warn(
68+
colored_warning(
6669
"SQLite doesn't support ILIKE currently, falling back to LIKE."
6770
)
6871
operator = Like
6972
return Where(column=self, value=value, operator=operator)
7073

7174
def not_like(self, value: str) -> Where:
72-
if '%' not in value:
73-
raise ValueError('% is required for like operators')
75+
if "%" not in value:
76+
raise ValueError("% is required for like operators")
7477
return Where(column=self, value=value, operator=NotLike)
7578

7679
def __lt__(self, value) -> Where:
@@ -92,22 +95,49 @@ def __ne__(self, value) -> Where: # type: ignore
9295
return Where(column=self, value=value, operator=NotEqual)
9396

9497
def __hash__(self):
95-
return hash(self._name)
98+
return hash(self.name)
99+
100+
@property
101+
def name(self) -> str:
102+
if not self._name:
103+
raise ValueError(
104+
"`_name` isn't defined - the Table Metaclass should set it."
105+
)
106+
return self._name
107+
108+
@name.setter
109+
def name(self, value: str):
110+
self._name = value
111+
112+
@property
113+
def table(self) -> Table:
114+
if not self._table:
115+
raise ValueError(
116+
"`_table` isn't defined - the Table Metaclass should set it."
117+
)
118+
return self._table
119+
120+
@property
121+
def engine_type(self) -> str:
122+
engine = self.table.Meta.db
123+
if engine:
124+
return engine.engine_type
125+
else:
126+
raise ValueError("The table has no engine defined.")
96127

97-
def get_full_name(self, just_alias=False) -> str:
128+
def _get_full_name(self, just_alias=False) -> str:
98129
"""
99130
Returns the full column name, taking into account joins.
100131
"""
101-
column_name = self._name
132+
column_name = self.name
102133

103134
if not self.call_chain:
104-
return f"{self._table.Meta.tablename}.{column_name}"
135+
return f"{self.table.Meta.tablename}.{column_name}"
105136

106137
column_name = (
107-
"$".join([i._name for i in self.call_chain])
108-
+ f"${column_name}"
138+
"$".join([i.name for i in self.call_chain]) + f"${column_name}"
109139
)
110-
alias = f"{self.call_chain[-1].table_alias}.{self._name}"
140+
alias = f"{self.call_chain[-1].table_alias}.{self.name}"
111141
if just_alias:
112142
return alias
113143
else:
@@ -118,23 +148,21 @@ def querystring(self) -> QueryString:
118148
"""
119149
Used when creating tables.
120150
"""
121-
name = getattr(self, '_name', '')
151+
name = getattr(self, "_name", "")
122152
column_type = getattr(
123-
self,
124-
'column_type',
125-
self.__class__.__name__.upper()
153+
self, "column_type", self.__class__.__name__.upper()
126154
)
127-
query = f'{name} {column_type}'
155+
query = f"{name} {column_type}"
128156
if self.primary:
129-
query += ' PRIMARY'
157+
query += " PRIMARY"
130158
if self.key:
131-
query += ' KEY'
159+
query += " KEY"
132160
if self.unique:
133-
query += ' UNIQUE'
161+
query += " UNIQUE"
134162

135-
references = getattr(self, 'references', None)
163+
references = getattr(self, "references", None)
136164
if references:
137-
query += f' REFERENCES {references.Meta.tablename}'
165+
query += f" REFERENCES {references.Meta.tablename}"
138166

139167
return QueryString(query)
140168

piccolo/columns/column_types.py

Lines changed: 26 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import annotations
12
import copy
23
from datetime import datetime
34
import typing as t
@@ -6,70 +7,65 @@
67
from piccolo.querystring import Unquoted
78

89
if t.TYPE_CHECKING:
9-
import table # noqa
10+
from piccolo.table import Table # noqa
1011
from piccolo.custom_types import Datetime # noqa
1112

1213

1314
class Varchar(Column):
1415

1516
value_type = str
1617

17-
def __init__(self, length: int = 255, default: str = None,
18-
**kwargs) -> None:
18+
def __init__(
19+
self, length: int = 255, default: str = None, **kwargs
20+
) -> None:
1921
self.length = length
2022
self.default = default
2123
super().__init__(**kwargs)
2224

2325

2426
class Integer(Column):
25-
2627
def __init__(self, default: int = None, **kwargs) -> None:
2728
self.default = default
2829
super().__init__(**kwargs)
2930

3031

3132
class Serial(Column):
32-
3333
def __init__(self, **kwargs) -> None:
3434
super().__init__(**kwargs)
3535

3636

37-
DEFAULT = Unquoted('DEFAULT')
38-
NULL = Unquoted('null')
37+
DEFAULT = Unquoted("DEFAULT")
38+
NULL = Unquoted("null")
3939

4040

4141
class PrimaryKey(Column):
42-
4342
@property
4443
def column_type(self):
4544
engine_type = self._table.Meta.db.engine_type
46-
if engine_type == 'postgres':
47-
return 'SERIAL'
48-
elif engine_type == 'sqlite':
49-
return 'INTEGER'
50-
raise Exception('Unrecognized engine type')
45+
if engine_type == "postgres":
46+
return "SERIAL"
47+
elif engine_type == "sqlite":
48+
return "INTEGER"
49+
raise Exception("Unrecognized engine type")
5150

5251
def default(self):
5352
engine_type = self._table.Meta.db.engine_type
54-
if engine_type == 'postgres':
53+
if engine_type == "postgres":
5554
return DEFAULT
56-
elif engine_type == 'sqlite':
55+
elif engine_type == "sqlite":
5756
return NULL
58-
raise Exception('Unrecognized engine type')
57+
raise Exception("Unrecognized engine type")
5958

6059
def __init__(self, **kwargs) -> None:
61-
kwargs.update({
62-
'primary': True,
63-
'key': True
64-
})
60+
kwargs.update({"primary": True, "key": True})
6561
super().__init__(**kwargs)
6662

6763

6864
class Timestamp(Column):
6965

7066
value_type = datetime
7167

72-
def __init__(self, default: 'Datetime' = None, **kwargs) -> None:
68+
def __init__(self, default: "Datetime" = None, **kwargs) -> None:
7369
self.default = default
7470
super().__init__(**kwargs)
7571

@@ -112,9 +108,9 @@ class ForeignKey(Integer):
112108
113109
"""
114110

115-
column_type = 'INTEGER'
111+
column_type = "INTEGER"
116112

117-
def __getattribute__(self, name):
113+
def __getattribute__(self, name: str):
118114
"""
119115
Returns attributes unmodified unless they're Column instances, in which
120116
case a copy is returned with an updated call_chain (which records the
@@ -128,7 +124,7 @@ def __getattribute__(self, name):
128124
except AttributeError:
129125
raise AttributeError
130126

131-
foreignkey_class = object.__getattribute__(self, '__class__')
127+
foreignkey_class = object.__getattribute__(self, "__class__")
132128

133129
if type(value) == foreignkey_class: # i.e. a ForeignKey
134130
new_column = copy.deepcopy(value)
@@ -142,21 +138,21 @@ def __getattribute__(self, name):
142138
# will be raised. Often there are more effective ways of
143139
# structuring a query than joining so many tables anyway.
144140
if len(new_column.call_chain) > 10:
145-
raise Exception('Call chain too long!')
141+
raise Exception("Call chain too long!")
146142

147143
for proxy_column in self.proxy_columns:
148144
try:
149-
delattr(new_column, proxy_column._name)
145+
delattr(new_column, proxy_column.name)
150146
except Exception:
151147
pass
152148

153149
for column in value.references.Meta.columns:
154150
_column = copy.deepcopy(column)
155151
_column.call_chain = copy.copy(new_column.call_chain)
156152
_column.call_chain.append(new_column)
157-
if _column._name == 'id':
153+
if _column._name == "id":
158154
continue
159-
setattr(new_column, _column._name, _column)
155+
setattr(new_column, _column.name, _column)
160156
self.proxy_columns.append(_column)
161157

162158
return new_column
@@ -168,7 +164,7 @@ def __getattribute__(self, name):
168164
else:
169165
return value
170166

171-
def __init__(self, references: t.Type['table.Table'], **kwargs) -> None:
167+
def __init__(self, references: t.Type[Table], **kwargs) -> None:
172168
super().__init__(**kwargs)
173169
self.references = references
174170
self.proxy_columns: t.List[Column] = []
@@ -177,5 +173,5 @@ def __init__(self, references: t.Type['table.Table'], **kwargs) -> None:
177173
# completion.
178174
for column in references.Meta.columns:
179175
_column = copy.deepcopy(column)
180-
setattr(self, column._name, _column)
176+
setattr(self, _column.name, _column)
181177
self.proxy_columns.append(_column)

0 commit comments

Comments
 (0)