///|
priv struct StreamCursor {
  bridge : Bridge
  tx : TransactionState?
  sql : String
  handle : @pg.RowStream
  mut status : CursorStatus
}

///|
priv enum CursorStatus {
  Ready
  Reading
  Draining
  Done
}

///|
async fn Bridge::start_cursor(
  self : Bridge,
  tx : TransactionState?,
  sql : String,
  params : Array[@db.Value],
  scope? : TransactionScope,
) -> StreamCursor raise @db.DbError {
  self.enter(scope?)
  errdefer {
    self.busy = false
  }
  if scope is Some(_) {
    check_scoped_sql(sql)
  }
  let handle = self.open_row_stream(tx, sql, params)
  { bridge: self, tx, sql, handle, status: Ready, }
}

///|
pub impl @db.AsyncDriver for Bridge with fn query_stream(self, sql, params) {
  self.start_cursor(self.transaction, sql, params)
}

///|
/// Consume rows within a transaction callback. Unread rows are drained before
/// the transaction scope resumes, including when the callback raises.
pub async fn[T] TransactionScope::with_stream(
  self : TransactionScope,
  sql : String,
  params : Array[@db.Value],
  f : async (&@db.AsyncCursor) -> T,
) -> T {
  let cursor = self.bridge.start_cursor(
    Some(self.state),
    sql,
    params,
    scope=self,
  )
  let handle : &@db.AsyncCursor = cursor
  let result = {
    errdefer @async.protect_from_cancel(() => handle.close())
    f(handle)
  }
  cursor.finish()
  result
}

///|
fn StreamCursor::release(self : StreamCursor) -> Unit {
  self.status = Done
  self.bridge.busy = false
}

///|
fn StreamCursor::on_stream_error(
  self : StreamCursor,
  error : Error,
) -> @db.DbError {
  // Server errors are delivered after ReadyForQuery. Other stream failures
  // can leave protocol cleanup in flight, so discard the connection.
  if !(error is @pg.ClientError::Database(_)) {
    self.bridge.abort()
  }
  stream_error(self.tx, error)
}

///|
async fn StreamCursor::finish(self : StreamCursor) -> Unit raise @db.DbError {
  match self.status {
    Done => return
    Draining => raise @db.QueryError("cursor close is already in progress")
    Reading => {
      self.bridge.abort()
      self.release()
      raise @db.QueryError("cursor closed during an active read")
    }
    Ready => self.status = Draining
  }
  defer self.release()
  self.bridge.check_open()
  @async.protect_from_cancel(() => {
    self.handle.detach()
    self.handle.finish() |> ignore
  }) catch {
    error => raise self.on_stream_error(error)
  }
  complete_query(self.tx, self.sql)
}

///|
impl @db.AsyncCursor for StreamCursor with fn next(self) {
  match self.status {
    Done | Draining => return None
    Reading => raise @db.QueryError("cursor already has an active read")
    Ready => self.status = Reading
  }
  errdefer {
    if @async.is_being_cancelled() {
      self.bridge.abort()
    }
    self.release()
  }
  self.bridge.check_open()
  let row = self.handle.next() catch {
    error => raise self.on_stream_error(error)
  }
  self.bridge.check_open()
  match row {
    None => {
      complete_query(self.tx, self.sql)
      self.release()
      None
    }
    Some(row) => {
      self.status = Ready
      Some(convert_row(row)) catch {
        error => {
          self.finish() catch {
            _ => ()
          }
          raise map_error(error)
        }
      }
    }
  }
}

///|
impl @db.AsyncCursor for StreamCursor with fn close(self) {
  self.finish() catch {
    _ => ()
  }
}