sea-query icon indicating copy to clipboard operation
sea-query copied to clipboard

Helper methods on `Expr` & `SimpleExpr` for performing numeric operations

Open billy1624 opened this issue 3 years ago • 1 comments

Motivation

Currently, we don't have a intuitive way to construct numeric operations for a SimpleExpr pair.

E.g. table.col_1 + table.col_2, table.col_1 * table.col_2, table.col_1 / table.col_2... etc.

We have SimpleExpr::add and SimpleExpr::sub but others common operator are still missing.

Proposed Solutions

  1. Support all common operators to SimpleExpr, e.g. mul, div, mod
  2. Support all common operators to Expr where the parameter is Into<SimpleExpr>, to avoid name conflict with existing methods like add for example, maybe we can name it with a _expr suffix? E.x. add_expr

A Workaround for People Who Needs This Right Now

assert_eq!(
    Query::select()
        .columns([Char::Character, Char::SizeW, Char::SizeH])
        .expr_as(
            SimpleExpr::Binary(
                Box::new(Expr::col(Char::SizeW).into()),
                BinOper::Mul,
                Box::new(Expr::col(Char::SizeH).into()),
            ),
            Alias::new("area")
        )
        .from(Char::Table)
        .limit(10)
        .offset(100)
        .to_string(MysqlQueryBuilder),
    "SELECT `character`, `size_w`, `size_h`, `size_w` * `size_h` AS `area` FROM `character` LIMIT 10 OFFSET 100"
);

billy1624 avatar Sep 14 '22 03:09 billy1624

Actually we can revisit the idea of operator overloading so we can literally + two expressions together. I forgot why it was futile the last time I tried.

tyt2y3 avatar Sep 14 '22 09:09 tyt2y3

Have done by: https://github.com/SeaQL/sea-query/pull/510

ikrivosheev avatar Nov 15 '22 18:11 ikrivosheev