Ejemplo n.º 1
0
        bool WriteBitArray(BitArray bitArray)
        {
            if (_pos < 0)
            {
                // Initial bitlength byte
                if (_writeBuf.WriteSpaceLeft < 4)
                {
                    return(false);
                }
                _writeBuf.WriteInt32(bitArray.Length);
                _pos = 0;
            }
            var byteLen = (bitArray.Length + 7) / 8;
            var endPos  = _pos + Math.Min(byteLen - _pos, _writeBuf.WriteSpaceLeft);

            for (; _pos < endPos; _pos++)
            {
                var bitPos = _pos * 8;
                var b      = 0;
                for (var i = 0; i < Math.Min(8, bitArray.Length - bitPos); i++)
                {
                    b += (bitArray[bitPos + i] ? 1 : 0) << (8 - i - 1);
                }
                _writeBuf.WriteByte((byte)b);
            }

            if (_pos < byteLen)
            {
                return(false);
            }

            _writeBuf = null;
            _value    = null;
            return(true);
        }
Ejemplo n.º 2
0
        internal override void WriteFully(WriteBuffer buf)
        {
            Contract.Requires(BackendProcessId != 0);

            buf.WriteInt32(Length);
            buf.WriteInt32(CancelRequestCode);
            buf.WriteInt32(BackendProcessId);
            buf.WriteInt32(BackendSecretKey);
        }
Ejemplo n.º 3
0
        internal override void WriteFully(WriteBuffer buf)
        {
            Contract.Requires(BackendProcessId != 0);

            buf.WriteInt32(Length);
            buf.WriteInt32(CancelRequestCode);
            buf.WriteInt32(BackendProcessId);
            buf.WriteInt32(BackendSecretKey);
        }
Ejemplo n.º 4
0
        internal override void WriteFully(WriteBuffer buf)
        {
            Debug.Assert(BackendProcessId != 0);

            buf.WriteInt32(Length);
            buf.WriteInt32(CancelRequestCode);
            buf.WriteInt32(BackendProcessId);
            buf.WriteInt32(BackendSecretKey);
        }
Ejemplo n.º 5
0
        bool WriteParameters(WriteBuffer buf, ref DirectBuffer directBuf)
        {
            for (; _paramIndex < InputParameters.Count; _paramIndex++)
            {
                var param = InputParameters[_paramIndex];

                if (!_wroteParamLen)
                {
                    if (param.Value is DBNull)
                    {
                        if (buf.WriteSpaceLeft < 4)
                        {
                            return(false);
                        }
                        buf.WriteInt32(-1);
                        continue;
                    }

                    param.LengthCache?.Rewind();
                }

                var handler = param.Handler;

                var asChunkingWriter = handler as IChunkingTypeHandler;
                if (asChunkingWriter != null)
                {
                    if (!_wroteParamLen)
                    {
                        if (buf.WriteSpaceLeft < 4)
                        {
                            return(false);
                        }
                        buf.WriteInt32(param.ValidateAndGetLength());
                        asChunkingWriter.PrepareWrite(param.Value, buf, param.LengthCache, param);
                        _wroteParamLen = true;
                    }
                    if (!asChunkingWriter.Write(ref directBuf))
                    {
                        return(false);
                    }
                    _wroteParamLen = false;
                    continue;
                }

                var len            = param.ValidateAndGetLength();
                var asSimpleWriter = (ISimpleTypeHandler)handler;
                if (buf.WriteSpaceLeft < len + 4)
                {
                    Contract.Assume(buf.Size >= len + 4);
                    return(false);
                }
                buf.WriteInt32(len);
                asSimpleWriter.Write(param.Value, buf, param);
            }
            return(true);
        }
Ejemplo n.º 6
0
        internal override void WriteFully(WriteBuffer buf)
        {
            Contract.Requires(Portal != null && Portal.All(c => c < 128));

            var portalNameBytes = Portal == "" ? PGUtil.EmptyBuffer : Encoding.ASCII.GetBytes(Portal);
            buf.WriteByte(Code);
            buf.WriteInt32(Length - 1);
            buf.WriteBytesNullTerminated(portalNameBytes);
            buf.WriteInt32(MaxRows);
        }
Ejemplo n.º 7
0
        internal override void WriteFully(WriteBuffer buf)
        {
            Debug.Assert(Portal != null && Portal.All(c => c < 128));

            buf.WriteByte(Code);
            buf.WriteInt32(Length - 1);
            Debug.Assert(Portal == string.Empty);
            buf.WriteByte(0);   // Portal is always an empty string
            buf.WriteInt32(MaxRows);
        }
