private byte[] ConvertToBackendPlainQuery(Object NativeData, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            if ((NativeData == DBNull.Value) || (NativeData == null))
            {
                return(ASCIIByteArrays.NULL); // Plain queries exptects null values as string NULL.
            }

            if (_ConvertNativeToBackendText != null)
            {
                byte[] backendSerialization;

                // This path is responsible for escaping, and may also add quoting and the E prefix.
                backendSerialization = (_ConvertNativeToBackendText(this, NativeData, false, options, arrayElement));

                if (Quote)
                {
                    backendSerialization = QuoteASCIIString(backendSerialization, false, arrayElement);
                }

                return(backendSerialization);
            }
            else if (NativeData is Enum)
            {
                byte[] backendSerialization;

                // Do a special handling of Enum values.
                // Translate enum value to its underlying type.
                backendSerialization =
                    BackendEncoding.UTF8Encoding.GetBytes(
                        (String)Convert.ChangeType(
                            Enum.Format(NativeData.GetType(), NativeData, "d"),
                            typeof(String), CultureInfo.InvariantCulture
                            )
                        );

                backendSerialization = QuoteASCIIString(backendSerialization, false, arrayElement);

                return(backendSerialization);
            }
            else
            {
                byte[] backendSerialization;

                if (NativeData is IFormattable)
                {
                    backendSerialization = BackendEncoding.UTF8Encoding.GetBytes(((IFormattable)NativeData).ToString(null, ni));
                }
                else
                {
                    backendSerialization = BackendEncoding.UTF8Encoding.GetBytes(NativeData.ToString());
                }

                if (Quote)
                {
                    backendSerialization = QuoteASCIIString(backendSerialization, false, arrayElement);
                }

                return(backendSerialization);
            }
        }
        private byte[] ConvertToBackendExtendedQuery(Object NativeData, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            if ((NativeData == DBNull.Value) || (NativeData == null))
            {
                return(null); // Extended query expects null values be represented as null.
            }

            if (!NpgsqlTypesHelper.SuppressBinaryBackendEncoding && _ConvertNativeToBackendBinary != null)
            {
                return(_ConvertNativeToBackendBinary(this, NativeData, options));
            }
            else if (_ConvertNativeToBackendText != null)
            {
                byte[] backendSerialization;

                backendSerialization = _ConvertNativeToBackendText(this, NativeData, true, options, arrayElement);

                if (Quote)
                {
                    backendSerialization = QuoteASCIIString(backendSerialization, true, arrayElement);
                }

                return(backendSerialization);
            }
            else
            {
                byte[] backendSerialization;

                if (NativeData is Enum)
                {
                    // Do a special handling of Enum values.
                    // Translate enum value to its underlying type.
                    backendSerialization = BackendEncoding.UTF8Encoding.GetBytes((String)
                                                                                 Convert.ChangeType(Enum.Format(NativeData.GetType(), NativeData, "d"), typeof(String),
                                                                                                    CultureInfo.InvariantCulture));
                }
                else if (NativeData is IFormattable)
                {
                    backendSerialization = BackendEncoding.UTF8Encoding.GetBytes(((IFormattable)NativeData).ToString(null, ni));
                }
                else
                {
                    backendSerialization = BackendEncoding.UTF8Encoding.GetBytes(NativeData.ToString());
                }

                if (Quote)
                {
                    backendSerialization = QuoteASCIIString(backendSerialization, true, arrayElement);
                }

                return(backendSerialization);
            }
        }
        /// <summary>
        /// Perform a data conversion from a native object to
        /// a backend representation.
        /// DBNull and null values are handled differently depending if a plain query is used
        /// When
        /// </summary>
        /// <param name="NativeData">Native .NET object to be converted.</param>
        /// <param name="forExtendedQuery">Specifies that the value should be formatted for the extended query syntax.</param>
        /// <param name="options">Options to guide serialization.  If null, a default options set is used.</param>
        /// <param name="arrayElement">Specifies that the value should be formatted as an extended query array element.</param>
        public byte[] ConvertToBackend(Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options = null, bool arrayElement = false)
        {
            if (options == null)
            {
                options = NativeToBackendTypeConverterOptions.Default;
            }

            if (forExtendedQuery)
            {
                return(ConvertToBackendExtendedQuery(NativeData, options, arrayElement));
            }
            else
            {
                return(ConvertToBackendPlainQuery(NativeData, options, arrayElement));
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Serialise the enumeration or array.
        /// </summary>
        public byte[] ArrayToArrayText(NpgsqlNativeTypeInfo TypeInfo, object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            MemoryStream array = new MemoryStream();

            if (!forExtendedQuery)
            {
                if (!options.UseConformantStrings && options.Supports_E_StringPrefix)
                {
                    array.WriteByte((byte)ASCIIBytes.E);
                }

                array.WriteByte((byte)ASCIIBytes.SingleQuote);
            }

            if (!WriteItemText(TypeInfo, NativeData, array, forExtendedQuery, options))
            {
                array.Write(ASCIIArrayByteArrays.EmptyArray, 0, ASCIIArrayByteArrays.EmptyArray.Length);
            }

            if (!forExtendedQuery)
            {
                array.WriteByte((byte)ASCIIBytes.SingleQuote);
            }

            return(array.ToArray());
        }
        internal static byte[] ToTimeTZ(NpgsqlNativeTypeInfo typeInfo, object nativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            if (nativeData is DateTime)
            {
                return(BasicNativeToBackendTypeConverter.ToTime(typeInfo, nativeData, forExtendedQuery, options, arrayElement));
            }
            NpgsqlTimeTZ time;

            if (nativeData is TimeSpan)
            {
                time = (NpgsqlTimeTZ)(TimeSpan)nativeData;
            }
            else
            {
                time = (NpgsqlTimeTZ)nativeData;
            }
            return(BackendEncoding.UTF8Encoding.GetBytes(time.ToString()));
        }
 /// <summary>
 /// Convert to a postgres inet.
 /// </summary>
 internal static byte[] ToIPAddress(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     if (NativeData is NpgsqlInet)
     {
         return(BackendEncoding.UTF8Encoding.GetBytes(((NpgsqlInet)NativeData).ToString()));
     }
     return(BackendEncoding.UTF8Encoding.GetBytes(NativeData.ToString()));
 }
        /// <summary>
        /// Polygon.
        /// </summary>
        internal static byte[] ToPolygon(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            StringBuilder B = new StringBuilder();

            foreach (NpgsqlPoint P in ((NpgsqlPolygon)NativeData))
            {
                B.AppendFormat(CultureInfo.InvariantCulture, "{0}({1},{2})", (B.Length > 0 ? "," : ""), P.X, P.Y);
            }

            return(BackendEncoding.UTF8Encoding.GetBytes(String.Format("({0})", B)));
        }
        /// <summary>
        /// Box.
        /// </summary>
        internal static byte[] ToBox(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            /*if (NativeData.GetType() == typeof(Rectangle)) {
             *  Rectangle       R = (Rectangle)NativeData;
             *  return String.Format(CultureInfo.InvariantCulture, "({0},{1}),({2},{3})", R.Left, R.Top, R.Left + R.Width, R.Top + R.Height);
             * } else if (NativeData.GetType() == typeof(RectangleF)) {
             *  RectangleF      R = (RectangleF)NativeData;
             *  return String.Format(CultureInfo.InvariantCulture, "({0},{1}),({2},{3})", R.Left, R.Top, R.Left + R.Width, R.Top + R.Height);*/

            if (NativeData is NpgsqlBox)
            {
                NpgsqlBox box = (NpgsqlBox)NativeData;
                return
                    (BackendEncoding.UTF8Encoding.GetBytes(String.Format(CultureInfo.InvariantCulture, "({0},{1}),({2},{3})", box.LowerLeft.X, box.LowerLeft.Y,
                                                                         box.UpperRight.X, box.UpperRight.Y)));
            }
            else
            {
                throw new InvalidCastException("Unable to cast data to Rectangle type");
            }
        }
 /// <summary>
 /// Convert a System.Double to a postgres float8.
 /// </summary>
 internal static byte[] DoubleToFloat8Binary(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, NativeToBackendTypeConverterOptions options)
 {
     return(PGUtil.HostNetworkByteOrderSwap(BitConverter.GetBytes(Convert.ToDouble(NativeData))));
 }
 internal static byte[] ToBasicType <T>(NpgsqlNativeTypeInfo TypeInfo, object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     // This double cast is needed in order to get the enum type handled correctly (IConvertible)
     // and the decimal separator always as "." regardless of culture (IFormattable)
     return(BackendEncoding.UTF8Encoding.GetBytes((((IFormattable)((IConvertible)NativeData).ToType(typeof(T), null)).ToString(null, CultureInfo.InvariantCulture.NumberFormat))));
 }
 /// <summary>
 /// Convert a string to UTF8 encoded text.
 /// </summary>
 internal static byte[] StringToTextBinary(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, NativeToBackendTypeConverterOptions options)
 {
     return(BackendEncoding.UTF8Encoding.GetBytes(NativeData.ToString()));
 }
        /// <summary>
        /// Convert a string to UTF8 encoded text, escaped and quoted as required.
        /// </summary>
        internal static byte[] StringToTextText(NpgsqlNativeTypeInfo TypeInfo, Object oNativeData, bool forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            string             NativeData = oNativeData.ToString();
            StringEncodingInfo encodingInfo;

            // Using a four bit hash key derived from the options at hand,
            // find the correct string encoding info object.
            encodingInfo = stringEncodingInfoTable[
                StringEncodingInfoHash(
                    forExtendedQuery,
                    options.UseConformantStrings,
                    options.Supports_E_StringPrefix,
                    arrayElement
                    )
                           ];

            if (encodingInfo.Quote == 0)
            {
                // No quoting or escaping needed.
                return(BackendEncoding.UTF8Encoding.GetBytes(NativeData));
            }

            // Give the output string builder enough room to start for the string, quotes, E-prefix,
            // and 1 in 10 characters needing to be escaped; a WAG.
            StringBuilder retQuotedEscaped = new StringBuilder(NativeData.Length + 3 + NativeData.Length / 10);

            if (encodingInfo.UseEPrefix)
            {
                retQuotedEscaped.Append('E');
            }

            retQuotedEscaped.Append((char)encodingInfo.Quote);

            // Escape the string using the escape characters from the lookup.
            foreach (char ch in NativeData)
            {
                switch (ch)
                {
                case '\'':
                    retQuotedEscaped.Append(encodingInfo.SingleQuoteEscape);
                    break;

                case '\"':
                    retQuotedEscaped.Append(encodingInfo.DoubleQuoteEscape);
                    break;

                case '\\':
                    retQuotedEscaped.Append(encodingInfo.BackSlashEscape);
                    break;
                }

                retQuotedEscaped.Append(ch);
            }

            retQuotedEscaped.Append((char)encodingInfo.Quote);

            return(BackendEncoding.UTF8Encoding.GetBytes(retQuotedEscaped.ToString()));
        }
 static NativeToBackendTypeConverterOptions()
 {
     _default = new NativeToBackendTypeConverterOptions(true, false, true, false, null);
 }
Exemplo n.º 14
0
        private bool WriteItemText(NpgsqlNativeTypeInfo TypeInfo, object item, MemoryStream array, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options)
        {
            //item could be:
            //an Ienumerable - in which case we call WriteEnumeration
            //an element - in which case we call the NpgsqlNativeTypeInfo for that type to serialise it.
            //an array - in which case we call WriteArray,

            // Even an string being an IEnumerable, it shouldn't be processed. It will be processed on the last else.
            // See http://pgfoundry.org/tracker/?func=detail&atid=592&aid=1010514&group_id=1000140 for more info.

            if (item == null || NpgsqlTypesHelper.DefinedType(item))
            {
                byte[] element;

                element = _elementConverter.ConvertToBackend(item, forExtendedQuery, options, true);

                array.Write(element, 0, element.Length);

                return(true);
            }
            else if (item is Array)
            {
                return(WriteArrayText(TypeInfo, item as Array, array, forExtendedQuery, options));
            }
            else if (item is IEnumerable)
            {
                return(WriteEnumeration(TypeInfo, item as IEnumerable, array, forExtendedQuery, options));
            }
            else
            {//This shouldn't really be reachable.
                byte[] element;

                element = _elementConverter.ConvertToBackend(item, forExtendedQuery, options, true);

                array.Write(element, 0, element.Length);

                return(true);
            }
        }
 /// <summary>
 /// Convert to a postgresql time.
 /// </summary>
 internal static byte[] ToTime(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     if (!(NativeData is DateTime))
     {
         return(ExtendedNativeToBackendTypeConverter.ToTime(TypeInfo, NativeData, forExtendedQuery, options, arrayElement));
     }
     else
     {
         return(BackendEncoding.UTF8Encoding.GetBytes(((DateTime)NativeData).ToString("HH:mm:ss.ffffff", DateTimeFormatInfo.InvariantInfo)));
     }
 }
        /// <summary>
        /// Binary data, escaped and quoted as required.
        /// </summary>
        internal static byte[] ByteArrayToByteaText(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, bool forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            StringEncodingInfo encodingInfo;

            // Using a four bit hash key derived from the options at hand,
            // find the correct string encoding info object.
            encodingInfo = stringEncodingInfoTable[
                StringEncodingInfoHash(
                    forExtendedQuery,
                    options.UseConformantStrings,
                    options.Supports_E_StringPrefix,
                    arrayElement
                    )
                           ];

            if (!options.SupportsHexByteFormat)
            {
                return(ByteArrayToByteaTextEscaped((byte[])NativeData, encodingInfo));
            }
            else
            {
                return(ByteArrayToByteaTextHexFormat((byte[])NativeData, encodingInfo));
            }
        }
 /// <summary>
 /// Convert to a postgres money.
 /// </summary>
 internal static byte[] ToMoney(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     //Formats accepted vary according to locale, but it always accepts a plain number (no currency or
     //grouping symbols) passed as a string (with the appropriate cast appended, as UseCast will cause
     //to happen.
     return(BackendEncoding.UTF8Encoding.GetBytes(((IFormattable)NativeData).ToString(null, CultureInfo.InvariantCulture.NumberFormat)));
 }
 /// <summary>
 /// Binary data, raw.
 /// </summary>
 internal static byte[] ByteArrayToByteaBinary(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, NativeToBackendTypeConverterOptions options)
 {
     return((byte[])NativeData);
 }
 internal static byte[] DoubleToFloat8Text(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     //Formats accepted vary according to locale, but it always accepts a plain number (no currency or
     //grouping symbols) passed as a string (with the appropriate cast appended, as UseCast will cause
     //to happen.
     if (!arrayElement)
     {
         var asDouble = (double)NativeData;
         if (double.IsNaN(asDouble))
         {
             return(ASCIIByteArrays.NAN_QUOTED);
         }
         if (double.IsPositiveInfinity(asDouble))
         {
             return(ASCIIByteArrays.INFINITY_QUOTED);
         }
         if (double.IsNegativeInfinity(asDouble))
         {
             return(ASCIIByteArrays.NEG_INFINITY_QUOTED);
         }
     }
     return(BackendEncoding.UTF8Encoding.GetBytes(((IFormattable)NativeData).ToString("R", CultureInfo.InvariantCulture.NumberFormat)));
 }
 /// <summary>
 /// Convert to a postgresql boolean text format.
 /// </summary>
 internal static byte[] BooleanToBooleanText(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     return(((bool)NativeData) ? ASCIIByteArrays.TRUE : ASCIIByteArrays.FALSE);
 }
 /// <summary>
 /// Point.
 /// </summary>
 internal static byte[] ToPoint(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     if (NativeData is NpgsqlPoint)
     {
         NpgsqlPoint P = (NpgsqlPoint)NativeData;
         return(BackendEncoding.UTF8Encoding.GetBytes(String.Format(CultureInfo.InvariantCulture, "({0},{1})", P.X, P.Y)));
     }
     else
     {
         throw new InvalidCastException("Unable to cast data to NpgsqlPoint type");
     }
 }
 /// <summary>
 /// Convert to a postgresql boolean binary format.
 /// </summary>
 internal static byte[] BooleanToBooleanBinary(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, NativeToBackendTypeConverterOptions options)
 {
     return(((bool)NativeData) ? ASCIIByteArrays.Byte_1 : ASCIIByteArrays.Byte_0);
 }
        /// <summary>
        /// LSeg.
        /// </summary>
        internal static byte[] ToLSeg(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            NpgsqlLSeg S = (NpgsqlLSeg)NativeData;

            return(BackendEncoding.UTF8Encoding.GetBytes(String.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", S.Start.X, S.Start.Y, S.End.X, S.End.Y)));
        }
 /// <summary>
 /// Convert to a postgresql binary int8.
 /// </summary>
 internal static byte[] Int64ToInt8Binary(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, NativeToBackendTypeConverterOptions options)
 {
     return(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(Convert.ToInt64(NativeData))));
 }
        /// <summary>
        /// Circle.
        /// </summary>
        internal static byte[] ToCircle(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            NpgsqlCircle C = (NpgsqlCircle)NativeData;

            return(BackendEncoding.UTF8Encoding.GetBytes(String.Format(CultureInfo.InvariantCulture, "{0},{1},{2}", C.Center.X, C.Center.Y, C.Radius)));
        }
 /// <summary>
 /// Convert to a postgresql bit.
 /// </summary>
 internal static byte[] ToBit(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     if (NativeData is bool)
     {
         return(((bool)NativeData) ? ASCIIByteArrays.AsciiDigit_1 : ASCIIByteArrays.AsciiDigit_0);
     }
     // It may seem more sensible to just convert an integer to a BitString here and pass it on.
     // However behaviour varies in terms of how this is interpretted if being passed to a bitstring
     // value smaller than the int.
     // Prior to Postgres 8.0, the behaviour would be the same either way. E.g. if 10 were passed to
     // a bit(1) then the bits (1010) would be extracted from the left, so resulting in the bitstring B'1'.
     // From 8.0 onwards though, if we cast 10 straight to a bit(1) then the right-most bit is taken,
     // resulting in B'0'. If we cast it to the "natural" bitstring for it's size first (which is what would
     // happen if we did that work here) then it would become B'1010' which would then be cast to bit(1) by
     // taking the left-most bit resulting in B'1' (the behaviour one would expect from Postgres 7.x).
     //
     // Since we don't know what implicit casts (say by inserting into a table with a bitstring field of
     // set size) may happen, we don't know how to ensure expected behaviour. While passing a bitstring
     // literal would work as expected with Postgres before 8.0, it can fail with 8.0 and later.
     else if (NativeData is int)
     {
         return(BackendEncoding.UTF8Encoding.GetBytes(NativeData.ToString()));
     }
     else
     {
         return(BackendEncoding.UTF8Encoding.GetBytes(((BitString)NativeData).ToString("E")));
     }
 }
 /// <summary>
 /// Convert to a postgres interval
 /// </summary>
 internal static byte[] ToInterval(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     return
         (BackendEncoding.UTF8Encoding.GetBytes(((NativeData is TimeSpan)
             ? ((NpgsqlInterval)(TimeSpan)NativeData).ToString()
             : ((NpgsqlInterval)NativeData).ToString())));
 }
 /// <summary>
 /// Convert to a postgresql timestamp.
 /// </summary>
 internal static byte[] ToDateTime(NpgsqlNativeTypeInfo TypeInfo, Object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     if (!(NativeData is DateTime))
     {
         return(ExtendedNativeToBackendTypeConverter.ToTimeStamp(TypeInfo, NativeData, forExtendedQuery, options, arrayElement));
     }
     if (DateTime.MaxValue.Equals(NativeData))
     {
         return(ASCIIByteArrays.INFINITY);
     }
     if (DateTime.MinValue.Equals(NativeData))
     {
         return(ASCIIByteArrays.NEG_INFINITY);
     }
     return(BackendEncoding.UTF8Encoding.GetBytes((((DateTime)NativeData).ToString("yyyy-MM-dd HH:mm:ss.ffffff", DateTimeFormatInfo.InvariantInfo))));
 }
 internal static byte[] ToTimeStamp(NpgsqlNativeTypeInfo typeInfo, object nativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
 {
     if (nativeData is DateTime)
     {
         return(BasicNativeToBackendTypeConverter.ToDateTime(typeInfo, nativeData, forExtendedQuery, options, arrayElement));
     }
     else
     {
         return(BackendEncoding.UTF8Encoding.GetBytes(nativeData.ToString()));
     }
 }
Exemplo n.º 30
0
        private bool WriteEnumeration(NpgsqlNativeTypeInfo TypeInfo, IEnumerable col, MemoryStream array, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options)
        {
            bool writtenSomething = false;
            bool firstItem        = true;


            //write each item with a comma between them.
            foreach (object item in col)
            {
                if (firstItem)
                {
                    array.WriteByte((byte)ASCIIBytes.BraceCurlyLeft);
                    firstItem = false;
                }
                else
                {
                    array.WriteByte((byte)ASCIIBytes.Comma);
                }

                writtenSomething |= WriteItemText(TypeInfo, item, array, forExtendedQuery, options);
            }

            if (writtenSomething)
            {
                array.WriteByte((byte)ASCIIBytes.BraceCurlyRight);
            }

            return(writtenSomething);
        }