/// <summary>
        /// Cancels and terminates an ongoing operation. Any data already written will be discarded.
        /// </summary>
        public void Cancel()
        {
            CheckDisposed();

            if (CanWrite)
            {
                _isDisposed = true;
                _writeBuf.EndCopyMode();
                _writeBuf.Clear();
                _connector.SendMessage(new CopyFailMessage());
                try
                {
                    var msg = _connector.ReadMessage();
                    // The CopyFail should immediately trigger an exception from the read above.
                    _connector.Break();
                    throw new NpgsqlException("Expected ErrorResponse when cancelling COPY but got: " + msg.Code);
                }
                catch (PostgresException e)
                {
                    if (e.SqlState == "57014")
                    {
                        return;
                    }
                    throw;
                }
            }
            else
            {
                _connector.CancelRequest();
            }
        }
        /// <summary>
        /// Commits the import operation. The writer is unusable after this operation.
        /// </summary>
        public void Commit()
        {
            CheckReady();

            if (InMiddleOfRow)
            {
                Cancel();
                throw new InvalidOperationException("Binary importer closed in the middle of a row, cancelling import.");
            }

            try
            {
                WriteTrailer();
                _buf.Flush();
                _buf.EndCopyMode();

                _connector.SendMessage(CopyDoneMessage.Instance);
                _connector.ReadExpecting <CommandCompleteMessage>();
                _connector.ReadExpecting <ReadyForQueryMessage>();

                _state = ImporterState.Committed;
            }
            catch
            {
                // An exception here will have already broken the connection etc.
                Cleanup();
                throw;
            }
        }