SqlBuilder.query constructor

SqlBuilder.query(
  1. String table, {
  2. bool? distinct,
  3. List<String>? columns,
  4. String? where,
  5. List<Object?>? whereArgs,
  6. String? groupBy,
  7. String? having,
  8. String? orderBy,
  9. int? limit,
  10. int? offset,
})

Build an SQL query string from the given clauses.

@param distinct true if you want each row to be unique, false otherwise. @param table The table names to compile the query against. @param columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used. @param where A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URL. @param groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped. @param having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used. @param orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. @param limit Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.

Implementation

SqlBuilder.query(String table,
    {bool? distinct,
    List<String>? columns,
    String? where,
    List<Object?>? whereArgs,
    String? groupBy,
    String? having,
    String? orderBy,
    int? limit,
    int? offset}) {
  if (groupBy == null && having != null) {
    throw ArgumentError(
        'HAVING clauses are only permitted when using a groupBy clause');
  }
  checkWhereArgs(whereArgs);

  final query = StringBuffer();

  query.write('SELECT ');
  if (distinct == true) {
    query.write('DISTINCT ');
  }
  if (columns != null && columns.isNotEmpty) {
    _writeColumns(query, columns);
  } else {
    query.write('* ');
  }
  query.write('FROM ');
  query.write(_escapeName(table));
  _writeClause(query, ' WHERE ', where);
  _writeClause(query, ' GROUP BY ', groupBy);
  _writeClause(query, ' HAVING ', having);
  _writeClause(query, ' ORDER BY ', orderBy);
  if (limit != null) {
    _writeClause(query, ' LIMIT ', limit.toString());
  }
  if (offset != null) {
    _writeClause(query, ' OFFSET ', offset.toString());
  }

  sql = query.toString();
  arguments = whereArgs != null ? List<Object?>.from(whereArgs) : null;
}