Ejemplo n.º 8
0
        public override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter)
        {
            if (parameter != null && parameter.ConvertedValue != null)
            {
                value = parameter.ConvertedValue;
            }

            NpgsqlDate date;

            if (value is NpgsqlDate)
            {
                date = (NpgsqlDate)value;
            }
            else if (value is DateTime)
            {
                var dt = (DateTime)value;
                if (_convertInfinityDateTime)
                {
                    if (dt == DateTime.MaxValue)
                    {
                        date = NpgsqlDate.Infinity;
                    }
                    else if (dt == DateTime.MinValue)
                    {
                        date = NpgsqlDate.NegativeInfinity;
                    }
                    else
                    {
                        date = new NpgsqlDate(dt);
                    }
                }
                else
                {
                    date = new NpgsqlDate(dt);
                }
            }
            else
            {
                throw PGUtil.ThrowIfReached();
            }

            if (date == NpgsqlDate.NegativeInfinity)
            {
                buf.WriteInt32(int.MinValue);
            }
            else if (date == NpgsqlDate.Infinity)
            {
                buf.WriteInt32(int.MaxValue);
            }
            else
            {
                buf.WriteInt32(date.DaysSinceEra - 730119);
            }
        }
Ejemplo n.º 9
0
        protected override void Write(object value, WriteBuffer buf, [CanBeNull] NpgsqlParameter parameter)
        {
            if (parameter?.ConvertedValue != null)
            {
                value = parameter.ConvertedValue;
            }

            NpgsqlDate date;

            if (value is NpgsqlDate)
            {
                date = (NpgsqlDate)value;
            }
            else if (value is DateTime)
            {
                var dt = (DateTime)value;
                if (_convertInfinityDateTime)
                {
                    if (dt == DateTime.MaxValue)
                    {
                        date = NpgsqlDate.Infinity;
                    }
                    else if (dt == DateTime.MinValue)
                    {
                        date = NpgsqlDate.NegativeInfinity;
                    }
                    else
                    {
                        date = new NpgsqlDate(dt);
                    }
                }
                else
                {
                    date = new NpgsqlDate(dt);
                }
            }
            else
            {
                throw new InvalidOperationException("Internal Npgsql bug, please report.");
            }

            if (date == NpgsqlDate.NegativeInfinity)
            {
                buf.WriteInt32(int.MinValue);
            }
            else if (date == NpgsqlDate.Infinity)
            {
                buf.WriteInt32(int.MaxValue);
            }
            else
            {
                buf.WriteInt32(date.DaysSinceEra - 730119);
            }
        }
Ejemplo n.º 10
0
        internal override void WriteFully(WriteBuffer buf)
        {
            Contract.Requires(Portal != null && Portal.All(c => c < 128));

            var portalNameBytes = Portal == "" ? PGUtil.EmptyBuffer : Encoding.ASCII.GetBytes(Portal);

            buf.WriteByte(Code);
            buf.WriteInt32(Length - 1);
            buf.WriteBytesNullTerminated(portalNameBytes);
            buf.WriteInt32(MaxRows);
        }
Ejemplo n.º 11
0
        protected override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter = null)
        {
            if (parameter?.ConvertedValue != null)
            {
                value = parameter.ConvertedValue;
            }

            var interval = value as TimeSpan? ?? (NpgsqlTimeSpan)value;

            buf.WriteInt64(interval.Ticks / 10); // TODO: round?
            buf.WriteInt32(interval.Days);
            buf.WriteInt32(interval.Months);
        }
Ejemplo n.º 12
0
        internal override void WriteFully(WriteBuffer buf)
        {
            buf.WriteInt32(_length);
            buf.WriteInt32(ProtocolVersion3);

            foreach (var kv in _parameters)
            {
                buf.WriteBytesNullTerminated(kv.Key);
                buf.WriteBytesNullTerminated(kv.Value);
            }

            buf.WriteByte(0);
        }
Ejemplo n.º 13
0
        internal override void WriteFully(WriteBuffer buf)
        {
            buf.WriteInt32(_length);
            buf.WriteInt32(ProtocolVersion3);

            foreach (var kv in _parameters)
            {
                buf.WriteBytesNullTerminated(kv.Key);
                buf.WriteBytesNullTerminated(kv.Value);
            }

            buf.WriteByte(0);
        }
