コード例 #1
0
ファイル: ConvertTests.cs プロジェクト: zxd60/linq2db
 public void ConvertFromNullableEnum2()
 {
     Assert.AreEqual(10, ConvertTo <int> .From((Enum15?)Enum15.AA));
     Assert.AreEqual(0, ConvertTo <int> .From((Enum15?)null));
     Assert.AreEqual(null, ConvertTo <int?> .From((Enum15?)null));
 }
コード例 #2
0
ファイル: TestBase.cs プロジェクト: volodin-danila/linq2db
        static TestBase()
        {
            Console.WriteLine("Tests started in {0}...",
#if NETSTANDARD1_6
                              System.IO.Directory.GetCurrentDirectory()
#else
                              Environment.CurrentDirectory
#endif
                              );

            Console.WriteLine("CLR Version: {0}...",
#if NETSTANDARD1_6
                              System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription
#else
                              Environment.Version
#endif
                              );

            var traceCount = 0;

            DataConnection.WriteTraceLine = (s1, s2) =>
            {
                if (traceCount < 10000)
                {
                    Console.WriteLine("{0}: {1}", s2, s1);
                    Debug.WriteLine(s1, s2);
                }

                if (traceCount++ > 10000)
                {
                    DataConnection.TurnTraceSwitchOn(TraceLevel.Error);
                }
            };

//			Configuration.RetryPolicy.Factory = db => new Retry();

//			Configuration.AvoidSpecificDataProviderAPI = true;
            Configuration.Linq.TraceMapperExpression = false;
//			Configuration.Linq.GenerateExpressionTest  = true;
            var assemblyPath = typeof(TestBase).AssemblyEx().GetPath();

#if !NETSTANDARD1_6 && !NETSTANDARD2_0
            try
            {
                SqlServerTypes.Utilities.LoadNativeAssemblies(assemblyPath);
            }
            catch             // this can fail during tests discovering with NUnitTestAdapter
            { }
#endif

#if NETSTANDARD1_6
            System.IO.Directory.SetCurrentDirectory(assemblyPath);
#else
            Environment.CurrentDirectory = assemblyPath;
#endif

            var dataProvidersJsonFile     = GetFilePath(assemblyPath, @"DataProviders.json");
            var userDataProvidersJsonFile = GetFilePath(assemblyPath, @"UserDataProviders.json");

            var dataProvidersJson     = File.ReadAllText(dataProvidersJsonFile);
            var userDataProvidersJson =
                File.Exists(userDataProvidersJsonFile) ? File.ReadAllText(userDataProvidersJsonFile) : null;

#if NETSTANDARD1_6
            var configName = "CORE1";
#elif NETSTANDARD2_0
            var configName = "CORE2";
#else
            var configName = "NET45";
#endif

#if APPVEYOR
#warning "AppVeyor configuration detected."

            Console.WriteLine("AppVeyor configuration detected.");
            configName += ".AppVeyor";
#endif
#if TRAVIS
#warning "Travis configuration detected."

            Console.WriteLine("Travis configuration detected.");
            configName += ".Travis";
#endif
            var testSettings = SettingsReader.Deserialize(configName, dataProvidersJson, userDataProvidersJson);
            var databasePath = Path.GetFullPath(Path.Combine("Database"));
            var dataPath     = Path.Combine(databasePath, "Data");

            if (Directory.Exists(dataPath))
            {
                Directory.Delete(dataPath, true);
            }

            Directory.CreateDirectory(dataPath);

            foreach (var file in Directory.GetFiles(databasePath, "*.*"))
            {
                var destination = Path.Combine(dataPath, Path.GetFileName(file));
                Console.WriteLine("{0} => {1}", file, destination);
                File.Copy(file, destination, true);
            }

            UserProviders = new HashSet <string>(testSettings.Providers, StringComparer.OrdinalIgnoreCase);

            var logLevel   = testSettings.TraceLevel;
            var traceLevel = TraceLevel.Info;

            if (!string.IsNullOrEmpty(logLevel))
            {
                if (!Enum.TryParse(logLevel, true, out traceLevel))
                {
                    traceLevel = TraceLevel.Info;
                }
            }

            if (!string.IsNullOrEmpty(testSettings.NoLinqService))
            {
                BaseDataContextSourceAttribute.NoLinqService = ConvertTo <bool> .From(testSettings.NoLinqService);
            }

            DataConnection.TurnTraceSwitchOn(traceLevel);

            Console.WriteLine("Connection strings:");

#if NETSTANDARD1_6 || NETSTANDARD2_0
            DataConnection.DefaultSettings            = TxtSettings.Instance;
            TxtSettings.Instance.DefaultConfiguration = "SQLiteMs";

            foreach (var provider in testSettings.Connections /*.Where(c => UserProviders.Contains(c.Key))*/)
            {
                if (string.IsNullOrWhiteSpace(provider.Value.ConnectionString))
                {
                    throw new InvalidOperationException("ConnectionString should be provided");
                }

                Console.WriteLine($"\tName=\"{provider.Key}\", Provider=\"{provider.Value.Provider}\", ConnectionString=\"{provider.Value.ConnectionString}\"");

                TxtSettings.Instance.AddConnectionString(
                    provider.Key, provider.Value.Provider ?? provider.Key, provider.Value.ConnectionString);
            }
#else
            foreach (var provider in testSettings.Connections)
            {
                Console.WriteLine($"\tName=\"{provider.Key}\", Provider=\"{provider.Value.Provider}\", ConnectionString=\"{provider.Value.ConnectionString}\"");

                DataConnection.AddOrSetConfiguration(
                    provider.Key,
                    provider.Value.ConnectionString,
                    provider.Value.Provider ?? "");
            }
#endif

            Console.WriteLine("Providers:");

            foreach (var userProvider in UserProviders)
            {
                Console.WriteLine($"\t{userProvider}");
            }

            var defaultConfiguration = testSettings.DefaultConfiguration;

            if (!string.IsNullOrEmpty(defaultConfiguration))
            {
                DataConnection.DefaultConfiguration = defaultConfiguration;
#if NETSTANDARD1_6 || NETSTANDARD2_0
                TxtSettings.Instance.DefaultConfiguration = defaultConfiguration;
#endif
            }

#if !NETSTANDARD1_6 && !NETSTANDARD2_0
            LinqService.TypeResolver = str =>
            {
                switch (str)
                {
                case "Tests.Model.Gender": return(typeof(Gender));

                case "Tests.Model.Person": return(typeof(Person));

                default: return(null);
                }
            };
#endif
        }
