Skip to content

Commit 973dedd

Browse files
committed
refactored Table.Meta to Table._meta, and using __init_subclass__
1 parent 59209d8 commit 973dedd

File tree

23 files changed

+113
-120
lines changed

23 files changed

+113
-120
lines changed

docs/src/piccolo/migrations/create.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ forwards and backwards functions.
4242
4343
4444
async def forwards():
45-
transaction = Band.Meta.db.transaction()
45+
transaction = Band._meta.db.transaction()
4646
4747
transaction.add(
4848
Band.create_without_columns(),

docs/src/piccolo/query_types/transactions.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ Usage
1313

1414
.. code-block:: python
1515
16-
transaction = Band.Meta.db.transaction()
16+
transaction = Band._meta.db.transaction()
1717
transaction.add(Manager.create())
1818
transaction.add(Concert.create())
1919
await transaction.run()

piccolo/columns/base.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@
2828

2929
@dataclass
3030
class ColumnMeta:
31+
"""
32+
We store as many attributes in ColumnMeta as possible, to help avoid name
33+
clashes with user defined attributes.
34+
"""
35+
3136
# General attributes:
3237
null: bool = True
3338
primary: bool = False
@@ -64,7 +69,7 @@ def table(self) -> Table:
6469

6570
@property
6671
def engine_type(self) -> str:
67-
engine = self.table.Meta.db
72+
engine = self.table._meta.db
6873
if engine:
6974
return engine.engine_type
7075
else:
@@ -77,7 +82,7 @@ def get_full_name(self, just_alias=False) -> str:
7782
column_name = self.name
7883

7984
if not self.call_chain:
80-
return f"{self.table.Meta.tablename}.{column_name}"
85+
return f"{self.table._meta.tablename}.{column_name}"
8186

8287
column_name = (
8388
"$".join([i._meta.name for i in self.call_chain])
@@ -173,7 +178,7 @@ def querystring(self) -> QueryString:
173178
foreign_key_meta = getattr(self, "foreign_key_meta", None)
174179
if foreign_key_meta:
175180
references = foreign_key_meta.references
176-
query += f" REFERENCES {references.Meta.tablename}"
181+
query += f" REFERENCES {references._meta.tablename}"
177182

178183
return QueryString(query)
179184

piccolo/columns/column_types.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,15 @@ def __init__(self, **kwargs) -> None:
4242
class PrimaryKey(Column):
4343
@property
4444
def column_type(self):
45-
engine_type = self._meta.table.Meta.db.engine_type
45+
engine_type = self._meta.table._meta.db.engine_type
4646
if engine_type == "postgres":
4747
return "SERIAL"
4848
elif engine_type == "sqlite":
4949
return "INTEGER"
5050
raise Exception("Unrecognized engine type")
5151

5252
def default(self):
53-
engine_type = self._meta.table.Meta.db.engine_type
53+
engine_type = self._meta.table._meta.db.engine_type
5454
if engine_type == "postgres":
5555
return DEFAULT
5656
elif engine_type == "sqlite":
@@ -123,7 +123,7 @@ def __init__(self, references: t.Type[Table], **kwargs) -> None:
123123

124124
# Allow columns on the referenced table to be accessed via auto
125125
# completion.
126-
for column in references.Meta.columns:
126+
for column in references._meta.columns:
127127
_column: Column = copy.deepcopy(column)
128128
setattr(self, _column._meta.name, _column)
129129
self._foreign_key_meta.proxy_columns.append(_column)
@@ -164,7 +164,7 @@ def __getattribute__(self, name: str):
164164
except Exception:
165165
pass
166166

167-
for column in value._foreign_key_meta.references.Meta.columns:
167+
for column in value._foreign_key_meta.references._meta.columns:
168168
_column: Column = copy.deepcopy(column)
169169
_column._meta.call_chain = copy.copy(
170170
new_column._meta.call_chain

piccolo/commands/playground.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,11 @@ def playground(engine, user, password, database, host, port):
110110
}
111111
)
112112
for _table in TABLES:
113-
_table.Meta.db = db
113+
_table._meta.db = db
114114
else:
115115
db = SQLiteEngine()
116116
for _table in TABLES:
117-
_table.Meta.db = db
117+
_table._meta.db = db
118118

119119
print("Tables:\n")
120120

piccolo/extensions/user.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@
1010
from piccolo.columns import Varchar, Boolean
1111

1212

13-
class BaseUser(Table):
13+
class BaseUser(Table, tablename="piccolo_user"):
1414
"""
15-
Subclass this table in your own project, so Meta.db can be defined.
15+
Provides a basic user, with authentication support. Use as is, or subclass,
16+
in your own projects.
1617
"""
1718

1819
username = Varchar(length=100, unique=True)
@@ -21,11 +22,6 @@ class BaseUser(Table):
2122
active = Boolean(default=False)
2223
admin = Boolean(default=False)
2324

24-
class Meta:
25-
# This is required because 'user' is a reserved keyword in SQL, so
26-
# using it as a tablename causes issues.
27-
tablename = "piccolo_user"
28-
2925
def __init__(self, **kwargs):
3026
"""
3127
Generating passwords upfront is expensive, so might need reworking.
@@ -56,9 +52,7 @@ async def update_password(cls, user: t.Union[str, int], password: str):
5652
elif type(user) == int:
5753
clause = cls.id == user # type: ignore
5854
else:
59-
raise ValueError(
60-
"The `user` arg must be a user id, or a username."
61-
)
55+
raise ValueError("The `user` arg must be a user id, or a username.")
6256

6357
password = cls.hash_password(password)
6458
await cls.update().values({cls.password: password}).where(clause).run()

piccolo/main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def forwards():
128128
print('Running migrations ...')
129129
sys.path.insert(0, os.getcwd())
130130

131-
Migration.Meta.db = PostgresEngine(_get_config())
131+
Migration._meta.db = PostgresEngine(_get_config())
132132

133133
_create_migration_table()
134134

@@ -169,7 +169,7 @@ def backwards(migration_name: str):
169169
_get_config() # Just required for path manipulation - needs changing
170170
_get_migration_modules()
171171

172-
Migration.Meta.db = PostgresEngine(_get_config())
172+
Migration._meta.db = PostgresEngine(_get_config())
173173

174174
_create_migration_table()
175175

piccolo/query/base.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,17 @@ def setup_delegates(self):
2929

3030
@property
3131
def engine_type(self) -> str:
32-
engine = self.table.Meta.db
32+
engine = self.table._meta.db
3333
if engine:
3434
return engine.engine_type
3535
else:
3636
raise ValueError("Engine isn't defined.")
3737

3838
async def run(self, in_pool=True):
39-
engine = getattr(self.table.Meta, "db", None)
39+
engine = getattr(self.table._meta, "db", None)
4040
if not engine:
4141
raise ValueError(
42-
f"Table {self.table.Meta.tablename} has no db defined in Meta"
42+
f"Table {self.table._meta.tablename} has no db defined in _meta"
4343
)
4444

4545
results = await engine.run_querystring(

piccolo/query/methods/alter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def querystring(self) -> QueryString:
5656
if self.boolean:
5757
return QueryString(f"ADD UNIQUE ({self.column._meta.name})")
5858
else:
59-
tablename = self.column._meta.table.Meta.tablename
59+
tablename = self.column._meta.table._meta.tablename
6060
column_name = self.column._meta.name
6161
key = f"{tablename}_{column_name}_key"
6262
return QueryString(f'DROP CONSTRAINT "{key}"')
@@ -120,7 +120,7 @@ def set_null(self, column: Column, boolean: bool = True) -> Alter:
120120

121121
@property
122122
def querystring(self) -> QueryString:
123-
query = f"ALTER TABLE {self.table.Meta.tablename}"
123+
query = f"ALTER TABLE {self.table._meta.tablename}"
124124

125125
alterations = [
126126
i.querystring

piccolo/query/methods/create.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ class Create(Query):
1111

1212
@property
1313
def querystring(self) -> QueryString:
14-
base = f'CREATE TABLE {self.table.Meta.tablename}'
15-
columns = ', '.join(['{}' for i in self.table.Meta.columns])
14+
base = f'CREATE TABLE {self.table._meta.tablename}'
15+
columns = ', '.join(['{}' for i in self.table._meta.columns])
1616
query = f'{base} ({columns})'
1717
return QueryString(
1818
query,
19-
*[i.querystring for i in self.table.Meta.columns]
19+
*[i.querystring for i in self.table._meta.columns]
2020
)
2121

2222
def __str__(self) -> str:

0 commit comments

Comments
 (0)