buildSelectStatement method

JoinedSelectStatement<$Table, $Dataclass> buildSelectStatement({
  1. Iterable<Expression<Object>>? targetColumns,
})

Builds a select statement with the given target columns, or all columns if none are provided

Implementation

JoinedSelectStatement<$Table, $Dataclass> buildSelectStatement({
  Iterable<Expression>? targetColumns,
}) {
  final joins = joinBuilders.map((e) => e.buildJoin()).toList();

  JoinedSelectStatement<$Table, $Dataclass> joinedStatement;
  // If we are only selecting specific columns, we can use a selectOnly statement
  if (targetColumns != null) {
    joinedStatement = (db.selectOnly(
      _tableAsTableInfo,
      distinct: distinct ?? false,
    )..addColumns(targetColumns));
    // Add the joins to the statement
    joinedStatement =
        joinedStatement.join(joins)
            as JoinedSelectStatement<$Table, $Dataclass>;
  } else {
    joinedStatement =
        db.select(_tableAsTableInfo, distinct: distinct ?? false).join(joins)
            as JoinedSelectStatement<$Table, $Dataclass>;
  }

  // Add any additional columns/expression that were added
  joinedStatement.addColumns(addedColumns);

  // If there are any added column, then group by primary key and apply filter to it
  // other wise add the filter to the select directly
  if (addedColumns.isNotEmpty) {
    // ignore: invalid_use_of_visible_for_overriding_member
    joinedStatement.groupBy(table.primaryKey!, having: filter);
  } else if (filter != null) {
    joinedStatement.where(filter!);
  }

  // Apply orderings and limits
  joinedStatement.orderBy(
    orderingBuilders.map((e) => e.buildTerm()).toList(),
  );
  if (limit != null) {
    joinedStatement.limit(limit!, offset: offset);
  }

  return joinedStatement;
}