コード例 #3
0
ファイル: LinqService.cs プロジェクト: zxsanny/linq2db
        public string ExecuteReader(string configuration, string queryData)
        {
            try
            {
                var query = LinqServiceSerializer.Deserialize(queryData);

                ValidateQuery(query);

                using (var db = CreateDataContext(configuration))
                {
                    using (var rd = DataConnection.QueryRunner.ExecuteReader(db, new QueryContext
                    {
                        SelectQuery = query.Query,
                        Parameters = query.Parameters,
                        QueryHints = query.QueryHints
                    }))
                    {
                        var ret = new LinqServiceResult
                        {
                            QueryID    = Guid.NewGuid(),
                            FieldCount = rd.FieldCount,
                            FieldNames = new string[rd.FieldCount],
                            FieldTypes = new Type  [rd.FieldCount],
                            Data       = new List <string[]>(),
                        };

                        for (var i = 0; i < ret.FieldCount; i++)
                        {
                            ret.FieldNames[i] = rd.GetName(i);
                            ret.FieldTypes[i] = rd.GetFieldType(i);
                        }

                        var varyingTypes = new List <Type>();

                        while (rd.Read())
                        {
                            var data  = new string  [rd.FieldCount];
                            var codes = new TypeCode[rd.FieldCount];

                            for (var i = 0; i < ret.FieldCount; i++)
                            {
                                codes[i] = Type.GetTypeCode(ret.FieldTypes[i]);
                            }

                            ret.RowCount++;

                            for (var i = 0; i < ret.FieldCount; i++)
                            {
                                if (!rd.IsDBNull(i))
                                {
                                    var code = codes[i];
                                    var type = rd.GetFieldType(i);
                                    var idx  = -1;

                                    if (type != ret.FieldTypes[i])
                                    {
                                        code = Type.GetTypeCode(type);
                                        idx  = varyingTypes.IndexOf(type);

                                        if (idx < 0)
                                        {
                                            varyingTypes.Add(type);
                                            idx = varyingTypes.Count - 1;
                                        }
                                    }

                                    switch (code)
                                    {
                                    case TypeCode.Decimal: data[i] = rd.GetDecimal(i).ToString(CultureInfo.InvariantCulture); break;

                                    case TypeCode.Double: data[i] = rd.GetDouble(i).ToString(CultureInfo.InvariantCulture); break;

                                    case TypeCode.Single: data[i] = rd.GetFloat(i).ToString(CultureInfo.InvariantCulture); break;

                                    case TypeCode.DateTime: data[i] = rd.GetDateTime(i).ToString("o");                          break;

                                    default:
                                    {
                                        if (type == typeof(DateTimeOffset))
                                        {
                                            var dt = rd.GetValue(i);

                                            if (dt is DateTime)
                                            {
                                                data[i] = ((DateTime)dt).ToString("o");
                                            }
                                            else if (dt is DateTimeOffset)
                                            {
                                                data[i] = ((DateTimeOffset)dt).ToString("o");
                                            }
                                            else
                                            {
                                                data[i] = rd.GetValue(i).ToString();
                                            }
                                        }
                                        else if (ret.FieldTypes[i] == typeof(byte[]))
                                        {
                                            data[i] = ConvertTo <string> .From((byte[])rd.GetValue(i));
                                        }
                                        else
                                        {
                                            data[i] = (rd.GetValue(i) ?? "").ToString();
                                        }

                                        break;
                                    }
                                    }

                                    if (idx >= 0)
                                    {
                                        data[i] = "\0" + (char)idx + data[i];
                                    }
                                }
                            }

                            ret.Data.Add(data);
                        }

                        ret.VaryingTypes = varyingTypes.ToArray();

                        return(LinqServiceSerializer.Serialize(ret));
                    }
                }
            }
            catch (Exception exception)
            {
                HandleException(exception);
                throw;
            }
        }