Ejemplo n.º 14
0
        // TODO: Duplicated from ArrayHandler... Refactor...
        bool WriteSingleElement([CanBeNull] object element, ref DirectBuffer directBuf)
        {
            if (element == null || element is DBNull)
            {
                if (_writeBuf.WriteSpaceLeft < 4)
                {
                    return(false);
                }
                _writeBuf.WriteInt32(-1);
                return(true);
            }

            var asSimpleWriter = ElementHandler as ISimpleTypeHandler;

            if (asSimpleWriter != null)
            {
                var elementLen = asSimpleWriter.ValidateAndGetLength(element, null);
                if (_writeBuf.WriteSpaceLeft < 4 + elementLen)
                {
                    return(false);
                }
                _writeBuf.WriteInt32(elementLen);
                asSimpleWriter.Write(element, _writeBuf, null);
                return(true);
            }

            var asChunkedWriter = ElementHandler as IChunkingTypeHandler;

            if (asChunkedWriter != null)
            {
                if (!_wroteElementLen)
                {
                    if (_writeBuf.WriteSpaceLeft < 4)
                    {
                        return(false);
                    }
                    _writeBuf.WriteInt32(asChunkedWriter.ValidateAndGetLength(element, ref _lengthCache, null));
                    asChunkedWriter.PrepareWrite(element, _writeBuf, _lengthCache, null);
                    _wroteElementLen = true;
                }
                if (!asChunkedWriter.Write(ref directBuf))
                {
                    return(false);
                }
                _wroteElementLen = false;
                return(true);
            }

            throw PGUtil.ThrowIfReached();
        }
Ejemplo n.º 15
0
        public override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter)
        {
            if (parameter != null && parameter.ConvertedValue != null)
            {
                value = parameter.ConvertedValue;
            }

            var interval = (value is TimeSpan)
                ? ((NpgsqlTimeSpan)(TimeSpan)value)
                : ((NpgsqlTimeSpan)value);

            buf.WriteInt64(interval.Ticks / 10); // TODO: round?
            buf.WriteInt32(interval.Days);
            buf.WriteInt32(interval.Months);
        }
Ejemplo n.º 16
0
        internal override bool Write(WriteBuffer buf)
        {
            if (_charPos == -1)
            {
                // Start new query
                if (buf.WriteSpaceLeft < 1 + 4)
                    return false;
                _charPos = 0;
                var queryByteLen = _encoding.GetByteCount(_query);
                _queryChars = _query.ToCharArray();
                buf.WriteByte(Code);
                buf.WriteInt32(4 +            // Message length (including self excluding code)
                               queryByteLen + // Query byte length
                               1);            // Null terminator
            }

            if (_charPos < _queryChars.Length)
            {
                int charsUsed;
                bool completed;
                buf.WriteStringChunked(_queryChars, _charPos, _queryChars.Length - _charPos, true,
                                       out charsUsed, out completed);
                _charPos += charsUsed;
                if (!completed)
                    return false;
            }

            if (buf.WriteSpaceLeft < 1)
                return false;
            buf.WriteByte(0);

            _charPos = -1;
            return true;
        }
Ejemplo n.º 17
0
        protected override async Task Write(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter,
                                            bool async, CancellationToken cancellationToken)
        {
            Debug.Assert(_members != null);

            var composite = (T)value;

            if (buf.WriteSpaceLeft < 4)
            {
                await buf.Flush(async, cancellationToken);
            }
            buf.WriteInt32(_members.Count);

            foreach (var fieldDescriptor in _members)
            {
                var fieldHandler = fieldDescriptor.Handler;
                var fieldValue   = fieldDescriptor.GetValue(composite);

                if (buf.WriteSpaceLeft < 4)
                {
                    await buf.Flush(async, cancellationToken);
                }

                buf.WriteUInt32(fieldDescriptor.OID);
                await fieldHandler.WriteWithLength(fieldValue, buf, lengthCache, null, async, cancellationToken);
            }
        }
Ejemplo n.º 18
0
        internal override bool Write(WriteBuffer buf)
        {
            if (_charPos == -1)
            {
                // Start new query
                if (buf.WriteSpaceLeft < 1 + 4)
                    return false;
                _charPos = 0;
                var queryByteLen = PGUtil.UTF8Encoding.GetByteCount(_query);
                _queryChars = _query.ToCharArray();
                buf.WriteByte(Code);
                buf.WriteInt32(4 +            // Message length (including self excluding code)
                               queryByteLen + // Query byte length
                               1);            // Null terminator
            }

            if (_charPos < _queryChars.Length)
            {
                int charsUsed;
                bool completed;
                buf.WriteStringChunked(_queryChars, _charPos, _queryChars.Length - _charPos, true,
                                       out charsUsed, out completed);
                _charPos += charsUsed;
                if (!completed)
                    return false;
            }

            if (buf.WriteSpaceLeft < 1)
                return false;
            buf.WriteByte(0);

            _charPos = -1;
            return true;
        }
Ejemplo n.º 19
0
        public override bool Write(ref DirectBuffer directBuf)
        {
            if (_lexemePos == -1)
            {
                if (_writeBuf.WriteSpaceLeft < 4)
                {
                    return(false);
                }
                _writeBuf.WriteInt32(_value.Count);
                _lexemePos = 0;
            }

            for (; _lexemePos < _value.Count; _lexemePos++)
            {
                if (_writeBuf.WriteSpaceLeft < MaxSingleLexemeBytes)
                {
                    return(false);
                }

                _writeBuf.WriteString(_value[_lexemePos].Text);
                _writeBuf.WriteByte(0);
                _writeBuf.WriteInt16(_value[_lexemePos].Count);
                for (var i = 0; i < _value[_lexemePos].Count; i++)
                {
                    _writeBuf.WriteInt16(_value[_lexemePos][i]._val);
                }
            }

            return(true);
        }
