generateDeleteSQL method

FutureOr<SQL> generateDeleteSQL(
  1. Transaction transaction,
  2. String entityName,
  3. String table,
  4. EntityMatcher matcher, {
  5. Object? parameters,
  6. List? positionalParameters,
  7. Map<String, Object?>? namedParameters,
})

Implementation

FutureOr<SQL> generateDeleteSQL(Transaction transaction, String entityName,
    String table, EntityMatcher matcher,
    {Object? parameters,
    List? positionalParameters,
    Map<String, Object?>? namedParameters}) {
  var retDeleteSQL = _generateSQLFrom(transaction, entityName, table, matcher,
      parameters: parameters,
      positionalParameters: positionalParameters,
      namedParameters: namedParameters,
      sqlBuilder: (String from, EncodingContext context) {
    var tableAlias = context.resolveEntityAlias(table);

    var sql = StringBuffer();
    sql.write('DELETE ');

    if (dialect.acceptsOutputSyntax) {
      sql.write(' OUTPUT DELETED.* ');
    }

    sql.write(from);

    if (dialect.acceptsReturningSyntax) {
      sql.write(' RETURNING "$tableAlias".*');
    }

    return sql.toString();
  });

  if (dialect.acceptsTemporaryTableForReturning &&
      !dialect.acceptsOutputSyntax &&
      !dialect.acceptsReturningSyntax) {
    return retDeleteSQL.resolveMapped((deleteSQL) {
      var conditionSQL = deleteSQL.sqlCondition;

      var tableAlias = deleteSQL.tablesAliases?[table];

      var tmpTable = createTemporaryTableName(table);

      var q = dialect.elementQuote;

      var sqlSelAll = tableAlias != null ? ' $q$tableAlias$q.* ' : '*';
      var sqlAsTableAlias = tableAlias != null ? ' as $q$tableAlias$q ' : '';

      var preSql = SQL(
          'CREATE TEMPORARY TABLE IF NOT EXISTS $q$tmpTable$q AS ('
          ' SELECT $sqlSelAll FROM $q$table$q$sqlAsTableAlias WHERE $conditionSQL '
          ')',
          positionalParameters ?? (parameters is List ? parameters : null),
          namedParameters ??
              (parameters is Map<String, dynamic> ? parameters : null),
          deleteSQL.parametersByPlaceholder,
          mainTable: tmpTable);

      var posSql1 =
          SQL('SELECT * FROM $q$tmpTable$q', [], {}, {}, mainTable: tmpTable);

      var posSql2 =
          SQL('DROP TABLE $q$tmpTable$q', [], {}, {}, mainTable: tmpTable);

      deleteSQL = deleteSQL.ensureNotSharedDummy();

      deleteSQL.preSQL = [preSql];
      deleteSQL.posSQL = [posSql1, posSql2];
      deleteSQL.posSQLReturnIndex = 0;

      return deleteSQL;
    });
  }

  return retDeleteSQL;
}