Inheritance in DAOS #2866
-
Hello everybody. During the modeling of any database, I realized the possibility of using inheritance so that different classes, tables, from the same group, would have the same set of columns. In order to do this I created a mixin. In order to keep the database interaction code modular, I would create a DAO for each table. However, I realized that I would have to repeat the same block of code - with few changes - for each table, in order to share the same set of columns that it inherited from the Auditable mixin, which contains:
All DateTimes. The set of functions they share are to search based on the value equal, less than, greater than, greater than or equal, less than or equal in rows in which the values are active or not. The only element that changes in each of the functions is the table from which the search will be made.Is there any way to create another mixin, an abstract class or something like that so that, through inheritance, this repetition can be eliminated? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Sure. Let's say you had a common mixin defining these columns: mixin WithDates on Table {
DateTimeColumn get createdAt => ...;
// ...
}
class Users extends Table with WithDates {} That allows writing a common DAO for all of them: abstract class BaseDao<D, T extends TableInfo<WithDates, D>> extends DatabaseAccessor {
BaseDao(super.attachedDatabase);
T get table;
Future<D> testQuery() async {
return await (select(table)..where((tbl) => tbl.createdAt.equals(whatever))).getSingle();
}
} A DAO for a particular table would extend that one, e.g. |
Beta Was this translation helpful? Give feedback.
Not at all, the code I've posted was wrong. The first type parameter on
TableInfo
is the source table class that you've added to the database, the second one is the generated row class. So it should beBaseDao<D, T extends TableInfo<WithDates, D>>
and then theUsersDao
would extendBaseoDao<User, $UsersTable>
.