Ejemplo n.º 20
0
        protected override async Task Write(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter,
                                            bool async, CancellationToken cancellationToken)
        {
            var vector = (NpgsqlTsVector)value;

            if (buf.WriteSpaceLeft < 4)
            {
                await buf.Flush(async, cancellationToken);
            }
            buf.WriteInt32(vector.Count);

            foreach (var lexeme in vector)
            {
                if (buf.WriteSpaceLeft < MaxSingleLexemeBytes)
                {
                    await buf.Flush(async, cancellationToken);
                }

                buf.WriteString(lexeme.Text);
                buf.WriteByte(0);
                buf.WriteInt16(lexeme.Count);
                for (var i = 0; i < lexeme.Count; i++)
                {
                    buf.WriteInt16(lexeme[i].Value);
                }
            }
        }
Ejemplo n.º 21
0
    internal Task WriteExecute(int maxRows, bool async, CancellationToken cancellationToken = default)
    {
        // Note: non-empty portal currently not supported

        const int len = sizeof(byte) +       // Message code
                        sizeof(int) +        // Length
                        sizeof(byte) +       // Null-terminated portal name (always empty for now)
                        sizeof(int);         // Max number of rows

        if (WriteBuffer.WriteSpaceLeft < len)
        {
            return(FlushAndWrite(maxRows, async, cancellationToken));
        }

        Write(maxRows);
        return(Task.CompletedTask);

        async Task FlushAndWrite(int maxRows, bool async, CancellationToken cancellationToken)
        {
            await Flush(async, cancellationToken);

            Debug.Assert(10 <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length 10 which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
            Write(maxRows);
        }

        void Write(int maxRows)
        {
            WriteBuffer.WriteByte(FrontendMessageCode.Execute);
            WriteBuffer.WriteInt32(len - 1);
            WriteBuffer.WriteByte(0);   // Portal is always empty for now
            WriteBuffer.WriteInt32(maxRows);
        }
    }
Ejemplo n.º 22
0
        public override bool Write(ref DirectBuffer directBuf)
        {
            if (_index == -1)
            {
                if (_writeBuf.WriteSpaceLeft < 4)
                {
                    return(false);
                }
                _writeBuf.WriteInt32(_value.Count);
                _index = 0;
            }

            for (; _index < _value.Count; _index++)
            {
                if (_writeBuf.WriteSpaceLeft < 16)
                {
                    return(false);
                }
                var p = _value[_index];
                _writeBuf.WriteDouble(p.X);
                _writeBuf.WriteDouble(p.Y);
            }
            _writeBuf = null;
            _value    = default(NpgsqlPolygon);
            return(true);
        }
Ejemplo n.º 23
0
        async Task WriteBitArray(BitArray bitArray, WriteBuffer buf, bool async, CancellationToken cancellationToken)
        {
            // Initial bitlength byte
            if (buf.WriteSpaceLeft < 4)
            {
                await buf.Flush(async, cancellationToken);
            }
            buf.WriteInt32(bitArray.Length);

            var byteLen = (bitArray.Length + 7) / 8;
            var pos     = 0;

            while (true)
            {
                var endPos = pos + Math.Min(byteLen - pos, buf.WriteSpaceLeft);
                for (; pos < endPos; pos++)
                {
                    var bitPos = pos * 8;
                    var b      = 0;
                    for (var i = 0; i < Math.Min(8, bitArray.Length - bitPos); i++)
                    {
                        b += (bitArray[bitPos + i] ? 1 : 0) << (8 - i - 1);
                    }
                    buf.WriteByte((byte)b);
                }

                if (pos == byteLen)
                {
                    return;
                }
                await buf.Flush(async, cancellationToken);
            }
        }
Ejemplo n.º 24
0
    internal Task WriteClose(StatementOrPortal type, string name, bool async, CancellationToken cancellationToken = default)
    {
        var len = sizeof(byte) +               // Message code
                  sizeof(int) +                // Length
                  sizeof(byte) +               // Statement or portal
                  name.Length + sizeof(byte);  // Statement or portal name plus null terminator

        if (WriteBuffer.WriteSpaceLeft < 10)
        {
            return(FlushAndWrite(len, type, name, async, cancellationToken));
        }

        Write(len, type, name);
        return(Task.CompletedTask);

        async Task FlushAndWrite(int len, StatementOrPortal type, string name, bool async, CancellationToken cancellationToken)
        {
            await Flush(async, cancellationToken);

            Debug.Assert(len <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length {len} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
            Write(len, type, name);
        }

        void Write(int len, StatementOrPortal type, string name)
        {
            WriteBuffer.WriteByte(FrontendMessageCode.Close);
            WriteBuffer.WriteInt32(len - 1);
            WriteBuffer.WriteByte((byte)type);
            WriteBuffer.WriteNullTerminatedString(name);
        }
    }
Ejemplo n.º 25
0
    internal async Task WriteSASLInitialResponse(string mechanism, byte[] initialResponse, bool async, CancellationToken cancellationToken = default)
    {
        var len = sizeof(byte) +                                                // Message code
                  sizeof(int) +                                                 // Length
                  PGUtil.UTF8Encoding.GetByteCount(mechanism) + sizeof(byte) +  // Mechanism plus null terminator
                  sizeof(int) +                                                 // Initial response length
                  (initialResponse?.Length ?? 0);                               // Initial response payload

        if (WriteBuffer.WriteSpaceLeft < len)
        {
            await WriteBuffer.Flush(async, cancellationToken);
        }

        WriteBuffer.WriteByte(FrontendMessageCode.Password);
        WriteBuffer.WriteInt32(len - 1);

        WriteBuffer.WriteString(mechanism);
        WriteBuffer.WriteByte(0);   // null terminator
        if (initialResponse == null)
        {
            WriteBuffer.WriteInt32(-1);
        }
        else
        {
            WriteBuffer.WriteInt32(initialResponse.Length);
            WriteBuffer.WriteBytes(initialResponse);
        }
    }
Ejemplo n.º 26
0
    internal void WriteStartup(Dictionary <string, string> parameters)
    {
        const int protocolVersion3 = 3 << 16; // 196608

        var len = sizeof(int) +               // Length
                  sizeof(int) +               // Protocol version
                  sizeof(byte);               // Trailing zero byte

        foreach (var kvp in parameters)
        {
            len += PGUtil.UTF8Encoding.GetByteCount(kvp.Key) + 1 +
                   PGUtil.UTF8Encoding.GetByteCount(kvp.Value) + 1;
        }

        // Should really never happen, just in case
        if (len > WriteBuffer.Size)
        {
            throw new Exception("Startup message bigger than buffer");
        }

        WriteBuffer.WriteInt32(len);
        WriteBuffer.WriteInt32(protocolVersion3);

        foreach (var kv in parameters)
        {
            WriteBuffer.WriteString(kv.Key);
            WriteBuffer.WriteByte(0);
            WriteBuffer.WriteString(kv.Value);
            WriteBuffer.WriteByte(0);
        }

        WriteBuffer.WriteByte(0);
    }
Ejemplo n.º 27
0
    internal Task WriteSync(bool async, CancellationToken cancellationToken = default)
    {
        const int len = sizeof(byte) +  // Message code
                        sizeof(int);    // Length

        if (WriteBuffer.WriteSpaceLeft < len)
        {
            return(FlushAndWrite(async, cancellationToken));
        }

        Write();
        return(Task.CompletedTask);

        async Task FlushAndWrite(bool async, CancellationToken cancellationToken)
        {
            await Flush(async, cancellationToken);

            Debug.Assert(len <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length {len} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
            Write();
        }

        void Write()
        {
            WriteBuffer.WriteByte(FrontendMessageCode.Sync);
            WriteBuffer.WriteInt32(len - 1);
        }
    }
Ejemplo n.º 28
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteByte(Code);
     buf.WriteInt32(Length - 1);
     // Error message not supported for now
     Debug.Assert(_errorMessage == null);
     buf.WriteByte(0);
 }
Ejemplo n.º 29
0
 protected override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter = null)
 {
     if (parameter?.ConvertedValue != null)
     {
         value = parameter.ConvertedValue;
     }
     buf.WriteInt32((int)(uint)value);
 }
Ejemplo n.º 30
0
        async Task WriteBitVector32(BitVector32 bitVector, WriteBuffer buf, bool async, CancellationToken cancellationToken)
        {
            if (buf.WriteSpaceLeft < 8)
            {
                await buf.Flush(async, cancellationToken);
            }

            if (bitVector.Data == 0)
            {
                buf.WriteInt32(0);
            }
            else
            {
                buf.WriteInt32(32);
                buf.WriteInt32(bitVector.Data);
            }
        }
Ejemplo n.º 31
0
        internal override void WriteFully(WriteBuffer buf)
        {
            buf.WriteByte(Code);
            buf.WriteInt32(Length - 1);

            buf.WriteString(_mechanism);
            buf.WriteByte(0);   // null terminator
            if (_initialResponse == null)
            {
                buf.WriteInt32(-1);
            }
            else
            {
                buf.WriteInt32(_initialResponse.Length);
                buf.WriteBytes(_initialResponse);
            }
        }
Ejemplo n.º 32
0
        protected override async Task Write(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter,
                                            bool async, CancellationToken cancellationToken)
        {
            var query     = (NpgsqlTsQuery)value;
            var numTokens = GetTokenCount(query);

            if (buf.WriteSpaceLeft < 4)
            {
                await buf.Flush(async, cancellationToken);
            }
            buf.WriteInt32(numTokens);

            if (numTokens == 0)
            {
                return;
            }

            _stack.Push(query);

            while (_stack.Count > 0)
            {
                if (buf.WriteSpaceLeft < 2)
                {
                    await buf.Flush(async, cancellationToken);
                }

                if (_stack.Peek().Kind == NpgsqlTsQuery.NodeKind.Lexeme && buf.WriteSpaceLeft < MaxSingleTokenBytes)
                {
                    await buf.Flush(async, cancellationToken);
                }

                var node = _stack.Pop();
                buf.WriteByte(node.Kind == NpgsqlTsQuery.NodeKind.Lexeme ? (byte)1 : (byte)2);
                if (node.Kind != NpgsqlTsQuery.NodeKind.Lexeme)
                {
                    buf.WriteByte((byte)node.Kind);
                    if (node.Kind == NpgsqlTsQuery.NodeKind.Not)
                    {
                        _stack.Push(((NpgsqlTsQueryNot)node).Child);
                    }
                    else
                    {
                        _stack.Push(((NpgsqlTsQueryBinOp)node).Right);
                        _stack.Push(((NpgsqlTsQueryBinOp)node).Left);
                    }
                }
                else
                {
                    var lexemeNode = (NpgsqlTsQueryLexeme)node;
                    buf.WriteByte((byte)lexemeNode.Weights);
                    buf.WriteByte(lexemeNode.IsPrefixSearch ? (byte)1 : (byte)0);
                    buf.WriteString(lexemeNode.Text);
                    buf.WriteByte(0);
                }
            }

            _stack.Clear();
        }
Ejemplo n.º 33
0
        protected override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter = null)
        {
            if (value is DateTimeOffset)
            {
                var dto = (DateTimeOffset)value;
                buf.WriteInt64(dto.TimeOfDay.Ticks / 10);
                buf.WriteInt32(-(int)(dto.Offset.Ticks / TimeSpan.TicksPerSecond));
                return;
            }

            if (value is DateTime)
            {
                var dt = (DateTime)value;

                buf.WriteInt64(dt.TimeOfDay.Ticks / 10);

                switch (dt.Kind)
                {
                case DateTimeKind.Utc:
                    buf.WriteInt32(0);
                    break;

                case DateTimeKind.Unspecified:
                // Treat as local...
                case DateTimeKind.Local:
                    buf.WriteInt32(-(int)(TimeZoneInfo.Local.BaseUtcOffset.Ticks / TimeSpan.TicksPerSecond));
                    break;

                default:
                    throw new InvalidOperationException($"Internal Npgsql bug: unexpected value {dt.Kind} of enum {nameof(DateTimeKind)}. Please file a bug.");
                }

                return;
            }

            if (value is TimeSpan)
            {
                var ts = (TimeSpan)value;
                buf.WriteInt64(ts.Ticks / 10);
                buf.WriteInt32(-(int)(TimeZoneInfo.Local.BaseUtcOffset.Ticks / TimeSpan.TicksPerSecond));
                return;
            }

            throw new InvalidOperationException("Internal Npgsql bug, please report.");
        }