コード例 #4
0
 public override void SetByte(object o, int index, Byte value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #5
0
ファイル: SapHanaTests.cs プロジェクト: exileDev/linq2db
        public void TestEnum2([IncludeDataSources(CurrentProvider)] string context)
        {
            var paramName = context.Contains("Odbc") ? "?" : ":p";

            using (var conn = GetDataConnection(context))
            {
                Assert.That(conn.Execute <string>($"SELECT {paramName} from dummy", new { p = TestEnum.AA }), Is.EqualTo("A"));
                Assert.That(conn.Execute <string>($"SELECT {paramName} from dummy", new { p = (TestEnum?)TestEnum.BB }), Is.EqualTo("B"));

                Assert.That(conn.Execute <string>($"SELECT {paramName} from dummy", new { p = ConvertTo <string> .From((TestEnum?)TestEnum.AA) }), Is.EqualTo("A"));
                Assert.That(conn.Execute <string>($"SELECT {paramName} from dummy", new { p = ConvertTo <string> .From(TestEnum.AA) }), Is.EqualTo("A"));
                Assert.That(conn.Execute <string>($"SELECT {paramName} from dummy", new { p = conn.MappingSchema.GetConverter <TestEnum?, string>() !(TestEnum.AA) }), Is.EqualTo("A"));
コード例 #6
0
 public override void SetSqlDateTime(object o, int index, SqlDateTime value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #7
0
 public override void SetSqlString(object o, int index, SqlString value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #8
0
 private static string Convert(object o) => ConvertTo <string> .From(o);
コード例 #9
0
        static TestBase()
        {
            Console.WriteLine("Tests started in {0}...", Environment.CurrentDirectory);

            Console.WriteLine("CLR Version: {0}...", Environment.Version);

            var traceCount = 0;

            DataConnection.TurnTraceSwitchOn(TraceLevel.Info);
            DataConnection.WriteTraceLine = (message, name, level) =>
            {
                var ctx   = CustomTestContext.Get();
                var trace = ctx.Get <StringBuilder>(CustomTestContext.TRACE);
                if (trace == null)
                {
                    trace = new StringBuilder();
                    ctx.Set(CustomTestContext.TRACE, trace);
                }

                trace.AppendLine($"{name}: {message}");

                if (traceCount < TRACES_LIMIT || level == TraceLevel.Error)
                {
                    ctx.Set(CustomTestContext.LIMITED, true);
                    Console.WriteLine("{0}: {1}", name, message);
                    Debug.WriteLine(message, name);
                }

                traceCount++;
            };

            //			Configuration.RetryPolicy.Factory = db => new Retry();

            Configuration.Linq.TraceMapperExpression = false;
            //			Configuration.Linq.GenerateExpressionTest  = true;
            var assemblyPath = typeof(TestBase).Assembly.GetPath();

#if NET46
            try
            {
                SqlServerTypes.Utilities.LoadNativeAssemblies(assemblyPath);
            }
            catch             // this can fail during tests discovering with NUnitTestAdapter
            { }
#endif

            Environment.CurrentDirectory = assemblyPath;

            var dataProvidersJsonFile     = GetFilePath(assemblyPath, @"DataProviders.json");
            var userDataProvidersJsonFile = GetFilePath(assemblyPath, @"UserDataProviders.json");

            var dataProvidersJson     = File.ReadAllText(dataProvidersJsonFile);
            var userDataProvidersJson =
                File.Exists(userDataProvidersJsonFile) ? File.ReadAllText(userDataProvidersJsonFile) : null;

#if NETCOREAPP2_1
            var configName = "CORE21";
#elif NETCOREAPP3_1
            var configName = "CORE31";
#elif NET46
            var configName = "NET46";
#else
            var configName = "";
#error Unknown framework
#endif

#if AZURE
            Console.WriteLine("Azure configuration detected.");
            configName += ".Azure";
#endif
            var testSettings = SettingsReader.Deserialize(configName, dataProvidersJson, userDataProvidersJson);
            var databasePath = Path.GetFullPath(Path.Combine("Database"));
            var dataPath     = Path.Combine(databasePath, "Data");

            if (Directory.Exists(dataPath))
            {
                Directory.Delete(dataPath, true);
            }

            Directory.CreateDirectory(dataPath);

            foreach (var file in Directory.GetFiles(databasePath, "*.*"))
            {
                var destination = Path.Combine(dataPath, Path.GetFileName(file));
                Console.WriteLine("{0} => {1}", file, destination);
                File.Copy(file, destination, true);
            }

            UserProviders  = new HashSet <string>(testSettings.Providers ?? Array <string> .Empty, StringComparer.OrdinalIgnoreCase);
            SkipCategories = new HashSet <string>(testSettings.Skip ?? Array <string> .Empty, StringComparer.OrdinalIgnoreCase);

            var logLevel   = testSettings.TraceLevel;
            var traceLevel = TraceLevel.Info;

            if (!string.IsNullOrEmpty(logLevel))
            {
                if (!Enum.TryParse(logLevel, true, out traceLevel))
                {
                    traceLevel = TraceLevel.Info;
                }
            }

            if (!string.IsNullOrEmpty(testSettings.NoLinqService))
            {
                DataSourcesBaseAttribute.NoLinqService = ConvertTo <bool> .From(testSettings.NoLinqService);
            }

            DataConnection.TurnTraceSwitchOn(traceLevel);

            Console.WriteLine("Connection strings:");

#if !NET46
            DataConnection.DefaultSettings            = TxtSettings.Instance;
            TxtSettings.Instance.DefaultConfiguration = "SQLiteMs";

            foreach (var provider in testSettings.Connections /*.Where(c => UserProviders.Contains(c.Key))*/)
            {
                if (string.IsNullOrWhiteSpace(provider.Value.ConnectionString))
                {
                    throw new InvalidOperationException("ConnectionString should be provided");
                }

                Console.WriteLine($"\tName=\"{provider.Key}\", Provider=\"{provider.Value.Provider}\", ConnectionString=\"{provider.Value.ConnectionString}\"");

                TxtSettings.Instance.AddConnectionString(
                    provider.Key, provider.Value.Provider ?? "", provider.Value.ConnectionString);
            }
#else
            foreach (var provider in testSettings.Connections)
            {
                Console.WriteLine($"\tName=\"{provider.Key}\", Provider=\"{provider.Value.Provider}\", ConnectionString=\"{provider.Value.ConnectionString}\"");

                DataConnection.AddOrSetConfiguration(
                    provider.Key,
                    provider.Value.ConnectionString,
                    provider.Value.Provider ?? "");
            }
#endif

            Console.WriteLine("Providers:");

            foreach (var userProvider in UserProviders)
            {
                Console.WriteLine($"\t{userProvider}");
            }

            DefaultProvider = testSettings.DefaultConfiguration;

            if (!DefaultProvider.IsNullOrEmpty())
            {
                DataConnection.DefaultConfiguration = DefaultProvider;
#if !NET46
                TxtSettings.Instance.DefaultConfiguration = DefaultProvider;
#endif
            }

#if NET46
            LinqService.TypeResolver = str =>
            {
                return(str switch
                {
                    "Tests.Model.Gender" => typeof(Gender),
                    "Tests.Model.Person" => typeof(Person),
                    _ => null,
                });
            };
コード例 #10
0
        public override void SetParameter(IDbDataParameter parameter, string name, DbDataType dataType, object value)
        {
            if (value is sbyte sb)
            {
                value    = (short)sb;
                dataType = dataType.WithDataType(DataType.Int16);
            }
            else if (value is byte b)
            {
                value    = (short)b;
                dataType = dataType.WithDataType(DataType.Int16);
            }

            switch (dataType.DataType)
            {
            case DataType.UInt16: dataType = dataType.WithDataType(DataType.Int32);    break;

            case DataType.UInt32: dataType = dataType.WithDataType(DataType.Int64);    break;

            case DataType.UInt64: dataType = dataType.WithDataType(DataType.Decimal);  break;

            case DataType.VarNumeric: dataType = dataType.WithDataType(DataType.Decimal);  break;

            case DataType.DateTime2: dataType = dataType.WithDataType(DataType.DateTime); break;

            case DataType.Char:
            case DataType.VarChar:
            case DataType.NChar:
            case DataType.NVarChar:
            {
                if (value is Guid g)
                {
                    value = g.ToString();
                }
                else if (value is bool b)
                {
                    value = ConvertTo <char> .From(b);
                }
                break;
            }

            case DataType.Boolean:
            case DataType.Int16:
            {
                if (value is bool b)
                {
                    value    = b ? 1 : 0;
                    dataType = dataType.WithDataType(DataType.Int16);
                }
                break;
            }

            case DataType.Guid:
            {
                if (value is Guid g)
                {
                    value    = g.ToByteArray();
                    dataType = dataType.WithDataType(DataType.VarBinary);
                }
                if (value == null)
                {
                    dataType = dataType.WithDataType(DataType.VarBinary);
                }
                break;
            }

            case DataType.Binary:
            case DataType.VarBinary:
            {
                if (value is Guid g)
                {
                    value = g.ToByteArray();
                }
                else if (parameter.Size == 0 && value != null && value.GetType().Name == "DB2Binary")
                {
                    dynamic v = value;
                    if (v.IsNull)
                    {
                        value = DBNull.Value;
                    }
                }
                break;
            }

            case DataType.Blob:
                base.SetParameter(parameter, "@" + name, dataType, value);
                _setBlob(parameter);
                return;
            }

            base.SetParameter(parameter, "@" + name, dataType, value);
        }
コード例 #11
0
 public override void SetValue(object obj, object value)
 {
     Setter(obj, ConvertTo <T> .From(value));
 }
コード例 #12
0
            public IEnumerable <TestMethod> BuildFrom(IMethodInfo method, Test suite)
            {
                var tests = UserProviders.ContainsKey(_providerName) ?
                            new[]
                {
                    new TypeTestData("bigintDataType", 0, (n, t, c) => t.TestTypeEx <long?>             (c, n, DataType.Int64), 1000000),
                    new TypeTestData("bigintDataType", 1, (n, t, c) => t.TestTypeEx <long?>             (c, n, DataType.Int64), 1000000),
                    new TypeTestData("numericDataType", (n, t, c) => t.TestTypeEx <decimal?>          (c, n, DataType.Decimal), 9999999m),
                    new TypeTestData("smallintDataType", (n, t, c) => t.TestTypeEx <short?>            (c, n, DataType.Int16), 25555),
                    new TypeTestData("intDataType", (n, t, c) => t.TestTypeEx <int?>              (c, n, DataType.Int32), 7777777),
//						new TypeTestData("moneyDataType",       (n,t,c) => t.TestTypeEx<decimal?>          (c, n, DataType.Money),   100000m),
                    new TypeTestData("doubleDataType", (n, t, c) => t.TestTypeEx <double?>           (c, n, DataType.Double), 20.31d),
                    new TypeTestData("realDataType", (n, t, c) => t.TestTypeEx <float?>            (c, n, DataType.Single), 16.2f),

#if NPG2
                    new TypeTestData("timestampDataType", (n, t, c) => t.TestTypeEx <NpgsqlTimeStamp?>  (c, n), new NpgsqlTimeStamp(2012, 12, 12, 12, 12, 12)),
                    new TypeTestData("timestampTZDataType", (n, t, c) => t.TestTypeEx <NpgsqlTimeStampTZ?>(c, n), new NpgsqlTimeStampTZ(2012, 12, 12, 11, 12, 12, new NpgsqlTimeZone(-5, 0))),
                    new TypeTestData("timeDataType", (n, t, c) => t.TestTypeEx <NpgsqlTime?>       (c, n), new NpgsqlTime(12, 12, 12)),
                    new TypeTestData("timeTZDataType", (n, t, c) => t.TestTypeEx <NpgsqlTimeTZ?>     (c, n), new NpgsqlTimeTZ(12, 12, 12)),
                    new TypeTestData("intervalDataType", (n, t, c) => t.TestTypeEx <NpgsqlInterval?>   (c, n), new NpgsqlInterval(1, 3, 5, 20)),
                    new TypeTestData("bitDataType", (n, t, c) => t.TestTypeEx <BitString?>        (c, n), new BitString(new[] { true, false, true })),
                    new TypeTestData("macaddrDataType", (n, t, c) => t.TestTypeEx <NpgsqlMacAddress?> (c, n), new NpgsqlMacAddress("01:02:03:04:05:06")),
#else
//						new TypeTestData("timestampDataType",   (n,t,c) => t.TestTypeEx<NpgsqlTimeStamp?>  (c, n),                       new NpgsqlTimeStamp(2012, 12, 12, 12, 12, 12)),
//						new TypeTestData("timestampTZDataType", (n,t,c) => t.TestTypeEx<NpgsqlTimeStampTZ?>(c, n),                       new NpgsqlTimeStampTZ(2012, 12, 12, 11, 12, 12, new NpgsqlTimeZone(-5, 0))),
                    new TypeTestData("timeDataType", (n, t, c) => t.TestTypeEx <TimeSpan?>         (c, n), new TimeSpan(12, 12, 12)),
//						new TypeTestData("timeTZDataType",      (n,t,c) => t.TestTypeEx<NpgsqlTimeTZ?>     (c, n),                       new NpgsqlTimeTZ(12, 12, 12)),
//						new TypeTestData("intervalDataType",    (n,t,c) => t.TestTypeEx<TimeSpan?>         (c, n),                       new TimeSpan(1, 3, 5, 20)),
                    new TypeTestData("bitDataType", (n, t, c) => t.TestTypeEx <BitArray>          (c, n), new BitArray(new[] { true, false, true })),
                    new TypeTestData("varBitDataType", (n, t, c) => t.TestTypeEx <BitArray>          (c, n), new BitArray(new[] { true, false, true, true })),
                    new TypeTestData("macaddrDataType", (n, t, c) => t.TestTypeEx <PhysicalAddress>   (c, n, skipDefaultNull: true), new PhysicalAddress(new byte[] { 1, 2, 3, 4, 5, 6 })),
#endif

                    new TypeTestData("timestampDataType", (n, t, c) => t.TestTypeEx <DateTime?>         (c, n, DataType.DateTime2), new DateTime(2012, 12, 12, 12, 12, 12)),
                    new TypeTestData("timestampTZDataType", (n, t, c) => t.TestTypeEx <DateTimeOffset?>   (c, n, DataType.DateTimeOffset), new DateTimeOffset(2012, 12, 12, 11, 12, 12, new TimeSpan(-5, 0, 0))),
                    new TypeTestData("dateDataType", 0, (n, t, c) => t.TestTypeEx <NpgsqlDate?>       (c, n, skipDefaultNull: true), new NpgsqlDate(2012, 12, 12)),
                    new TypeTestData("dateDataType", 1, (n, t, c) => t.TestTypeEx <DateTime?>         (c, n, DataType.Date), new DateTime(2012, 12, 12)),

                    new TypeTestData("charDataType", 0, (n, t, c) => t.TestTypeEx <char?>             (c, n, DataType.Char), '1'),
                    new TypeTestData("charDataType", 1, (n, t, c) => t.TestTypeEx <string>            (c, n, DataType.Char, skipDefaultNull: true), "1"),
                    new TypeTestData("charDataType", 2, (n, t, c) => t.TestTypeEx <string>            (c, n, DataType.NChar, skipDefaultNull: true), "1"),
                    new TypeTestData("varcharDataType", 0, (n, t, c) => t.TestTypeEx <string>            (c, n, DataType.VarChar, skipDefaultNull: true), "234"),
                    new TypeTestData("varcharDataType", 1, (n, t, c) => t.TestTypeEx <string>            (c, n, DataType.NVarChar, skipDefaultNull: true), "234"),
                    new TypeTestData("textDataType", (n, t, c) => t.TestTypeEx <string>            (c, n, DataType.Text, skipDefaultNull: true), "567"),

                    new TypeTestData("binaryDataType", 0, (n, t, c) => t.TestTypeEx <byte[]>            (c, n, DataType.Binary), new byte[] { 42 }),
                    new TypeTestData("binaryDataType", 1, (n, t, c) => t.TestTypeEx <byte[]>            (c, n, DataType.VarBinary), new byte[] { 42 }),
                    new TypeTestData("binaryDataType", 2, (n, t, c) => t.TestTypeEx <Binary>            (c, n, DataType.VarBinary).ToArray(), new byte[] { 42 }),

                    new TypeTestData("uuidDataType", (n, t, c) => t.TestTypeEx <Guid?>             (c, n, DataType.Guid), new Guid("6F9619FF-8B86-D011-B42D-00C04FC964FF")),
                    new TypeTestData("booleanDataType", (n, t, c) => t.TestTypeEx <bool?>             (c, n, DataType.Boolean), true),
//						new TypeTestData("colorDataType",       (n,t,c) => t.TestTypeEx<string>            (c, n, skipDefaultNull:true, skipDefault:true,skipUndefined:true), "Green"),

                    new TypeTestData("pointDataType", (n, t, c) => t.TestTypeEx <NpgsqlPoint?>      (c, n, skipNull: true, skipNotNull: true), new NpgsqlPoint(1, 2)),
                    new TypeTestData("lsegDataType", (n, t, c) => t.TestTypeEx <NpgsqlLSeg?>       (c, n, skipDefaultNull: true), new NpgsqlLSeg(new NpgsqlPoint(1, 2), new NpgsqlPoint(3, 4))),
                    new TypeTestData("boxDataType", (n, t, c) => t.TestTypeEx <NpgsqlBox?>        (c, n, skipDefaultNull: true).ToString(), new NpgsqlBox(new NpgsqlPoint(3, 4), new NpgsqlPoint(1, 2)).ToString()),
#if !NPGSQL226
                    new TypeTestData("pathDataType", (n, t, c) => t.TestTypeEx <NpgsqlPath?>       (c, n, skipDefaultNull: true), new NpgsqlPath(new NpgsqlPoint(1, 2), new NpgsqlPoint(3, 4))),
                    new TypeTestData("polygonDataType", (n, t, c) => t.TestTypeEx <NpgsqlPolygon?>    (c, n, skipNull: true, skipNotNull: true), new NpgsqlPolygon(new NpgsqlPoint(1, 2), new NpgsqlPoint(3, 4))),
#endif
                    new TypeTestData("circleDataType", (n, t, c) => t.TestTypeEx <NpgsqlCircle?>     (c, n, skipDefaultNull: true), new NpgsqlCircle(new NpgsqlPoint(1, 2), 3)),

                    new TypeTestData("inetDataType", (n, t, c) => t.TestTypeEx <NpgsqlInet?>       (c, n, skipDefaultNull: true), new NpgsqlInet(new IPAddress(new byte[] { 192, 168, 1, 1 }))),

                    new TypeTestData("xmlDataType", 0, (n, t, c) => t.TestTypeEx <string>            (c, n, DataType.Xml, skipNull: true, skipNotNull: true),
                                     "<root><element strattr=\"strvalue\" intattr=\"12345\"/></root>"),
                    new TypeTestData("xmlDataType", 1, (n, t, c) => t.TestTypeEx <XDocument>         (c, n, DataType.Xml, skipNull: true, skipNotNull: true).ToString(),
                                     XDocument.Parse("<root><element strattr=\"strvalue\" intattr=\"12345\"/></root>").ToString()),
                    new TypeTestData("xmlDataType", 2, (n, t, c) => t.TestTypeEx <XmlDocument>       (c, n, DataType.Xml, skipNull: true, skipNotNull: true).InnerXml,
                                     ConvertTo <XmlDocument> .From("<root><element strattr=\"strvalue\" intattr=\"12345\"/></root>").InnerXml),
                }
                                        :
                new[]
                {
                    new TypeTestData("ignore", (n, t, c) => t.TestTypeEx <long?>(c, n, DataType.Int64), 1000000)
                };

                var builder = new NUnitTestCaseBuilder();

                var data = tests.Select(t => new TestCaseParameters(new object[] { t.Name, t.ID, t, _providerName }));

                foreach (var item in data)
                {
                    var test = builder.BuildTestMethod(method, suite, item);

                    test.Properties.Set(PropertyNames.Category, _providerName);

                    if (!UserProviders.ContainsKey(_providerName))
                    {
                        test.RunState = RunState.Ignored;
                        test.Properties.Set(PropertyNames.SkipReason, "Provider is disabled. See UserDataProviders.txt");
                    }

                    yield return(test);
                }
            }
コード例 #13
0
 public void ConvertFromEnum()
 {
     Assert.AreEqual(15, ConvertTo <int> .From(Enum4.Value1));
     Assert.AreEqual(25, ConvertTo <int> .From(Enum4.Value2));
 }
コード例 #14
0
ファイル: ConvertTests.cs プロジェクト: zxd60/linq2db
 public void ToObject()
 {
     Assert.AreEqual(1, ConvertTo <object> .From(1));
 }
コード例 #15
0
 public override void SetNullableDateTimeOffset(object o, int index, DateTimeOffset?value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #16
0
 public override void SetChar(object o, int index, Char value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #17
0
 public override void SetSqlBoolean(object o, int index, SqlBoolean value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #18
0
 public override void SetNullableInt64(object o, int index, Int64?value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #19
0
 public override void SetSqlDecimal(object o, int index, SqlDecimal value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #20
0
 public override void SetNullableUInt32(object o, int index, UInt32?value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #21
0
 public override void SetInt32(object o, int index, Int32 value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #22
0
 public override void SetNullableBoolean(object o, int index, Boolean?value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #23
0
 public override void SetUInt64(object o, int index, UInt64 value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #24
0
 public override void SetNullableSingle(object o, int index, Single?value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #25
0
        protected override List <ColumnInfo> GetColumns(DataConnection dataConnection)
        {
            return(dataConnection
                   .Query <ColumnInfo>(@"
					SELECT
						c.tabid     as TableID,
						c.colname   as Name,
						c.colno     as Ordinal,
						c.coltype   as DataType,
						c.collength as Length
					FROM systables t
						JOIN syscolumns c ON t.tabid = c.tabid
					WHERE t.tabid >= 100"                    )
                   .Select(c =>
            {
                var typeid = ConvertTo <int> .From(c.DataType);
                var len = c.Length;

                c.Length = 0;
                c.IsNullable = (typeid & 0x100) != 0x100;

                switch (typeid & 0xFF)
                {
                case    0:
                    c.DataType = "CHAR";
                    c.Length = len;
                    break;

                case    1: c.DataType = "SMALLINT";         break;

                case    2: c.DataType = "INTEGER";          break;

                case    3: c.DataType = "FLOAT";            break;

                case    4: c.DataType = "SMALLFLOAT";       break;

                case    5:
                    c.DataType = "DECIMAL";
                    c.Precision = (int)(len / 256);
                    if (c.Precision >= len % 256)
                    {
                        c.Scale = (int)(len % 256);
                    }
                    break;

                case    6:
                    c.DataType = "SERIAL";
                    c.IsIdentity = c.SkipOnInsert = c.SkipOnUpdate = true;
                    break;

                case    7: c.DataType = "DATE";             break;

                case    8:
                    c.DataType = "MONEY";
                    c.Precision = (int)(len / 256);
                    if (c.Precision >= len % 256)
                    {
                        c.Scale = (int)(len % 256);
                    }
                    break;

                case    9: c.DataType = "NULL";             break;

                case   10:
                    c.DataType = "DATETIME";
                    SetDate(c, (int)len);
                    break;

                case   11: c.DataType = "BYTE";             break;

                case   12: c.DataType = "TEXT";             break;

                case   13:
                    c.DataType = "VARCHAR";
                    c.Length = len;
                    break;

                case   14:
                    c.DataType = "INTERVAL";
                    SetDate(c, (int)len);
                    break;

                case   15:
                    c.DataType = "NCHAR";
                    c.Length = len;
                    break;

                case   16:
                    c.DataType = "NVARCHAR";
                    c.Length = len;
                    break;

                case   17: c.DataType = "INT8";             break;

                case   18: c.DataType = "SERIAL8";          break;

                case   19: c.DataType = "SET";              break;

                case   20: c.DataType = "MULTISET";         break;

                case   21: c.DataType = "LIST";             break;

                case   22: c.DataType = "ROW";              break;

                case   23: c.DataType = "COLLECTION";       break;

                case   40:                                  // Variable-length opaque type
                    c.DataType = "LVARCHAR";
                    c.Length = len;
                    break;

                case   41: c.DataType = "BOOLEAN";          break;                                  // Fixed-length opaque type

                case   43:
                    c.DataType = "LVARCHAR";
                    c.Length = len;
                    break;

                case   45: c.DataType = "BOOLEAN";          break;

                case   52: c.DataType = "BIGINT";           break;

                case   53:
                    c.DataType = "BIGSERIAL";
                    c.IsIdentity = c.SkipOnInsert = c.SkipOnUpdate = true;
                    break;

                case 2061: c.DataType = "IDSSECURITYLABEL"; break;

                case 4118: c.DataType = "ROW";              break;
                }

                return c;
            })
                   .ToList());
        }
コード例 #26
0
 public override void SetNullableDecimal(object o, int index, Decimal?value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #27
0
ファイル: FirebirdTests.cs プロジェクト: zxd60/linq2db
        public void TestEnum2([IncludeDataSources(TestProvName.AllFirebird)] string context)
        {
            using (var conn = new DataConnection(context))
            {
                Assert.That(conn.Execute <string>("SELECT Cast(@p as char) FROM \"Dual\"", new { p = TestEnum.AA }), Is.EqualTo("A"));
                Assert.That(conn.Execute <string>("SELECT Cast(@p as char) FROM \"Dual\"", new { p = (TestEnum?)TestEnum.BB }), Is.EqualTo("B"));

                Assert.That(conn.Execute <string>("SELECT Cast(@p as char) FROM \"Dual\"", new { p = ConvertTo <string> .From((TestEnum?)TestEnum.AA) }), Is.EqualTo("A"));
                Assert.That(conn.Execute <string>("SELECT Cast(@p as char) FROM \"Dual\"", new { p = ConvertTo <string> .From(TestEnum.AA) }), Is.EqualTo("A"));
                Assert.That(conn.Execute <string>("SELECT Cast(@p as char) FROM \"Dual\"", new { p = conn.MappingSchema.GetConverter <TestEnum?, string>() !(TestEnum.AA) }), Is.EqualTo("A"));
コード例 #28
0
 public override void SetNullableGuid(object o, int index, Guid?value)
 {
     _list.Add(ConvertTo <T> .From(value));
 }
コード例 #29
0
ファイル: DB2Tests.cs プロジェクト: mladenmihanovic/linq2db
 public void TestEnum2(string context)
 {
     using (var conn = new DataConnection(context))
     {
         Assert.That(conn.Execute <string>("SELECT @p FROM SYSIBM.SYSDUMMY1", new { p = TestEnum.AA }), Is.EqualTo("A"));
         Assert.That(conn.Execute <string>("SELECT @p FROM SYSIBM.SYSDUMMY1", new { p = (TestEnum?)TestEnum.BB }), Is.EqualTo("B"));
         Assert.That(conn.Execute <string>("SELECT @p FROM SYSIBM.SYSDUMMY1", new { p = ConvertTo <string> .From((TestEnum?)TestEnum.AA) }), Is.EqualTo("A"));
         Assert.That(conn.Execute <string>("SELECT @p FROM SYSIBM.SYSDUMMY1", new { p = ConvertTo <string> .From(TestEnum.AA) }), Is.EqualTo("A"));
         Assert.That(conn.Execute <string>("SELECT @p FROM SYSIBM.SYSDUMMY1", new { p = conn.MappingSchema.GetConverter <TestEnum?, string>()(TestEnum.AA) }), Is.EqualTo("A"));
     }
 }
コード例 #30
0
ファイル: ConvertTests.cs プロジェクト: zxd60/linq2db
 public void ConvertToEnum11()
 {
     Assert.AreEqual(Enum11.Value1, ConvertTo <Enum11> .From(Enum10.Value2));
     Assert.AreEqual(Enum11.Value2, ConvertTo <Enum11> .From(Enum10.Value1));
     Assert.AreEqual(Enum11.Value3, ConvertTo <Enum11> .From(Enum10.Value3));
 }