internal CommandCompleteMessage Load(NpgsqlBuffer buf, int len) { RowsAffected = null; LastInsertedOID = null; var tag = buf.ReadString(len-1); buf.Skip(1); // Null terminator var tokens = tag.Split(); switch (tokens[0]) { case "INSERT": var lastInsertedOID = uint.Parse(tokens[1]); if (lastInsertedOID != 0) { LastInsertedOID = lastInsertedOID; } goto case "UPDATE"; case "UPDATE": case "DELETE": case "COPY": uint rowsAffected; if (uint.TryParse(tokens[tokens.Length - 1], out rowsAffected)) { RowsAffected = rowsAffected; } break; } return this; }
internal override void PrepareRead(NpgsqlBuffer buf, FieldDescription fieldDescription, int len) { if (fieldDescription.IsBinaryFormat) { throw new NotSupportedException("The type {0} currently unknown to Npgsql. You can retrieve it as a string by marking it as unknown, please see the FAQ."); } base.PrepareRead(buf, fieldDescription, len); }
static PregeneratedMessage() { _tempBuf = new NpgsqlBuffer(new MemoryStream(), NpgsqlBuffer.MinimumBufferSize, Encoding.ASCII); BeginTransRepeatableRead = BuildQuery("BEGIN; SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;"); BeginTransSerializable = BuildQuery("BEGIN; SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;"); BeginTransReadCommitted = BuildQuery("BEGIN; SET TRANSACTION ISOLATION LEVEL READ COMMITTED;"); BeginTransReadUncommitted = BuildQuery("BEGIN; SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;"); CommitTransaction = BuildQuery("COMMIT"); RollbackTransaction = BuildQuery("ROLLBACK"); DiscardAll = BuildQuery("DISCARD ALL"); UnlistenAll = BuildQuery("UNLISTEN *"); KeepAlive = BuildQuery("SELECT NULL"); SetStmtTimeout10Sec = BuildQuery("SET statement_timeout = 10000"); SetStmtTimeout20Sec = BuildQuery("SET statement_timeout = 20000"); SetStmtTimeout30Sec = BuildQuery("SET statement_timeout = 30000"); SetStmtTimeout60Sec = BuildQuery("SET statement_timeout = 60000"); SetStmtTimeout90Sec = BuildQuery("SET statement_timeout = 90000"); SetStmtTimeout120Sec = BuildQuery("SET statement_timeout = 120000"); _tempBuf = null; BeginTransactionMessages = new[] { BeginTransRepeatableRead, BeginTransSerializable, BeginTransReadCommitted, BeginTransReadUncommitted }; }
internal override void PrepareRead(NpgsqlBuffer buf, FieldDescription fieldDescription, int len) { if (fieldDescription.IsBinaryFormat) { buf.Skip(len); throw new SafeReadException(new NotSupportedException(String.Format("The field {0} has a type currently unknown to Npgsql (OID {1}). You can retrieve it as a string by marking it as unknown, please see the FAQ.", fieldDescription.Name, fieldDescription.OID))); } base.PrepareRead(buf, fieldDescription, len); }
internal override void Write(NpgsqlBuffer buf) { Contract.Requires(Query != null && Query.All(c => c < 128)); buf.WriteByte(Code); buf.WriteInt32(Length - 1); buf.WriteBytesNullTerminated(Encoding.ASCII.GetBytes(Query)); }
internal ParameterDescriptionMessage Load(NpgsqlBuffer buf) { var numParams = buf.ReadInt16(); TypeOIDs.Clear(); for (var i = 0; i < numParams; i++) { TypeOIDs.Add(buf.ReadUInt32()); } return this; }
internal override void Write(NpgsqlBuffer buf) { Contract.Requires(BackendProcessId != 0); buf.WriteInt32(Length); buf.WriteInt32(CancelRequestCode); buf.WriteInt32(BackendProcessId); buf.WriteInt32(BackendSecretKey); }
internal override void Write(NpgsqlBuffer 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)); }
internal override DataRowMessage Load(NpgsqlBuffer buf) { buf.Ensure(sizeof(short)); NumColumns = buf.ReadInt16(); Buffer = buf; Column = -1; ColumnLen = -1; PosInColumn = 0; return this; }
internal override void Write(NpgsqlBuffer buf) { Contract.Requires(Portal != null && Portal.All(c => c < 128)); // TODO: Recycle? var portalNameBytes = Encoding.ASCII.GetBytes(Portal); buf.WriteByte(Code); buf.WriteInt32(Length - 1); buf.WriteBytesNullTerminated(portalNameBytes); buf.WriteInt32(MaxRows); }
internal override void Write(NpgsqlBuffer buf) { buf.WriteInt32(_length); buf.WriteInt32(ProtocolVersion3); foreach (var kv in _parameters) { buf.WriteBytesNullTerminated(kv.Key); buf.WriteBytesNullTerminated(kv.Value); } buf.WriteByte(0); }
internal override void Write(NpgsqlBuffer buf) { buf.WriteByte(Code); buf.WriteInt32(Length - 1); if (_errorMessageLen == 0) { buf.WriteByte(0); } else { buf.WriteBytesNullTerminated(PGUtil.UTF8Encoding.GetBytes(_errorMessage)); } }
internal void Load(NpgsqlBuffer buf) { ColumnFormatCodes.Clear(); var binaryIndicator = buf.ReadByte(); switch (binaryIndicator) { case 0: IsBinary = false; break; case 1: IsBinary = true; break; default: throw new Exception("Invalid binary indicator in CopyInResponse message: " + binaryIndicator); } NumColumns = buf.ReadInt16(); for (var i = 0; i < NumColumns; i++) ColumnFormatCodes.Add((FormatCode)buf.ReadInt16()); }
internal override DataRowMessage Load(NpgsqlBuffer buf) { NumColumns = buf.ReadInt16(); Buffer = buf; Column = -1; ColumnLen = -1; PosInColumn = 0; // TODO: Recycle message objects rather than recreating for each row _columnOffsets = new List<int>(NumColumns); for (var i = 0; i < NumColumns; i++) { _columnOffsets.Add(buf.ReadPosition); var len = buf.ReadInt32(); if (len != -1) { buf.Seek(len, SeekOrigin.Current); } } _endOffset = buf.ReadPosition; return this; }
string ISimpleTypeReader <string> .Read(NpgsqlBuffer buf, FieldDescription fieldDescription, int len) { return(((ISimpleTypeReader <NpgsqlInet>) this).Read(buf, fieldDescription, len).ToString()); }
NpgsqlDateTime ISimpleTypeReader <NpgsqlDateTime> .Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return(ReadTimeStamp(buf, len, fieldDescription)); }
internal override bool Write(NpgsqlBuffer 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.WroteNothing: var formatCodesSum = InputParameters.Select(p => p.FormatCode).Sum(c => (int)c); var 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 2 * formatCodeListLength + // List of format codes 2; // Number of parameters 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 + 4 * InputParameters.Count + // Parameter lengths InputParameters.Select(p => p.ValidateAndGetLength()).Sum() + // Parameter values 2 + // Number of result format codes 2 * (UnknownResultTypeList == null ? 1 : UnknownResultTypeList.Length); // Result format codes buf.WriteByte(Code); buf.WriteInt32(messageLength-1); buf.WriteBytesNullTerminated(Encoding.ASCII.GetBytes(Portal)); buf.WriteBytesNullTerminated(Encoding.ASCII.GetBytes(Statement)); // 0 implicitly means all-text, 1 means all binary, >1 means mix-and-match buf.WriteInt16(formatCodeListLength); if (formatCodeListLength == 1) { buf.WriteInt16((short)FormatCode.Binary); } else if (formatCodeListLength > 1) { foreach (var code in InputParameters.Select(p => p.FormatCode)) buf.WriteInt16((short)code); } buf.WriteInt16(InputParameters.Count); _state = State.WroteHeader; goto case State.WroteHeader; case State.WroteHeader: if (!WriteParameters(buf, ref directBuf)) { return false; } _state = State.WroteParameters; goto case State.WroteParameters; case State.WroteParameters: 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(); } }
public void Write(object value, NpgsqlBuffer buf) { DoWrite(value, buf, false); }
public bool Write(ref DirectBuffer directBuf) { if (_charPos == -1) { if (_byteLen <= _buf.WriteSpaceLeft) { // Can simply write the string to the buffer if (_str != null) { _buf.WriteStringSimple(_str, _charLen); _str = null; } else { Contract.Assert(_chars != null); _buf.WriteCharsSimple(_chars, _charLen); _str = null; } _buf = null; return(true); } if (_byteLen <= _buf.Size) { // Buffer is currently too full, but the string can fit. Force a write to fill. return(false); } // Bad case: the string doesn't fit in our buffer. _charPos = 0; // For strings, allocate a temporary byte buffer to hold the entire string and write it directly. if (_str != null) { directBuf.Buffer = new byte[_byteLen]; _buf.TextEncoding.GetBytes(_str, 0, _charLen, directBuf.Buffer, 0); return(false); } Contract.Assert(_chars != null); // For char arrays, fall through to chunked writing below } if (_str != null) { // We did a direct buffer write above, and must now clean up _str = null; _buf = null; return(true); } int charsUsed; bool completed; _buf.WriteStringChunked(_chars, _charPos, _chars.Length - _charPos, false, out charsUsed, out completed); if (completed) { // Flush encoder _buf.WriteStringChunked(_chars, _charPos, _chars.Length - _charPos, true, out charsUsed, out completed); _chars = null; _buf = null; return(true); } _charPos += charsUsed; return(false); }
public decimal Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return(buf.ReadInt64() / 100m); }
internal override void Write(NpgsqlBuffer buf) { buf.WriteByte(Code); buf.WriteInt32(Length - 1); buf.WriteBytes(Password, 0, Password.Length); }
DateTimeOffset ISimpleTypeReader <DateTimeOffset> .Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return(new DateTimeOffset(ReadTimeStamp(buf, len, fieldDescription).DateTime, TimeSpan.Zero)); }
NpgsqlDateTime ISimpleTypeReader <NpgsqlDateTime> .Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { var ts = ReadTimeStamp(buf, len, fieldDescription); return(new NpgsqlDateTime(ts.Date, ts.Time, DateTimeKind.Utc)); }
internal ReadyForQueryMessage Load(NpgsqlBuffer buf) { TransactionStatusIndicator = (TransactionStatus)buf.ReadByte(); return(this); }
public void Write(object value, NpgsqlBuffer buf) { var f = GetIConvertibleValue <float>(value); buf.WriteSingle(f); }
double ISimpleTypeReader <double> .Read(NpgsqlBuffer buf, FieldDescription fieldDescription, int len) { return(Read(buf, fieldDescription, len)); }
public float Read(NpgsqlBuffer buf, FieldDescription fieldDescription, int len) { return(buf.ReadSingle()); }
public void Write(object value, NpgsqlBuffer buf, NpgsqlParameter parameter) { throw new NotSupportedException(); }
internal override void Write(NpgsqlBuffer buf) { buf.WriteByte(Code); buf.WriteInt32(4); }
public int Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { throw new Exception("Non-safe read exception as requested"); }
public short Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return(buf.ReadInt16()); }
NpgsqlInet ISimpleTypeReader <NpgsqlInet> .Read(NpgsqlBuffer buf, FieldDescription fieldDescription, int len) { return(DoRead(buf, fieldDescription, len, false)); }
decimal ISimpleTypeReader <decimal> .Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return(Read(buf, len, fieldDescription)); }
public void Write(object value, NpgsqlBuffer buf) { var money = value is decimal ? (decimal)value : Decimal.Parse(value.ToString(), CultureInfo.InvariantCulture); buf.WriteInt64((long)(money * 100m + 0.5m /* round */)); }
public DateTime Read(NpgsqlBuffer buf, FieldDescription fieldDescription, int len) { // TODO: Convert directly to DateTime without passing through NpgsqlTime? return((DateTime)((ISimpleTypeReader <NpgsqlTime>) this).Read(buf, fieldDescription, len)); }
internal virtual void PrepareRead(NpgsqlBuffer buf, FieldDescription fieldDescription, int len) { _buf = buf; _byteLen = len; _bytePos = -1; }
public void PrepareWrite(object value, NpgsqlBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter = null) { _buf = buf; _value = (NpgsqlPath)value; _index = -1; }
bool WriteParameters(NpgsqlBuffer 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; } if (param.LengthCache != null) { param.LengthCache.Rewind(); } } var handler = param.Handler; var asChunkingWriter = handler as IChunkingTypeWriter; 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 = (ISimpleTypeWriter)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; }
public void PrepareRead(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { _buf = buf; _index = -1; }
internal abstract DataRowMessage Load(NpgsqlBuffer buf);
internal static AuthenticationGSSContinueMessage Load(NpgsqlBuffer buf, int len) { len -= 4; // The AuthRequestType code var authenticationData = new byte[len]; buf.ReadBytes(authenticationData, 0, len); return new AuthenticationGSSContinueMessage(authenticationData); }
internal CommandCompleteMessage Load(NpgsqlBuffer buf, int len) { Rows = 0; OID = 0; var tag = buf.ReadString(len-1); buf.Skip(1); // Null terminator var tokens = tag.Split(); switch (tokens[0]) { case "INSERT": StatementType = StatementType.Insert; uint oid; if (uint.TryParse(tokens[1], out oid)) { OID = oid; } else { Log.Error("Ignoring unparseable OID in CommandComplete: " + tokens[1]); } ParseRows(tokens[2]); break; case "DELETE": StatementType = StatementType.Delete; ParseRows(tokens[1]); break; case "UPDATE": StatementType = StatementType.Update; ParseRows(tokens[1]); break; case "SELECT": StatementType = StatementType.Select; // PostgreSQL 8.4 and below doesn't include the number of rows if (tokens.Length > 1) { ParseRows(tokens[1]); } break; case "MOVE": StatementType = StatementType.Move; ParseRows(tokens[1]); break; case "FETCH": StatementType = StatementType.Fetch; ParseRows(tokens[1]); break; case "COPY": StatementType = StatementType.Copy; ParseRows(tokens[1]); break; case "CREATE": if (tag.StartsWith("CREATE TABLE AS")) { StatementType = StatementType.CreateTableAs; ParseRows(tokens[3]); break; } goto default; default: StatementType = StatementType.Other; break; } return this; }
internal override bool Write(NpgsqlBuffer buf) { Contract.Requires(Statement != null && Statement.All(c => c < 128)); switch (_state) { case State.WroteNothing: _statementNameBytes = BackendEncoding.UTF8Encoding.GetBytes(Statement); _queryLen = BackendEncoding.UTF8Encoding.GetByteCount(Query); if (buf.WriteSpaceLeft < 4 + _statementNameBytes.Length + 1) { return false; } var messageLength = 4 + // Length _statementNameBytes.Length + 1 + // Null terminator _queryLen + 1 + // Null terminator 2 + // Number of parameters ParameterTypeOIDs.Count * 4; buf.WriteByte(Code); buf.WriteInt32(messageLength); buf.WriteBytesNullTerminated(_statementNameBytes); goto case State.WroteHeader; case State.WroteHeader: _state = State.WroteHeader; if (_queryLen <= buf.WriteSpaceLeft) { buf.WriteStringSimple(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 + ParameterTypeOIDs.Count * 4) { return false; } buf.WriteByte(0); // Null terminator for the query buf.WriteInt16((short)ParameterTypeOIDs.Count); foreach (var t in ParameterTypeOIDs) { buf.WriteInt32((int)t); } _state = State.WroteAll; return true; default: throw PGUtil.ThrowIfReached(); } }
public TimeSpan Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return((TimeSpan)((ISimpleTypeReader <NpgsqlTimeSpan>) this).Read(buf, len, fieldDescription)); }
internal override void Write(NpgsqlBuffer buf) { buf.WriteBytes(_data, 0, _data.Length); }
// ReSharper disable once FunctionComplexityOverflow internal ErrorOrNoticeMessage(NpgsqlBuffer buf) { while (true) { var code = (ErrorFieldTypeCode)buf.ReadByte(); switch (code) { case ErrorFieldTypeCode.Done: // Null terminator; error message fully consumed. return; case ErrorFieldTypeCode.Severity: Severity = buf.ReadNullTerminatedString(PGUtil.RelaxedUTF8Encoding); break; case ErrorFieldTypeCode.Code: Code = buf.ReadNullTerminatedString(); break; case ErrorFieldTypeCode.Message: Message = buf.ReadNullTerminatedString(PGUtil.RelaxedUTF8Encoding); break; case ErrorFieldTypeCode.Detail: Detail = buf.ReadNullTerminatedString(PGUtil.RelaxedUTF8Encoding); break; case ErrorFieldTypeCode.Hint: Hint = buf.ReadNullTerminatedString(PGUtil.RelaxedUTF8Encoding); break; case ErrorFieldTypeCode.Position: var positionStr = buf.ReadNullTerminatedString(); int position; if (!int.TryParse(positionStr, out position)) { Log.Warn("Non-numeric position in ErrorResponse: " + positionStr); continue; } Position = position; break; case ErrorFieldTypeCode.InternalPosition: var internalPositionStr = buf.ReadNullTerminatedString(); int internalPosition; if (!Int32.TryParse(internalPositionStr, out internalPosition)) { Log.Warn("Non-numeric position in ErrorResponse: " + internalPositionStr); continue; } InternalPosition = internalPosition; break; case ErrorFieldTypeCode.InternalQuery: InternalQuery = buf.ReadNullTerminatedString(); break; case ErrorFieldTypeCode.Where: Where = buf.ReadNullTerminatedString(); break; case ErrorFieldTypeCode.File: File = buf.ReadNullTerminatedString(PGUtil.RelaxedUTF8Encoding); break; case ErrorFieldTypeCode.Line: Line = buf.ReadNullTerminatedString(); break; case ErrorFieldTypeCode.Routine: Routine = buf.ReadNullTerminatedString(); break; case ErrorFieldTypeCode.SchemaName: SchemaName = buf.ReadNullTerminatedString(); break; case ErrorFieldTypeCode.TableName: TableName = buf.ReadNullTerminatedString(); break; case ErrorFieldTypeCode.ColumnName: ColumnName = buf.ReadNullTerminatedString(); break; case ErrorFieldTypeCode.DataTypeName: DataTypeName = buf.ReadNullTerminatedString(); break; case ErrorFieldTypeCode.ConstraintName: ConstraintName = buf.ReadNullTerminatedString(); break; default: // Unknown error field; consume and discard. buf.ReadNullTerminatedString(); break; } } }
public int Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { buf.ReadInt32(); throw new SafeReadException(new Exception("Safe read exception as requested")); }
internal static AuthenticationMD5PasswordMessage Load(NpgsqlBuffer buf) { var salt = new byte[4]; buf.ReadBytes(salt, 0, 4); return new AuthenticationMD5PasswordMessage(salt); }
internal override void Write(NpgsqlBuffer buf) { buf.WriteByte((byte)BackendMessageCode.CopyDone); buf.WriteInt32(4); }
internal new CopyBothResponseMessage Load(NpgsqlBuffer buf) { base.Load(buf); return this; }
byte ISimpleTypeReader <byte> .Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return((byte)Read(buf, len, fieldDescription)); }
int ISimpleTypeReader <int> .Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return((int)Read(buf, len, fieldDescription)); }
long ISimpleTypeReader <long> .Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return((long)Read(buf, len, fieldDescription)); }
public NpgsqlCircle Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return(new NpgsqlCircle(buf.ReadDouble(), buf.ReadDouble(), buf.ReadDouble())); }
public IPAddress Read(NpgsqlBuffer buf, FieldDescription fieldDescription, int len) { return(((ISimpleTypeReader <NpgsqlInet>) this).Read(buf, fieldDescription, len).Address); }
internal BackendKeyDataMessage(NpgsqlBuffer buf) { BackendProcessId = buf.ReadInt32(); BackendSecretKey = buf.ReadInt32(); }
internal ReadyForQueryMessage Load(NpgsqlBuffer buf) { TransactionStatusIndicator = (TransactionStatus)buf.ReadByte(); return this; }
string ISimpleTypeReader <string> .Read(NpgsqlBuffer buf, int len, FieldDescription fieldDescription) { return(Read(buf, len, fieldDescription).ToString()); }