Ejemplo n.º 34
0
        public override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter)
        {
            if (value is DateTimeOffset)
            {
                var dto = (DateTimeOffset)value;
                buf.WriteInt64(dto.TimeOfDay.Ticks / 10);
                buf.WriteInt32(-(int)(dto.Offset.Ticks / TimeSpan.TicksPerSecond));
                return;
            }

            if (value is DateTime)
            {
                var dt = (DateTime)value;

                buf.WriteInt64(dt.TimeOfDay.Ticks / 10);

                switch (dt.Kind)
                {
                case DateTimeKind.Utc:
                    buf.WriteInt32(0);
                    break;

                case DateTimeKind.Unspecified:
                // Treat as local...
                case DateTimeKind.Local:
                    buf.WriteInt32(-(int)(TimeZoneInfo.Local.BaseUtcOffset.Ticks / TimeSpan.TicksPerSecond));
                    break;

                default:
                    throw PGUtil.ThrowIfReached();
                }

                return;
            }

            if (value is TimeSpan)
            {
                var ts = (TimeSpan)value;
                buf.WriteInt64(ts.Ticks / 10);
                buf.WriteInt32(-(int)(TimeZoneInfo.Local.BaseUtcOffset.Ticks / TimeSpan.TicksPerSecond));
                return;
            }

            throw PGUtil.ThrowIfReached();
        }
