drift icon indicating copy to clipboard operation
drift copied to clipboard

[Feature Request] Inheritance on moor files

Open JCKodel opened this issue 4 years ago • 0 comments

Let's assume we have two tables:

CREATE TABLE Orders (
  id INT PRIMARY KEY
);

CREATE TABLE Products (
  id INT PRIMARY KEY,
  orderId INT REFERENCES Orders(id)
);

Moor will generate classes for both tables. Now, imagine I want to get all orders and also the quantity of products in each order. Very easy to do:

getAllOrders:
  SELECT
    o.*,
    (SELECT COUNT(*) FROM Products WHERE orderId = o.id) AS productsCount
  FROM Orders;

This will generate a new class called GetGetAllOrdersResult.

If I have this need in other queries, I can generate a single class using as:

getAllOrders as OrdersWithProductsCount:
  SELECT
    o.*,
    (SELECT COUNT(*) FROM Products WHERE orderId = o.id) AS productsCount
  FROM Orders;

The generated class is plain (meaning it doesn't have any methods in it, including .copyWith).

What I'm proposing is something like this:

getAllOrders extends Order as OrdersWithProductsCount:
  SELECT
    o.*,
    (SELECT COUNT(*) FROM Products WHERE orderId = o.id) AS productsCount
  FROM Orders;

Moor generator would then generate a class that inherits Order instead of creating a new class. This inherited class will have the extra(s) property(ies) (int productsCount in this case) and the .copyWith method would be generated copying this property and calling the base class.

Now, I need to implement .copyWith by hand (through extension methods), and there is no guarantee whatsoever that I'm not missing some property in it (since none of the properties are required, intellisense won't give me hints that I miss a copy in the implemented .copyWith method).

And, of course, a simple implementation of .copyWith in the current generated result class would be very usefull as well.

Now, if we just do this:

getAllOrders extends BaseOrder:
  SELECT
    o.*,
  FROM Orders;

This would generate the Order class, as usual, but make it extend BaseOrder class.

This is usefull, for example, if we want to implement helper properties (like this one):

  bool get isLate => DateTime(this.date).difference(DateTime.now()).inDays > 1;

Both behaviors could cover the needs of https://github.com/simolus3/moor/issues/162

JCKodel avatar Jul 20 '20 17:07 JCKodel