Exemplo n.º 1
0
        public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior)
        {
            Reset();

            try
            {
                while (true)
                {
                    var payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false);

                    var firstByte = payload.HeaderByte;
                    if (firstByte == OkPayload.Signature)
                    {
                        var ok = OkPayload.Create(payload.Span, Session.SupportsDeprecateEof, Session.SupportsSessionTrack);
                        RecordsAffected = (RecordsAffected ?? 0) + ok.AffectedRowCount;
                        LastInsertId    = unchecked ((long)ok.LastInsertId);
                        WarningCount    = ok.WarningCount;
                        if (ok.NewSchema is not null)
                        {
                            Connection.Session.DatabaseOverride = ok.NewSchema;
                        }
                        ColumnDefinitions = null;
                        ColumnTypes       = null;
                        State             = (ok.ServerStatus & ServerStatus.MoreResultsExist) == 0
                                                        ? ResultSetState.NoMoreData
                                                        : ResultSetState.HasMoreData;
                        if (State == ResultSetState.NoMoreData)
                        {
                            break;
                        }
                    }
                    else if (firstByte == LocalInfilePayload.Signature)
                    {
                        try
                        {
                            if (!Connection.AllowLoadLocalInfile)
                            {
                                throw new NotSupportedException("To use LOAD DATA LOCAL INFILE, set AllowLoadLocalInfile=true in the connection string. See https://fl.vu/mysql-load-data");
                            }
                            var localInfile     = LocalInfilePayload.Create(payload.Span);
                            var hasSourcePrefix = localInfile.FileName.StartsWith(MySqlBulkLoader.SourcePrefix, StringComparison.Ordinal);
                            if (!IsHostVerified(Connection) && !hasSourcePrefix)
                            {
                                throw new NotSupportedException("Use SourceStream or SslMode >= VerifyCA for LOAD DATA LOCAL INFILE. See https://fl.vu/mysql-load-data");
                            }

                            var source = hasSourcePrefix ?
                                         MySqlBulkLoader.GetAndRemoveSource(localInfile.FileName) :
                                         File.OpenRead(localInfile.FileName);
                            switch (source)
                            {
                            case Stream stream:
                                var buffer = ArrayPool <byte> .Shared.Rent(1048576);

                                try
                                {
                                    int byteCount;
                                    while ((byteCount = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
                                    {
                                        payload = new(new ArraySegment <byte>(buffer, 0, byteCount));
                                        await Session.SendReplyAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false);
                                    }
                                }
                                finally
                                {
                                    ArrayPool <byte> .Shared.Return(buffer);

                                    stream.Dispose();
                                }
                                break;

                            case MySqlBulkCopy bulkCopy:
                                await bulkCopy.SendDataReaderAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false);

                                break;

                            default:
                                throw new InvalidOperationException("Unsupported Source type: {0}".FormatInvariant(source.GetType().Name));
                            }
                        }
                        catch (Exception ex)
                        {
                            // store the exception, to be thrown after reading the response packet from the server
                            ReadResultSetHeaderException = new("Error during LOAD DATA LOCAL INFILE", ex);
                        }

                        await Session.SendReplyAsync(EmptyPayload.Instance, ioBehavior, CancellationToken.None).ConfigureAwait(false);
                    }
                    else
                    {
                        int ReadColumnCount(ReadOnlySpan <byte> span)
                        {
                            var reader       = new ByteArrayReader(span);
                            var columnCount_ = (int)reader.ReadLengthEncodedInteger();

                            if (reader.BytesRemaining != 0)
                            {
                                throw new MySqlException("Unexpected data at end of column_count packet; see https://github.com/mysql-net/MySqlConnector/issues/324");
                            }
                            return(columnCount_);
                        }
                        var columnCount = ReadColumnCount(payload.Span);

                        // reserve adequate space to hold a copy of all column definitions (but note that this can be resized below if we guess too small)
                        Utility.Resize(ref m_columnDefinitionPayloads, columnCount * 96);

                        ColumnDefinitions = new ColumnDefinitionPayload[columnCount];
                        ColumnTypes       = new MySqlDbType[columnCount];

                        for (var column = 0; column < ColumnDefinitions.Length; column++)
                        {
                            payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false);

                            var payloadLength = payload.Span.Length;

                            // 'Session.ReceiveReplyAsync' reuses a shared buffer; make a copy so that the column definitions can always be safely read at any future point
                            if (m_columnDefinitionPayloadUsedBytes + payloadLength > m_columnDefinitionPayloads.Count)
                            {
                                Utility.Resize(ref m_columnDefinitionPayloads, m_columnDefinitionPayloadUsedBytes + payloadLength);
                            }
                            payload.Span.CopyTo(m_columnDefinitionPayloads.Array.AsSpan().Slice(m_columnDefinitionPayloadUsedBytes));

                            var columnDefinition = ColumnDefinitionPayload.Create(new ResizableArraySegment <byte>(m_columnDefinitionPayloads, m_columnDefinitionPayloadUsedBytes, payloadLength));
                            ColumnDefinitions[column]           = columnDefinition;
                            ColumnTypes[column]                 = TypeMapper.ConvertToMySqlDbType(columnDefinition, treatTinyAsBoolean: Connection.TreatTinyAsBoolean, guidFormat: Connection.GuidFormat);
                            m_columnDefinitionPayloadUsedBytes += payloadLength;
                        }

                        if (!Session.SupportsDeprecateEof)
                        {
                            payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false);

                            EofPayload.Create(payload.Span);
                        }

                        if (ColumnDefinitions.Length == (Command?.OutParameters?.Count + 1) && ColumnDefinitions[0].Name == SingleCommandPayloadCreator.OutParameterSentinelColumnName)
                        {
                            ContainsCommandParameters = true;
                        }
                        LastInsertId = -1;
                        WarningCount = 0;
                        State        = ResultSetState.ReadResultSetHeader;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                ReadResultSetHeaderException = ex;
            }
            finally
            {
                BufferState = State;
            }
        }