Ejemplo n.º 35
0
        internal override void WriteFully(WriteBuffer buf)
        {
            Contract.Requires(Name != null && Name.All(c => c < 128));

            buf.WriteByte(Code);
            buf.WriteInt32(Length - 1);
            buf.WriteByte((byte)StatementOrPortal);
            buf.WriteBytesNullTerminated(Encoding.ASCII.GetBytes(Name));
        }
Ejemplo n.º 36
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteByte(Code);
     buf.WriteInt32(Length - 1);
     if (_errorMessageLen == 0)
     {
         buf.WriteByte(0);
     }
     else
     {
         buf.WriteBytesNullTerminated(PGUtil.UTF8Encoding.GetBytes(_errorMessage));
     }
 }
Ejemplo n.º 37
0
        bool WriteParameters(WriteBuffer buf, ref DirectBuffer directBuf)
        {
            for (; _paramIndex < InputParameters.Count; _paramIndex++)
            {
                var param = InputParameters[_paramIndex];

                if (!_wroteParamLen)
                {
                    if (param.Value is DBNull)
                    {
                        if (buf.WriteSpaceLeft < 4) { return false; }
                        buf.WriteInt32(-1);
                        continue;
                    }

                    param.LengthCache?.Rewind();
                }

                var handler = param.Handler;

                var asChunkingWriter = handler as IChunkingTypeHandler;
                if (asChunkingWriter != null)
                {
                    if (!_wroteParamLen)
                    {
                        if (buf.WriteSpaceLeft < 4) { return false; }
                        buf.WriteInt32(param.ValidateAndGetLength());
                        asChunkingWriter.PrepareWrite(param.Value, buf, param.LengthCache, param);
                        _wroteParamLen = true;
                    }
                    if (!asChunkingWriter.Write(ref directBuf)) {
                        return false;
                    }
                    _wroteParamLen = false;
                    continue;
                }

                var len = param.ValidateAndGetLength();
                var asSimpleWriter = (ISimpleTypeHandler)handler;
                if (buf.WriteSpaceLeft < len + 4)
                {
                    Contract.Assume(buf.Size >= len + 4);
                    return false;
                }
                buf.WriteInt32(len);
                asSimpleWriter.Write(param.Value, buf, param);
            }
            return true;
        }
