Dynamic Table Name for entity at runtime
See original GitHub issueIssue type: [ ] question [ ] bug report [X] feature request [ ] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql
/ mariadb
[ ] oracle
[X] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo
TypeORM version:
[ ] latest
[X] @next
[ ] 0.x.x
(or put your version here)
Hello,
I am trying to migrate a PHP project to Nodejs and from Doctrine to TypeORM. I am currently stuck at setting dynamic table name for query.
We have many big table and we use table partition to keep table size relatively small so querying them won’t take too much time (cf https://www.postgresql.org/docs/10/ddl-partitioning.html)
For example, the table UserLog is partitioned by month. So in 2019 I have the following tables: user_log_201901 user_log_201902 user_log_201903 …
I am looking to achieve something like this:
class UserLog {...};
// Select
const originalRepo = getRepository(UserLog);
const repo201903 = originalRepo.cloneWithMetaData( { tableName: 'user_log_201903'});
const rows = await repo201903.find(); // Get all rows from user_log_201903 table
// Insertion
const newLog = new UserLog();
const repo201906 = originalRepo.cloneWithMetaData( { tableName: 'user_log_201906'});
repo201906.save(newLog);
Currently I can do it with Doctrine like this (not ideal but it works): $em ->getClassMetadata(‘MyApp\MyBundle\Entity\UserLog’) ->setTableName(‘user_log_201906’);
I am writing this as feature request as I cannot find a way to do it with TypeORM. Table partitioning is an important feature for any enterprise DBM so having support for it would help many developers.
(You can use trigger/rules at DBM level to redirect query to partition table but when there are lots of table, inserting to the main table make a lot of overhead).
Thank you for your consideration.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:5
- Comments:17 (4 by maintainers)
https://gist.github.com/linhx/e5cce0b941546557d7e1625923b7f0c2 I created a few lines code that allow to dynamic table name. It seems to work well but I’m not sure if there is anything wrong. Hope the authors could verify it.
Update 2022-05-24: Typeorm has been updated a lot. the code is different now. Only use this code with Typeorm ver 0.2.30
Update 2022-05-26: I have created a commit for adding new Entity class at runtime, but it changed the code order. I’m not sure about the effect. I’m wating for the answer on their Slack. While waiting, I have created a repo for the tricky code for ver 0.3.6: https://github.com/linhx/typeorm-dynamic-table-name-sample. But actually I don’t like this, It is too risky. TypeORM can be updated anytime.
I have not tried it before. But maybe using
EntitySchema
could resolve your issue. https://typeorm.io/#/separating-entity-definition