Dynamic Table creation and mapping #904
-
Hi i am creating a Multi-tenant system where each tenant would have their own separate tables, I was wondering is it possible to create multiple tables using the same schema and map them to the same object. here is a example on what i am trying to achieve in SqlAlchemy https://medium.com/@ketansomvanshi007/dynamic-object-mapping-in-sqlalchemy-for-multitenancy-4e7c5064c816 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Piccolo lets you specify which schema a table lives in: class MyTable(Table, schema='schema_1'):
my_column = Varchar() If you potentially have many schemas (one for each customer) you can create table classes at run time using this: Lines 1358 to 1387 in 5f972d0 For example: from piccolo.table import create_table_class
from piccolo.columns import Varchar
MyTable = create_table_class(
class_name='MyTable',
class_kwargs={
"schema": 'schema_1',
},
class_members={
'name': Varchar()
},
) You can then use that table like any other. For example: def get_table(schema: str):
return create_table_class(
class_name='MyTable',
class_kwargs={
"schema": schema,
},
class_members={
'name': Varchar()
},
)
async def get_user_data(schema: str):
MyTable = get_table(schema)
return await MyTable.objects() Another solution is to use Piccolo's reflection API. |
Beta Was this translation helpful? Give feedback.
Piccolo lets you specify which schema a table lives in:
If you potentially have many schemas (one for each customer) you can create table classes at run time using this:
piccolo/piccolo/table.py
Lines 1358 to 1387 in 5f972d0