Ejemplo n.º 38
0
        internal bool Write(WriteBuffer buf, ref DirectBuffer directBuf)
        {
            Contract.Requires(Statement != null && Statement.All(c => c < 128));
            Contract.Requires(Portal != null && Portal.All(c => c < 128));

            switch (_state)
            {
                case State.Header:
                    var formatCodesSum = InputParameters.Select(p => p.FormatCode).Sum(c => (int)c);
                    _formatCodeListLength = formatCodesSum == 0 ? 0 : formatCodesSum == InputParameters.Count ? 1 : InputParameters.Count;
                    var headerLength =
                        1 +                        // Message code
                        4 +                        // Message length
                        Portal.Length + 1 +
                        Statement.Length + 1 +
                        2;                         // Number of parameter format codes that follow

                    if (buf.WriteSpaceLeft < headerLength)
                    {
                        Contract.Assume(buf.Size >= headerLength, "Buffer too small for Bind header");
                        return false;
                    }

                    foreach (var c in InputParameters.Select(p => p.LengthCache).Where(c => c != null))
                        c.Rewind();
                    var messageLength = headerLength +
                        2 * _formatCodeListLength + // List of format codes
                        2 +                         // Number of parameters
                        4 * InputParameters.Count +                                     // Parameter lengths
                        InputParameters.Select(p => p.ValidateAndGetLength()).Sum() +   // Parameter values
                        2 +                                                             // Number of result format codes
                        2 * (UnknownResultTypeList?.Length ?? 1);                       // Result format codes

                    buf.WriteByte(Code);
                    buf.WriteInt32(messageLength-1);
                    buf.WriteBytesNullTerminated(Encoding.ASCII.GetBytes(Portal));
                    buf.WriteBytesNullTerminated(Encoding.ASCII.GetBytes(Statement));
                    buf.WriteInt16(_formatCodeListLength);
                    _paramIndex = 0;

                    _state = State.ParameterFormatCodes;
                    goto case State.ParameterFormatCodes;

                case State.ParameterFormatCodes:
                    // 0 length implicitly means all-text, 1 means all-binary, >1 means mix-and-match
                    if (_formatCodeListLength == 1)
                    {
                        if (buf.WriteSpaceLeft < 2)
                            return false;
                        buf.WriteInt16((short)FormatCode.Binary);
                    }
                    else if (_formatCodeListLength > 1)
                        for (; _paramIndex < InputParameters.Count; _paramIndex++)
                        {
                            if (buf.WriteSpaceLeft < 2)
                                return false;
                            buf.WriteInt16((short)InputParameters[_paramIndex].FormatCode);
                        }
                    _state = State.ParameterCount;
                    goto case State.ParameterCount;

                case State.ParameterCount:
                    if (buf.WriteSpaceLeft < 2)
                        return false;

                    buf.WriteInt16(InputParameters.Count);
                    _paramIndex = 0;

                    _state = State.ParameterValues;
                    goto case State.ParameterValues;

                case State.ParameterValues:
                    if (!WriteParameters(buf, ref directBuf))
                        return false;
                    _state = State.ResultFormatCodes;
                    goto case State.ResultFormatCodes;

                case State.ResultFormatCodes:
                    if (UnknownResultTypeList != null)
                    {
                        if (buf.WriteSpaceLeft < 2 + UnknownResultTypeList.Length * 2)
                            return false;
                        buf.WriteInt16(UnknownResultTypeList.Length);
                        foreach (var t in UnknownResultTypeList)
                            buf.WriteInt16(t ? 0 : 1);
                    }
                    else
                    {
                        if (buf.WriteSpaceLeft < 4)
                            return false;
                        buf.WriteInt16(1);
                        buf.WriteInt16(AllResultTypesAreUnknown ? 0 : 1);
                    }

                    _state = State.Done;
                    return true;

                default:
                    throw PGUtil.ThrowIfReached();
            }
        }
Ejemplo n.º 39
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteByte(Code);
     buf.WriteInt32(4);
 }
Ejemplo n.º 40
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteByte((byte)BackendMessageCode.CopyDone);
     buf.WriteInt32(4);
 }
Ejemplo n.º 41
0
        internal override bool Write(WriteBuffer buf)
        {
            Contract.Requires(Statement != null);

            switch (_state)
            {
                case State.WroteNothing:
                    _statementNameBytes = Statement.Length == 0 ? PGUtil.EmptyBuffer : _encoding.GetBytes(Statement);
                    _queryLen = _encoding.GetByteCount(Query);
                    if (buf.WriteSpaceLeft < 1 + 4 + _statementNameBytes.Length + 1) {
                        return false;
                    }

                    var messageLength =
                        1 +                         // Message code
                        4 +                         // Length
                        _statementNameBytes.Length +
                        1 +                         // Null terminator
                        _queryLen +
                        1 +                         // Null terminator
                        2 +                         // Number of parameters
                        ParameterTypeOIDs.Count * 4;

                    buf.WriteByte(Code);
                    buf.WriteInt32(messageLength - 1);
                    buf.WriteBytesNullTerminated(_statementNameBytes);
                    goto case State.WroteHeader;

                case State.WroteHeader:
                    _state = State.WroteHeader;

                    if (_queryLen <= buf.WriteSpaceLeft) {
                        buf.WriteString(Query);
                        goto case State.WroteQuery;
                    }

                    if (_queryLen <= buf.Size) {
                        // String can fit entirely in an empty buffer. Flush and retry rather than
                        // going into the partial writing flow below (which requires ToCharArray())
                        return false;
                    }

                    _queryChars = Query.ToCharArray();
                    _charPos = 0;
                    goto case State.WritingQuery;

                case State.WritingQuery:
                    _state = State.WritingQuery;
                    int charsUsed;
                    bool completed;
                    buf.WriteStringChunked(_queryChars, _charPos, _queryChars.Length - _charPos, true,
                                           out charsUsed, out completed);
                    if (!completed)
                    {
                        _charPos += charsUsed;
                        return false;
                    }
                    goto case State.WroteQuery;

                case State.WroteQuery:
                    _state = State.WroteQuery;
                    if (buf.WriteSpaceLeft < 1 + 2) {
                        return false;
                    }
                    buf.WriteByte(0); // Null terminator for the query
                    buf.WriteInt16((short)ParameterTypeOIDs.Count);
                    goto case State.WritingParameterTypes;

                case State.WritingParameterTypes:
                    _state = State.WritingParameterTypes;
                    for (; _parameterTypePos < ParameterTypeOIDs.Count; _parameterTypePos++)
                    {
                        if (buf.WriteSpaceLeft < 4)
                        {
                            return false;
                        }
                        buf.WriteInt32((int)ParameterTypeOIDs[_parameterTypePos]);
                    }

                    _state = State.WroteAll;
                    return true;

                default:
                    throw PGUtil.ThrowIfReached();
            }
        }
Ejemplo n.º 42
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteInt32(Length);
     buf.WriteInt32(80877103);
 }
Ejemplo n.º 43
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteByte(Code);
     buf.WriteInt32(Length - 1);
     buf.WriteBytes(Password, 0, Password.Length);
 }