diff --git a/Changelog.md b/Changelog.md index b0a1d77..9984980 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,6 +2,6 @@ Refactoring efforts complete. First NuGet drop. -## Version 3.0.1 +## Version 3.0.2 -Revert names of public classes to `SnowflakeXxx` insead of `SFXxxx`. This was a bad idea that makes adoption from the legacy version harder than necessary for minimal gains. +Revert names of public classes to `SnowflakeDbXxx` insead of `SFXxxx`. This was a bad idea that makes adoption from the legacy version harder than necessary for minimal gains. diff --git a/Snowflake.Data.Tests/Mock/MockCloseSessionException.cs b/Snowflake.Data.Tests/Mock/MockCloseSessionException.cs index bbac773..c5e42e9 100644 --- a/Snowflake.Data.Tests/Mock/MockCloseSessionException.cs +++ b/Snowflake.Data.Tests/Mock/MockCloseSessionException.cs @@ -58,7 +58,7 @@ public Task PostAsync(RestRequest postRequest, CancellationToken cancellat } else { - throw new SnowflakeException("", SESSION_CLOSE_ERROR, "Mock generated error", null); + throw new SnowflakeDbException("", SESSION_CLOSE_ERROR, "Mock generated error", null); } } diff --git a/Snowflake.Data.Tests/Mock/MockSnowflakeDbConnection.cs b/Snowflake.Data.Tests/Mock/MockSnowflakeDbConnection.cs index 058db89..f8393c8 100644 --- a/Snowflake.Data.Tests/Mock/MockSnowflakeDbConnection.cs +++ b/Snowflake.Data.Tests/Mock/MockSnowflakeDbConnection.cs @@ -8,7 +8,7 @@ namespace Tortuga.Data.Snowflake.Tests.Mock; -class MockSnowflakeDbConnection : SnowflakeConnection +class MockSnowflakeDbConnection : SnowflakeDbConnection { readonly private IMockRestRequester _restRequester; @@ -31,7 +31,7 @@ public override void Open() SfSession.Open(); OnSessionEstablished(); } - catch (SnowflakeException) + catch (SnowflakeDbException) { m_ConnectionState = ConnectionState.Closed; throw; @@ -40,7 +40,7 @@ public override void Open() { // Otherwise when Dispose() is called, the close request would timeout. m_ConnectionState = System.Data.ConnectionState.Closed; - throw new SnowflakeException(ex, SnowflakeError.InternalError, "Unable to connect"); + throw new SnowflakeDbException(ex, SnowflakeDbError.InternalError, "Unable to connect"); } } @@ -55,7 +55,7 @@ public async override Task OpenAsync(CancellationToken cancellationToken) await SfSession.OpenAsync(cancellationToken).ConfigureAwait(false); OnSessionEstablished(); } - catch (SnowflakeException) + catch (SnowflakeDbException) { m_ConnectionState = ConnectionState.Closed; throw; @@ -68,13 +68,13 @@ public async override Task OpenAsync(CancellationToken cancellationToken) catch (Exception ex) when (ex is not TaskCanceledException || !cancellationToken.IsCancellationRequested) { m_ConnectionState = ConnectionState.Closed; - throw new SnowflakeException(ex, SnowflakeError.InternalError, "Unable to connect"); + throw new SnowflakeDbException(ex, SnowflakeDbError.InternalError, "Unable to connect"); } } private void SetMockSession() { - SfSession = new SFSession(ConnectionString, Password, _restRequester, SnowflakeConfiguration.Default); + SfSession = new SFSession(ConnectionString, Password, _restRequester, SnowflakeDbConfiguration.Default); m_ConnectionTimeout = (int)SfSession.m_ConnectionTimeout.TotalSeconds; diff --git a/Snowflake.Data.Tests/SFBindTestIT.cs b/Snowflake.Data.Tests/SFBindTestIT.cs index 8d21d55..cc1d869 100755 --- a/Snowflake.Data.Tests/SFBindTestIT.cs +++ b/Snowflake.Data.Tests/SFBindTestIT.cs @@ -14,7 +14,7 @@ class SFBindTestIT : SFBaseTest [Test] public void TestArrayBind() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -54,7 +54,7 @@ public void TestArrayBind() [Test] public void TestBindNullValue() { - using (var dbConnection = new SnowflakeConnection()) + using (var dbConnection = new SnowflakeDbConnection()) { dbConnection.ConnectionString = ConnectionString; dbConnection.Open(); @@ -164,9 +164,9 @@ public void TestBindNullValue() command.Parameters.Add(param); int rowsInserted = command.ExecuteNonQuery(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.UnsupportedDotnetType, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.UnsupportedDotnetType, e.SnowflakeError); } } } @@ -207,7 +207,7 @@ public void TestBindNullValue() [Test] public void testBindValue() { - using (SnowflakeConnection dbConnection = new SnowflakeConnection()) + using (SnowflakeDbConnection dbConnection = new SnowflakeDbConnection()) { dbConnection.ConnectionString = ConnectionString; dbConnection.Open(); @@ -330,9 +330,9 @@ public void testBindValue() command.Parameters.Add(param); int rowsInserted = command.ExecuteNonQuery(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.UnsupportedDotnetType, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.UnsupportedDotnetType, e.SnowflakeError); } } } @@ -373,20 +373,20 @@ public void testBindValue() [Test] public void TestBindValueWithSFDataType() { - using (SnowflakeConnection dbConnection = new SnowflakeConnection()) + using (SnowflakeDbConnection dbConnection = new SnowflakeDbConnection()) { dbConnection.ConnectionString = ConnectionString; dbConnection.Open(); try { - foreach (SnowflakeDataType type in Enum.GetValues(typeof(SnowflakeDataType))) + foreach (SnowflakeDbDataType type in Enum.GetValues(typeof(SnowflakeDbDataType))) { - if (!type.Equals(SnowflakeDataType.None)) + if (!type.Equals(SnowflakeDbDataType.None)) { bool isTypeSupported = true; using (var command = dbConnection.CreateCommand()) { - if (!type.Equals(SnowflakeDataType.Fixed)) + if (!type.Equals(SnowflakeDbDataType.Fixed)) { command.CommandText = $"create or replace table TEST_TBL (data {type}, unsupportedType VARCHAR)"; } @@ -399,48 +399,48 @@ public void TestBindValueWithSFDataType() using (var command = dbConnection.CreateCommand()) { - SnowflakeParameter param = (SnowflakeParameter)command.CreateParameter(); + SnowflakeDbParameter param = (SnowflakeDbParameter)command.CreateParameter(); param.ParameterName = "p0"; param.SFDataType = type; switch (type) { - case SnowflakeDataType.Binary: + case SnowflakeDbDataType.Binary: param.Value = Encoding.UTF8.GetBytes("BinaryData"); break; - case SnowflakeDataType.Fixed: + case SnowflakeDbDataType.Fixed: param.Value = 10; break; - case SnowflakeDataType.Boolean: + case SnowflakeDbDataType.Boolean: param.Value = true; break; - case SnowflakeDataType.Date: + case SnowflakeDbDataType.Date: param.Value = DateTime.Now; break; - case SnowflakeDataType.Text: + case SnowflakeDbDataType.Text: param.Value = "thisIsAString"; break; - case SnowflakeDataType.TimestampLtz: + case SnowflakeDbDataType.TimestampLtz: param.Value = DateTimeOffset.Now; break; - case SnowflakeDataType.TimestampNtz: + case SnowflakeDbDataType.TimestampNtz: param.Value = DateTime.Now; break; - case SnowflakeDataType.TimestampTz: + case SnowflakeDbDataType.TimestampTz: param.Value = DateTimeOffset.Now; break; - case SnowflakeDataType.Time: + case SnowflakeDbDataType.Time: param.Value = DateTime.Now; break; - case SnowflakeDataType.Real: + case SnowflakeDbDataType.Real: param.Value = 25.3; break; @@ -460,9 +460,9 @@ public void TestBindValueWithSFDataType() Assert.AreEqual(1, rowsInserted); } // DB rejects query if param type is VARIANT, OBJECT or ARRAY - else if (!type.Equals(SnowflakeDataType.Variant) && - !type.Equals(SnowflakeDataType.Object) && - !type.Equals(SnowflakeDataType.Array)) + else if (!type.Equals(SnowflakeDbDataType.Variant) && + !type.Equals(SnowflakeDbDataType.Object) && + !type.Equals(SnowflakeDbDataType.Array)) { try { @@ -471,9 +471,9 @@ public void TestBindValueWithSFDataType() command.Parameters.Add(param); int rowsInserted = command.ExecuteNonQuery(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.UnsupportedSnowflakeTypeForParam, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.UnsupportedSnowflakeTypeForParam, e.SnowflakeError); } } } @@ -508,7 +508,7 @@ public void TestBindValueWithSFDataType() [Test] public void TestParameterCollection() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -535,7 +535,7 @@ public void TestParameterCollection() parameters.SetValue(p2, 1); parameters.SetValue(p3, 2); - ((SnowflakeParameterCollection)cmd.Parameters).AddRange(parameters); + ((SnowflakeDbParameterCollection)cmd.Parameters).AddRange(parameters); var target = new IDataParameter[15]; diff --git a/Snowflake.Data.Tests/SFConnectionIT.cs b/Snowflake.Data.Tests/SFConnectionIT.cs index 996faa1..fa2fc88 100644 --- a/Snowflake.Data.Tests/SFConnectionIT.cs +++ b/Snowflake.Data.Tests/SFConnectionIT.cs @@ -16,7 +16,7 @@ class SFConnectionIT : SFBaseTest [Test] public void TestBasicConnection() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -24,9 +24,9 @@ public void TestBasicConnection() Assert.AreEqual(120, conn.ConnectionTimeout); // Data source is empty string for now - Assert.AreEqual("", ((SnowflakeConnection)conn).DataSource); + Assert.AreEqual("", ((SnowflakeDbConnection)conn).DataSource); - var serverVersion = ((SnowflakeConnection)conn).ServerVersion; + var serverVersion = ((SnowflakeDbConnection)conn).ServerVersion; if (!string.Equals(serverVersion, "Dev")) { var versionElements = serverVersion.Split('.'); @@ -47,7 +47,7 @@ public void TestApplicationName() // Valid names foreach (var appName in validApplicationNames) { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.ConnectionString += $"application={appName}"; @@ -62,7 +62,7 @@ public void TestApplicationName() // Invalid names foreach (var appName in invalidApplicationNames) { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.ConnectionString += $"application={appName}"; @@ -71,7 +71,7 @@ public void TestApplicationName() conn.Open(); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { // Expected Assert.AreEqual("08006", e.SqlState); // Connection failure @@ -85,7 +85,7 @@ public void TestApplicationName() [Test] public void TestIncorrectUserOrPasswordBasicConnection() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = $"scheme={TestConfig.Protocol};host={TestConfig.Host};port={TestConfig.Port};" + $"account={TestConfig.Account};role={TestConfig.Role};db={TestConfig.Database};schema={TestConfig.Schema};warehouse={TestConfig.Warehouse};user={"unknown"};password={TestConfig.Password};"; @@ -96,7 +96,7 @@ public void TestIncorrectUserOrPasswordBasicConnection() conn.Open(); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { // Expected Assert.AreEqual("08006", e.SqlState); // Connection failure @@ -108,42 +108,42 @@ public void TestIncorrectUserOrPasswordBasicConnection() public void TestCrlCheckSwitchConnection() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString + ";INSECUREMODE=true"; conn.Open(); Assert.AreEqual(ConnectionState.Open, conn.State); } - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); Assert.AreEqual(ConnectionState.Open, conn.State); } - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString + ";INSECUREMODE=false"; conn.Open(); Assert.AreEqual(ConnectionState.Open, conn.State); } - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); Assert.AreEqual(ConnectionState.Open, conn.State); } - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString + ";INSECUREMODE=false"; conn.Open(); Assert.AreEqual(ConnectionState.Open, conn.State); } - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString + ";INSECUREMODE=true"; conn.Open(); @@ -156,7 +156,7 @@ public void TestConnectViaSecureString() { var connEntries = ConnectionString.Split(';'); var connectionStringWithoutPassword = ""; - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { var password = new System.Security.SecureString(); foreach (var entry in connEntries) @@ -205,9 +205,9 @@ public void TestLoginTimeout() conn.Open(); Assert.Fail("Timeout exception did not occur"); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.RequestTimeout, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.RequestTimeout, e.SnowflakeError); } stopwatch.Stop(); @@ -239,9 +239,9 @@ public async Task TestLoginTimeoutAsync() await conn.OpenAsync().ConfigureAwait(false); Assert.Fail("Connection did not timeout"); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.RequestTimeout, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.RequestTimeout, e.SnowflakeError); } stopwatch.Stop(); @@ -271,9 +271,9 @@ public void TestDefaultLoginTimeout() conn.Open(); Assert.Fail("Connection did not timeout"); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.RequestTimeout, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.RequestTimeout, e.SnowflakeError); stopwatch.Stop(); // Should timeout after the default timeout (120 sec) @@ -287,7 +287,7 @@ public void TestDefaultLoginTimeout() [Test] public void TestConnectionFailFast() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { // Just a way to get a 404 on the login request and make sure there are no retry var invalidConnectionString = "host=docs.microsoft.com;connection_timeout=0;account=testFailFast;user=testFailFast;password=testFailFast;"; @@ -300,9 +300,9 @@ public void TestConnectionFailFast() conn.Open(); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.InternalError, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.InternalError, e.SnowflakeError); } Assert.AreEqual(ConnectionState.Closed, conn.State); @@ -316,7 +316,7 @@ public void TestValidateDefaultParameters() $"account={TestConfig.Account};role={TestConfig.Role};db={TestConfig.Database};schema={TestConfig.Schema};warehouse={"WAREHOUSE_NEVER_EXISTS"};user={TestConfig.User};password={TestConfig.Password};"; // By default should validate parameters - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { try { @@ -324,14 +324,14 @@ public void TestValidateDefaultParameters() conn.Open(); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { Assert.AreEqual(390201, e.ErrorCode); } } // This should succeed - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = connectionString + ";VALIDATE_DEFAULT_PARAMETERS=false"; conn.Open(); @@ -349,9 +349,9 @@ public void TestInvalidConnectionString() "complete_invalid_string", }; - var expectedErrorCode = new[] { SnowflakeError.MissingConnectionProperty, SnowflakeError.InvalidConnectionString, SnowflakeError.InvalidConnectionString }; + var expectedErrorCode = new[] { SnowflakeDbError.MissingConnectionProperty, SnowflakeDbError.InvalidConnectionString, SnowflakeDbError.InvalidConnectionString }; - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { for (var i = 0; i < invalidStrings.Length; i++) { @@ -361,7 +361,7 @@ public void TestInvalidConnectionString() conn.Open(); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { Assert.AreEqual(expectedErrorCode[i], e.SnowflakeError); } @@ -372,7 +372,7 @@ public void TestInvalidConnectionString() [Test] public void TestUnknownConnectionProperty() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { // invalid propety will be ignored. conn.ConnectionString = ConnectionString + ";invalidProperty=invalidvalue;"; @@ -387,7 +387,7 @@ public void TestUnknownConnectionProperty() [IgnoreOnEnvIs("snowflake_cloud_env", new string[] { "AZURE", "GCP" })] public void TestSwitchDb() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; @@ -411,7 +411,7 @@ public void TestSwitchDb() [Test] public void TestConnectWithoutHost() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { var connStrFmt = "account={0};user={1};password={2}"; conn.ConnectionString = string.Format(connStrFmt, TestConfig.Account, @@ -429,7 +429,7 @@ public void TestConnectWithoutHost() [Test] public void TestConnectWithDifferentRole() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { var host = TestConfig.Host; if (string.IsNullOrEmpty(host)) @@ -464,7 +464,7 @@ public void TestConnectWithDifferentRole() [Test] public void TestConnectionDispose() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { // Setup conn.ConnectionString = ConnectionString; @@ -480,7 +480,7 @@ public void TestConnectionDispose() t1c1.ExecuteNonQuery(); } - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { // Previous connection would be disposed and // uncommitted txn would rollback at this point @@ -511,13 +511,13 @@ public void TestUnknownAuthenticator() { try { - var conn = new SnowflakeConnection() { ConnectionString = "scheme=http;host=test;port=8080;user=test;password=test;account=test;authenticator=" + wrongAuthenticator }; + var conn = new SnowflakeDbConnection() { ConnectionString = "scheme=http;host=test;port=8080;user=test;password=test;account=test;authenticator=" + wrongAuthenticator }; conn.Open(); Assert.Fail("Authentication of {0} should fail", wrongAuthenticator); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.UnknownAuthenticator, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.UnknownAuthenticator, e.SnowflakeError); } } } @@ -527,7 +527,7 @@ public void TestInValidOAuthTokenConnection() { try { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionStringWithoutAuth @@ -537,7 +537,7 @@ public void TestInValidOAuthTokenConnection() Assert.Fail(); } } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { // Invalid OAuth access token Assert.AreEqual(390303, e.ErrorCode); @@ -547,7 +547,7 @@ public void TestInValidOAuthTokenConnection() [Test] public void TestInvalidProxySettingFromConnectionString() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString + "connection_timeout=5;useProxy=true;proxyHost=Invalid;proxyPort=8080"; @@ -556,10 +556,10 @@ public void TestInvalidProxySettingFromConnectionString() conn.Open(); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { // Expected - Assert.AreEqual(SnowflakeError.RequestTimeout, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.RequestTimeout, e.SnowflakeError); } } } @@ -567,7 +567,7 @@ public void TestInvalidProxySettingFromConnectionString() [Test] public void TestUseProxyFalseWithInvalidProxyConnectionString() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString + ";useProxy=false;proxyHost=Invalid;proxyPort=8080"; @@ -579,7 +579,7 @@ public void TestUseProxyFalseWithInvalidProxyConnectionString() [Test] public void TestInvalidProxySettingWithByPassListFromConnectionString() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = $"{ConnectionString};useProxy=true;proxyHost=Invalid;proxyPort=8080;nonProxyHosts=*.foo.com %7C{TestConfig.Account}.snowflakecomputing.com|localhost"; conn.Open(); diff --git a/Snowflake.Data.Tests/SFConnectionITAsync.cs b/Snowflake.Data.Tests/SFConnectionITAsync.cs index 423685f..2b7cdc1 100644 --- a/Snowflake.Data.Tests/SFConnectionITAsync.cs +++ b/Snowflake.Data.Tests/SFConnectionITAsync.cs @@ -78,7 +78,7 @@ public void TestAsyncLoginTimeout() } catch (AggregateException e) { - Assert.AreEqual(SnowflakeError.RequestTimeout, ((SnowflakeException)e.InnerException).SnowflakeError); + Assert.AreEqual(SnowflakeDbError.RequestTimeout, ((SnowflakeDbException)e.InnerException).SnowflakeError); } stopwatch.Stop(); @@ -111,7 +111,7 @@ public void TestAsyncDefaultLoginTimeout() } catch (AggregateException e) { - Assert.AreEqual(SnowflakeError.RequestTimeout, ((SnowflakeException)e.InnerException).SnowflakeError); + Assert.AreEqual(SnowflakeDbError.RequestTimeout, ((SnowflakeDbException)e.InnerException).SnowflakeError); } stopwatch.Stop(); @@ -128,7 +128,7 @@ public void TestAsyncDefaultLoginTimeout() [Test] public void TestAsyncConnectionFailFast() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { // Just a way to get a 404 on the login request and make sure there are no retry var invalidConnectionString = "host=docs.microsoft.com;connection_timeout=0;account=testFailFast;user=testFailFast;password=testFailFast;"; @@ -146,7 +146,7 @@ public void TestAsyncConnectionFailFast() } catch (AggregateException e) { - Assert.AreEqual(SnowflakeError.InternalError, ((SnowflakeException)e.InnerException).SnowflakeError); + Assert.AreEqual(SnowflakeDbError.InternalError, ((SnowflakeDbException)e.InnerException).SnowflakeError); } Assert.AreEqual(ConnectionState.Closed, conn.State); @@ -161,7 +161,7 @@ public void TestCloseAsync() // https://docs.microsoft.com/en-us/dotnet/api/system.data.common.dbconnection.closeasync // An application can call Close or CloseAsync more than one time. // No exception is generated. - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; Assert.AreEqual(conn.State, ConnectionState.Closed); @@ -209,7 +209,7 @@ public async Task TestCloseAsyncFailure() await conn.CloseAsync(new CancellationTokenSource().Token); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { Assert.AreEqual(MockCloseSessionException.SESSION_CLOSE_ERROR, e.ErrorCode); } diff --git a/Snowflake.Data.Tests/SFDataConverterTest.cs b/Snowflake.Data.Tests/SFDataConverterTest.cs index 93ae47c..5c38ad3 100755 --- a/Snowflake.Data.Tests/SFDataConverterTest.cs +++ b/Snowflake.Data.Tests/SFDataConverterTest.cs @@ -37,7 +37,7 @@ public void TestConvertBindToSFValFinlandLocale() [TestCase("anything else", false)] public void TestConvertBoolean(string inputBooleanString, bool expected) { - var actual = SFDataConverter.ConvertToCSharpVal(inputBooleanString, SnowflakeDataType.Boolean, typeof(bool)); + var actual = SFDataConverter.ConvertToCSharpVal(inputBooleanString, SnowflakeDbDataType.Boolean, typeof(bool)); Assert.AreEqual(expected, actual); } @@ -62,7 +62,7 @@ public void TestConvertDatetime(string inputTimeStr) var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var tickDiff = inputTime.Ticks - unixEpoch.Ticks; var inputStringAsItWasFromDatabase = (tickDiff / 10000000.0m).ToString(CultureInfo.InvariantCulture); - var result = SFDataConverter.ConvertToCSharpVal(inputStringAsItWasFromDatabase, SnowflakeDataType.TimestampNtz, typeof(DateTime)); + var result = SFDataConverter.ConvertToCSharpVal(inputStringAsItWasFromDatabase, SnowflakeDbDataType.TimestampNtz, typeof(DateTime)); Assert.AreEqual(inputTime, result); } @@ -94,7 +94,7 @@ public void TestConvertTimeSpan(string inputTimeStr) inputStringAsItComesBackFromDatabase += inputTimeStr.Substring(8, inputTimeStr.Length - 8); // Run the conversion - var result = SFDataConverter.ConvertToCSharpVal(inputStringAsItComesBackFromDatabase, SnowflakeDataType.Time, typeof(TimeSpan)); + var result = SFDataConverter.ConvertToCSharpVal(inputStringAsItComesBackFromDatabase, SnowflakeDbDataType.Time, typeof(TimeSpan)); // Verify the result Assert.AreEqual(expected, result); @@ -145,7 +145,7 @@ static void InternalTestConvertDate(DateTime dtExpected, DateTime testValue) [TestCase("999999999999999999")] public void TestConvertToInt64(string s) { - var actual = (Int64)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(Int64)); + var actual = (Int64)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(Int64)); var expected = Convert.ToInt64(s); Assert.AreEqual(expected, actual); } @@ -157,7 +157,7 @@ public void TestConvertToInt64(string s) [TestCase("0")] public void TestConvertToInt32(string s) { - var actual = (Int32)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(Int32)); + var actual = (Int32)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(Int32)); var expected = Convert.ToInt32(s); Assert.AreEqual(expected, actual); } @@ -169,7 +169,7 @@ public void TestConvertToInt32(string s) [TestCase("0")] public void TestConvertToInt16(string s) { - var actual = (Int16)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(Int16)); + var actual = (Int16)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(Int16)); var expected = Convert.ToInt16(s); Assert.AreEqual(expected, actual); } @@ -179,7 +179,7 @@ public void TestConvertToInt16(string s) [TestCase("0")] public void TestConvertToByte(string s) { - var actual = (byte)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(byte)); + var actual = (byte)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(byte)); var expected = Convert.ToByte(s); Assert.AreEqual(expected, actual); } @@ -189,7 +189,7 @@ public void TestConvertToByte(string s) [TestCase("-1")] public void TestOverflowByte(string s) { - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(byte))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(byte))); } [Test] @@ -197,7 +197,7 @@ public void TestOverflowByte(string s) [TestCase("-32769")] public void TestOverflowInt16(string s) { - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(Int16))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(Int16))); } [Test] @@ -205,7 +205,7 @@ public void TestOverflowInt16(string s) [TestCase("-2147483649")] public void TestOverflowInt32(string s) { - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(Int32))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(Int32))); } [Test] @@ -213,7 +213,7 @@ public void TestOverflowInt32(string s) [TestCase("-9223372036854775809")] public void TestOverflowInt64(string s) { - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(Int64))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(Int64))); } [Test] @@ -231,7 +231,7 @@ public void TestOverflowInt64(string s) [TestCase("79228162514264337593543950334.9999999999999999999999999999")] //A Decimal object has 29 digits of precision. If s represents a number that has more than 29 digits, but has a fractional part and is within the range of MaxValue and MinValue, the number is rounded public void TestConvertToDecimal(string s) { - var actual = (decimal)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(decimal)); + var actual = (decimal)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(decimal)); var expected = Convert.ToDecimal(s, CultureInfo.InvariantCulture); Assert.AreEqual(expected, actual); @@ -243,7 +243,7 @@ public void TestConvertToDecimal(string s) [TestCase("79228162514264337593543950335.9999999999999999999999999999")] // The scaling factor range is 0 to 28. Scaling factor = 29 and fractional part > MaxValue public void TestOverflowDecimal(string s) { - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(decimal))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(decimal))); } [Test] @@ -260,12 +260,12 @@ public void TestOverflowDecimal(string s) [TestCase("NaN")] public void TestConvertToFloat(string s) { - var actualDouble = (double)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(double)); + var actualDouble = (double)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(double)); var expectedDoulbe = Convert.ToDouble(s, CultureInfo.InvariantCulture); Assert.AreEqual(actualDouble, expectedDoulbe); - var actualFloat = (float)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(float)); + var actualFloat = (float)SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(float)); var expectedFloat = Convert.ToSingle(s, CultureInfo.InvariantCulture); Assert.AreEqual(expectedFloat, actualFloat); @@ -283,18 +283,18 @@ public void TestConvertToFloat(string s) [TestCase("NaN")] public void TestInvalidConversionInvalidInt(string s) { - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(Int32))); - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(Int64))); - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(Int16))); - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(byte))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(Int32))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(Int64))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(Int16))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(byte))); } [Test] [TestCase("thisIsNotAValidValue")] public void TestInvalidConversionInvalidFloat(string s) { - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(float))); - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(double))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(float))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(double))); } [Test] @@ -306,6 +306,6 @@ public void TestInvalidConversionInvalidFloat(string s) [TestCase("NaN")] public void TestInvalidConversionInvalidDecimal(string s) { - Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDataType.Fixed, typeof(decimal))); + Assert.Throws(() => SFDataConverter.ConvertToCSharpVal(s, SnowflakeDbDataType.Fixed, typeof(decimal))); } } diff --git a/Snowflake.Data.Tests/SFDbAdaptorIT.cs b/Snowflake.Data.Tests/SFDbAdaptorIT.cs index 435d8e6..df95345 100755 --- a/Snowflake.Data.Tests/SFDbAdaptorIT.cs +++ b/Snowflake.Data.Tests/SFDbAdaptorIT.cs @@ -15,12 +15,12 @@ class SFDbAdaptorIT : SFBaseTest public void TestSelectStatement() { DataSet ds = new DataSet("ds"); - using (SnowflakeConnection conn = new SnowflakeConnection()) + using (SnowflakeDbConnection conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); - IDbDataAdapter adaptor = new SnowlfakeDataAdapter("select 1 as col1, 2 AS col2", conn); + IDbDataAdapter adaptor = new SnowlfakeDbDataAdapter("select 1 as col1, 2 AS col2", conn); adaptor.Fill(ds); conn.Close(); } diff --git a/Snowflake.Data.Tests/SFDbCommandIT.cs b/Snowflake.Data.Tests/SFDbCommandIT.cs index 1f15872..ea038d3 100755 --- a/Snowflake.Data.Tests/SFDbCommandIT.cs +++ b/Snowflake.Data.Tests/SFDbCommandIT.cs @@ -10,91 +10,91 @@ namespace Tortuga.Data.Snowflake.Tests; [TestFixture] class SFDbCommandIT : SFBaseTest { - [Test] - public void TestSimpleCommand() - { - using (var conn = new SnowflakeConnection()) - { - conn.ConnectionString = ConnectionString; - - conn.Open(); - IDbCommand cmd = conn.CreateCommand(); - cmd.CommandText = "select 1"; - - // command type can only be text, stored procedure are not supported. - Assert.AreEqual(CommandType.Text, cmd.CommandType); - try - { - cmd.CommandType = CommandType.StoredProcedure; - Assert.Fail(); - } - catch (NotSupportedException) - { - } - - Assert.AreEqual(UpdateRowSource.None, cmd.UpdatedRowSource); - try - { - cmd.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord; - Assert.Fail(); - } - catch (NotSupportedException) - { - } - - Assert.AreSame(conn, cmd.Connection); - try - { - cmd.Connection = null; - Assert.Fail(); - } - catch (InvalidOperationException) - { - } - - Assert.IsFalse(((SnowflakeCommand)cmd).DesignTimeVisible); - try - { - ((SnowflakeCommand)cmd).DesignTimeVisible = true; - Assert.Fail(); - } - catch (NotSupportedException) - { - } - - object val = cmd.ExecuteScalar(); - Assert.AreEqual(1L, (long)val); - - conn.Close(); - } - } - - [Test] - // Skip SimpleLargeResultSet test on GCP as it will fail - // on row 8192 consistently on Appveyor. - [IgnoreOnEnvIs("snowflake_cloud_env", new string[] { "GCP" })] - public void TestSimpleLargeResultSet() - { - using (var conn = new SnowflakeConnection()) - { - conn.ConnectionString = ConnectionString; - - conn.Open(); - - IDbCommand cmd = conn.CreateCommand(); - cmd.CommandText = "select seq4(), uniform(1, 10, 42) from table(generator(rowcount => 1000000)) v order by 1"; - IDataReader reader = cmd.ExecuteReader(); - int counter = 0; - while (reader.Read()) - { - Assert.AreEqual(counter.ToString(), reader.GetString(0)); - counter++; - } - conn.Close(); - } - } - - /* + [Test] + public void TestSimpleCommand() + { + using (var conn = new SnowflakeDbConnection()) + { + conn.ConnectionString = ConnectionString; + + conn.Open(); + IDbCommand cmd = conn.CreateCommand(); + cmd.CommandText = "select 1"; + + // command type can only be text, stored procedure are not supported. + Assert.AreEqual(CommandType.Text, cmd.CommandType); + try + { + cmd.CommandType = CommandType.StoredProcedure; + Assert.Fail(); + } + catch (NotSupportedException) + { + } + + Assert.AreEqual(UpdateRowSource.None, cmd.UpdatedRowSource); + try + { + cmd.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord; + Assert.Fail(); + } + catch (NotSupportedException) + { + } + + Assert.AreSame(conn, cmd.Connection); + try + { + cmd.Connection = null; + Assert.Fail(); + } + catch (InvalidOperationException) + { + } + + Assert.IsFalse(((SnowflakeDbCommand)cmd).DesignTimeVisible); + try + { + ((SnowflakeDbCommand)cmd).DesignTimeVisible = true; + Assert.Fail(); + } + catch (NotSupportedException) + { + } + + object val = cmd.ExecuteScalar(); + Assert.AreEqual(1L, (long)val); + + conn.Close(); + } + } + + [Test] + // Skip SimpleLargeResultSet test on GCP as it will fail + // on row 8192 consistently on Appveyor. + [IgnoreOnEnvIs("snowflake_cloud_env", new string[] { "GCP" })] + public void TestSimpleLargeResultSet() + { + using (var conn = new SnowflakeDbConnection()) + { + conn.ConnectionString = ConnectionString; + + conn.Open(); + + IDbCommand cmd = conn.CreateCommand(); + cmd.CommandText = "select seq4(), uniform(1, 10, 42) from table(generator(rowcount => 1000000)) v order by 1"; + IDataReader reader = cmd.ExecuteReader(); + int counter = 0; + while (reader.Read()) + { + Assert.AreEqual(counter.ToString(), reader.GetString(0)); + counter++; + } + conn.Close(); + } + } + + /* * Disabled to make sure that configuration changes does not cause problems with appveyor * [Test] @@ -148,246 +148,246 @@ public void TestUseV2ChunkDownloader() } */ - [Test] - public void TestDataSourceError() - { - using (var conn = new SnowflakeConnection()) - { - conn.ConnectionString = ConnectionString; - - conn.Open(); - - IDbCommand cmd = conn.CreateCommand(); - cmd.CommandText = "select * from table_not_exists"; - try - { - IDataReader reader = cmd.ExecuteReader(); - Assert.Fail(); - } - catch (SnowflakeException e) - { - Assert.AreEqual(2003, e.ErrorCode); - Assert.AreNotEqual("", e.QueryId); - } - - conn.Close(); - } - } - - [Test] - public void TestCancelQuery() - { - using (var conn = new SnowflakeConnection()) - { - conn.ConnectionString = ConnectionString; - - conn.Open(); - - IDbCommand cmd = conn.CreateCommand(); - cmd.CommandText = "select count(seq4()) from table(generator(timelimit => 20)) v"; - Task executionThread = Task.Run(() => - { - try - { - cmd.ExecuteScalar(); - Assert.Fail(); - } - catch (SnowflakeException e) - { - // 604 is error code from server meaning query has been canceled - if (604 != e.ErrorCode) - { - Assert.Fail($"Unexpected error code {e.ErrorCode} for {e.Message}"); - } - } - }); - - Thread.Sleep(8000); - cmd.Cancel(); - - try - { - executionThread.Wait(); - } - catch (AggregateException e) - { - if (e.InnerException.GetType() != typeof(NUnit.Framework.AssertionException)) - { - Assert.AreEqual( - "System.Threading.Tasks.TaskCanceledException", - e.InnerException.GetType().ToString()); - } - else - { - // Unexpected exception - throw; - } - } - - conn.Close(); - } - } - - [Test] - public void TestTransaction() - { - using (var conn = new SnowflakeConnection()) - { - conn.ConnectionString = ConnectionString; - - conn.Open(); - - try - { - conn.BeginTransaction(IsolationLevel.ReadUncommitted); - Assert.Fail(); - } - catch (ArgumentOutOfRangeException) - { - } - - IDbTransaction tran = conn.BeginTransaction(IsolationLevel.ReadCommitted); - - IDbCommand command = conn.CreateCommand(); - command.Transaction = tran; - command.CommandText = "create or replace table testtransaction(cola string)"; - command.ExecuteNonQuery(); - command.Transaction.Commit(); - - command.CommandText = "show tables like 'testtransaction'"; - IDataReader reader = command.ExecuteReader(); - Assert.IsTrue(reader.Read()); - Assert.IsFalse(reader.Read()); - - // start another transaction to test rollback - tran = conn.BeginTransaction(IsolationLevel.ReadCommitted); - command.Transaction = tran; - command.CommandText = "insert into testtransaction values('test')"; - - command.ExecuteNonQuery(); - command.CommandText = "select * from testtransaction"; - reader = command.ExecuteReader(); - Assert.IsTrue(reader.Read()); - Assert.AreEqual("test", reader.GetString(0)); - command.Transaction.Rollback(); - - // no value will be in table since it has been rollbacked - command.CommandText = "select * from testtransaction"; - reader = command.ExecuteReader(); - Assert.IsFalse(reader.Read()); - - conn.Close(); - } - } - - [Test] - public void TestRowsAffected() - { - String[] testCommands = - { - "create or replace table test_rows_affected(cola int, colb string)", - "insert into test_rows_affected values(1, 'a'),(2, 'b')", - "merge into test_rows_affected using (select 1 as cola, 'c' as colb) m on " + - "test_rows_affected.cola = m.cola when matched then update set test_rows_affected.colb='update' " + - "when not matched then insert (cola, colb) values (3, 'd')", - "drop table if exists test_rows_affected" - }; - - int[] expectedResult = - { - 0, 2, 1, 0 - }; - - using (var conn = new SnowflakeConnection()) - { - conn.ConnectionString = ConnectionString; - - conn.Open(); - - using (IDbCommand command = conn.CreateCommand()) - { - int rowsAffected = -1; - for (int i = 0; i < testCommands.Length; i++) - { - command.CommandText = testCommands[i]; - rowsAffected = command.ExecuteNonQuery(); - - Assert.AreEqual(expectedResult[i], rowsAffected); - } - } - conn.Close(); - } - } - - [Test] - public void TestExecuteScalarNull() - { - using (var conn = new SnowflakeConnection()) - { - conn.ConnectionString = ConnectionString; - conn.Open(); - - using (IDbCommand command = conn.CreateCommand()) - { - command.CommandText = "select 1 where 2 > 3"; - object val = command.ExecuteScalar(); - - Assert.AreEqual(DBNull.Value, val); - } - conn.Close(); - } - } - - [Test] - public void TestCreateCommandBeforeOpeningConnection() - { - using (var conn = new SnowflakeConnection()) - { - conn.ConnectionString = ConnectionString; - - using (var command = conn.CreateCommand()) - { - conn.Open(); - command.CommandText = "select 1"; - Assert.DoesNotThrow(() => command.ExecuteNonQuery()); - } - } - } - - [Test] - public void TestRowsAffectedUnload() - { - using (var conn = new SnowflakeConnection()) - { - conn.ConnectionString = ConnectionString; - conn.Open(); - - using (IDbCommand command = conn.CreateCommand()) - { - command.CommandText = "create or replace table test_rows_affected_unload(c1 number)"; - command.ExecuteNonQuery(); - - command.CommandText = "insert into test_rows_affected_unload values(1), (2), (3), (4), (5), (6)"; - command.ExecuteNonQuery(); - - command.CommandText = "drop stage if exists my_unload_stage"; - command.ExecuteNonQuery(); - - command.CommandText = "create stage if not exists my_unload_stage"; - command.ExecuteNonQuery(); - - command.CommandText = "copy into @my_unload_stage/unload/ from test_rows_affected_unload;"; - int affected = command.ExecuteNonQuery(); - - Assert.AreEqual(6, affected); - - command.CommandText = "drop stage if exists my_unload_stage"; - command.ExecuteNonQuery(); - - command.CommandText = "drop table if exists test_rows_affected_unload"; - command.ExecuteNonQuery(); - } - conn.Close(); - } - } + [Test] + public void TestDataSourceError() + { + using (var conn = new SnowflakeDbConnection()) + { + conn.ConnectionString = ConnectionString; + + conn.Open(); + + IDbCommand cmd = conn.CreateCommand(); + cmd.CommandText = "select * from table_not_exists"; + try + { + IDataReader reader = cmd.ExecuteReader(); + Assert.Fail(); + } + catch (SnowflakeDbException e) + { + Assert.AreEqual(2003, e.ErrorCode); + Assert.AreNotEqual("", e.QueryId); + } + + conn.Close(); + } + } + + [Test] + public void TestCancelQuery() + { + using (var conn = new SnowflakeDbConnection()) + { + conn.ConnectionString = ConnectionString; + + conn.Open(); + + IDbCommand cmd = conn.CreateCommand(); + cmd.CommandText = "select count(seq4()) from table(generator(timelimit => 20)) v"; + Task executionThread = Task.Run(() => + { + try + { + cmd.ExecuteScalar(); + Assert.Fail(); + } + catch (SnowflakeDbException e) + { + // 604 is error code from server meaning query has been canceled + if (604 != e.ErrorCode) + { + Assert.Fail($"Unexpected error code {e.ErrorCode} for {e.Message}"); + } + } + }); + + Thread.Sleep(8000); + cmd.Cancel(); + + try + { + executionThread.Wait(); + } + catch (AggregateException e) + { + if (e.InnerException.GetType() != typeof(NUnit.Framework.AssertionException)) + { + Assert.AreEqual( + "System.Threading.Tasks.TaskCanceledException", + e.InnerException.GetType().ToString()); + } + else + { + // Unexpected exception + throw; + } + } + + conn.Close(); + } + } + + [Test] + public void TestTransaction() + { + using (var conn = new SnowflakeDbConnection()) + { + conn.ConnectionString = ConnectionString; + + conn.Open(); + + try + { + conn.BeginTransaction(IsolationLevel.ReadUncommitted); + Assert.Fail(); + } + catch (ArgumentOutOfRangeException) + { + } + + IDbTransaction tran = conn.BeginTransaction(IsolationLevel.ReadCommitted); + + IDbCommand command = conn.CreateCommand(); + command.Transaction = tran; + command.CommandText = "create or replace table testtransaction(cola string)"; + command.ExecuteNonQuery(); + command.Transaction.Commit(); + + command.CommandText = "show tables like 'testtransaction'"; + IDataReader reader = command.ExecuteReader(); + Assert.IsTrue(reader.Read()); + Assert.IsFalse(reader.Read()); + + // start another transaction to test rollback + tran = conn.BeginTransaction(IsolationLevel.ReadCommitted); + command.Transaction = tran; + command.CommandText = "insert into testtransaction values('test')"; + + command.ExecuteNonQuery(); + command.CommandText = "select * from testtransaction"; + reader = command.ExecuteReader(); + Assert.IsTrue(reader.Read()); + Assert.AreEqual("test", reader.GetString(0)); + command.Transaction.Rollback(); + + // no value will be in table since it has been rollbacked + command.CommandText = "select * from testtransaction"; + reader = command.ExecuteReader(); + Assert.IsFalse(reader.Read()); + + conn.Close(); + } + } + + [Test] + public void TestRowsAffected() + { + String[] testCommands = + { + "create or replace table test_rows_affected(cola int, colb string)", + "insert into test_rows_affected values(1, 'a'),(2, 'b')", + "merge into test_rows_affected using (select 1 as cola, 'c' as colb) m on " + + "test_rows_affected.cola = m.cola when matched then update set test_rows_affected.colb='update' " + + "when not matched then insert (cola, colb) values (3, 'd')", + "drop table if exists test_rows_affected" + }; + + int[] expectedResult = + { + 0, 2, 1, 0 + }; + + using (var conn = new SnowflakeDbConnection()) + { + conn.ConnectionString = ConnectionString; + + conn.Open(); + + using (IDbCommand command = conn.CreateCommand()) + { + int rowsAffected = -1; + for (int i = 0; i < testCommands.Length; i++) + { + command.CommandText = testCommands[i]; + rowsAffected = command.ExecuteNonQuery(); + + Assert.AreEqual(expectedResult[i], rowsAffected); + } + } + conn.Close(); + } + } + + [Test] + public void TestExecuteScalarNull() + { + using (var conn = new SnowflakeDbConnection()) + { + conn.ConnectionString = ConnectionString; + conn.Open(); + + using (IDbCommand command = conn.CreateCommand()) + { + command.CommandText = "select 1 where 2 > 3"; + object val = command.ExecuteScalar(); + + Assert.AreEqual(DBNull.Value, val); + } + conn.Close(); + } + } + + [Test] + public void TestCreateCommandBeforeOpeningConnection() + { + using (var conn = new SnowflakeDbConnection()) + { + conn.ConnectionString = ConnectionString; + + using (var command = conn.CreateCommand()) + { + conn.Open(); + command.CommandText = "select 1"; + Assert.DoesNotThrow(() => command.ExecuteNonQuery()); + } + } + } + + [Test] + public void TestRowsAffectedUnload() + { + using (var conn = new SnowflakeDbConnection()) + { + conn.ConnectionString = ConnectionString; + conn.Open(); + + using (IDbCommand command = conn.CreateCommand()) + { + command.CommandText = "create or replace table test_rows_affected_unload(c1 number)"; + command.ExecuteNonQuery(); + + command.CommandText = "insert into test_rows_affected_unload values(1), (2), (3), (4), (5), (6)"; + command.ExecuteNonQuery(); + + command.CommandText = "drop stage if exists my_unload_stage"; + command.ExecuteNonQuery(); + + command.CommandText = "create stage if not exists my_unload_stage"; + command.ExecuteNonQuery(); + + command.CommandText = "copy into @my_unload_stage/unload/ from test_rows_affected_unload;"; + int affected = command.ExecuteNonQuery(); + + Assert.AreEqual(6, affected); + + command.CommandText = "drop stage if exists my_unload_stage"; + command.ExecuteNonQuery(); + + command.CommandText = "drop table if exists test_rows_affected_unload"; + command.ExecuteNonQuery(); + } + conn.Close(); + } + } } diff --git a/Snowflake.Data.Tests/SFDbCommandITAsync.cs b/Snowflake.Data.Tests/SFDbCommandITAsync.cs index 256127d..a4a0d0b 100644 --- a/Snowflake.Data.Tests/SFDbCommandITAsync.cs +++ b/Snowflake.Data.Tests/SFDbCommandITAsync.cs @@ -14,7 +14,7 @@ class SFDbCommandITAsync : SFBaseTestAsync [Test] public void TestExecAsyncAPI() { - using (DbConnection conn = new SnowflakeConnection()) + using (DbConnection conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; @@ -55,7 +55,7 @@ public void TestCancelExecuteAsync() { CancellationTokenSource externalCancel = new CancellationTokenSource(TimeSpan.FromSeconds(8)); - using (DbConnection conn = new SnowflakeConnection()) + using (DbConnection conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; diff --git a/Snowflake.Data.Tests/SFDbCommandITSlow.cs b/Snowflake.Data.Tests/SFDbCommandITSlow.cs index 5af4ad6..c0e7ad8 100644 --- a/Snowflake.Data.Tests/SFDbCommandITSlow.cs +++ b/Snowflake.Data.Tests/SFDbCommandITSlow.cs @@ -13,7 +13,7 @@ class SFDbCommandITSlow : SFBaseTest [Test] public void TestLongRunningQuery() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; @@ -32,7 +32,7 @@ public void TestLongRunningQuery() [Test] public void TestRowsAffectedOverflowInt() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); diff --git a/Snowflake.Data.Tests/SFDbDataReaderIT.cs b/Snowflake.Data.Tests/SFDbDataReaderIT.cs index 379060f..6313259 100755 --- a/Snowflake.Data.Tests/SFDbDataReaderIT.cs +++ b/Snowflake.Data.Tests/SFDbDataReaderIT.cs @@ -16,7 +16,7 @@ class SFDbDataReaderIT : SFBaseTest [Test] public void TestRecordsAffected() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -48,7 +48,7 @@ public void TestRecordsAffected() [Test] public void TestGetNumber() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -112,7 +112,7 @@ public void TestGetNumber() [Test] public void TestGetFloat() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -173,7 +173,7 @@ public void TestGetFloat() [TestCase("1900-09-03 00:00:00.0000000")] public void TestGetDate(string inputTimeStr) { - TestGetDateAndOrTime(inputTimeStr, null, SnowflakeDataType.Date); + TestGetDateAndOrTime(inputTimeStr, null, SnowflakeDbDataType.Date); } [Test] @@ -189,7 +189,7 @@ public void TestGetDate(string inputTimeStr) [TestCase("1900-09-03 12:12:12.1212121", 1)] public void TestGetTime(string inputTimeStr, int? precision) { - TestGetDateAndOrTime(inputTimeStr, precision, SnowflakeDataType.Time); + TestGetDateAndOrTime(inputTimeStr, precision, SnowflakeDbDataType.Time); } [Test] @@ -209,7 +209,7 @@ public void TestGetTime(string inputTimeStr, int? precision) [TestCase("23:59:59.123456789")] public void TestGetTimeSpan(string inputTimeStr) { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -233,7 +233,7 @@ public void TestGetTimeSpan(string inputTimeStr) // For time, we getDateTime on the column and ignore date part var dateTimeTime = reader.GetDateTime(0); - var timeSpanTime = ((SnowflakeDataReader)reader).GetTimeSpan(0); + var timeSpanTime = ((SnowflakeDbDataReader)reader).GetTimeSpan(0); reader.Close(); // The expected result. Timespan precision only goes up to 7 digits @@ -256,7 +256,7 @@ public void TestGetTimeSpan(string inputTimeStr) public void TestGetTimeSpanError() { // Only Time data can be retrieved using GetTimeSpan, other type will fail - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -295,12 +295,12 @@ public void TestGetTimeSpanError() { try { - ((SnowflakeDataReader)reader).GetTimeSpan(i); + ((SnowflakeDbDataReader)reader).GetTimeSpan(i); Assert.Fail("Data should not be converted to TIME"); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.InvalidDataConversion, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.InvalidDataConversion, e.SnowflakeError); } } @@ -309,7 +309,7 @@ public void TestGetTimeSpanError() try { - ((SnowflakeDataReader)reader).GetTimeSpan(12); + ((SnowflakeDbDataReader)reader).GetTimeSpan(12); Assert.Fail("TimeSpan is not nullable"); } catch (InvalidCastException) @@ -318,7 +318,7 @@ public void TestGetTimeSpanError() } // Valid time column - var timeSpanTime = ((SnowflakeDataReader)reader).GetTimeSpan(13); + var timeSpanTime = ((SnowflakeDbDataReader)reader).GetTimeSpan(13); reader.Close(); @@ -329,20 +329,20 @@ public void TestGetTimeSpanError() } } - private void TestGetDateAndOrTime(string inputTimeStr, int? precision, SnowflakeDataType dataType) + private void TestGetDateAndOrTime(string inputTimeStr, int? precision, SnowflakeDbDataType dataType) { // Can't use DateTime object as test case, must parse. DateTime inputTime; if (inputTimeStr == null) { - inputTime = dataType == SnowflakeDataType.Date ? DateTime.Today : DateTime.Now; + inputTime = dataType == SnowflakeDbDataType.Date ? DateTime.Today : DateTime.Now; } else { inputTime = DateTime.ParseExact(inputTimeStr, "yyyy-MM-dd HH:mm:ss.fffffff", CultureInfo.InvariantCulture); } - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -360,17 +360,17 @@ private void TestGetDateAndOrTime(string inputTimeStr, int? precision, Snowflake p1.Value = inputTime; switch (dataType) { - case SnowflakeDataType.Time: + case SnowflakeDbDataType.Time: p1.DbType = DbType.Time; break; - case SnowflakeDataType.Date: + case SnowflakeDbDataType.Date: p1.DbType = DbType.Date; break; - case SnowflakeDataType.TimestampLtz: - case SnowflakeDataType.TimestampTz: - case SnowflakeDataType.TimestampNtz: + case SnowflakeDbDataType.TimestampLtz: + case SnowflakeDbDataType.TimestampTz: + case SnowflakeDbDataType.TimestampNtz: p1.DbType = DbType.DateTime; break; } @@ -388,19 +388,19 @@ private void TestGetDateAndOrTime(string inputTimeStr, int? precision, Snowflake // For time, we getDateTime on the column and ignore date part var actualTime = reader.GetDateTime(0); - if (dataType == SnowflakeDataType.Date) + if (dataType == SnowflakeDbDataType.Date) { Assert.AreEqual(inputTime.Date, reader.GetDateTime(0)); Assert.AreEqual(inputTime.Date.ToString("yyyy-MM-dd"), reader.GetString(0)); } - if (dataType != SnowflakeDataType.Date) + if (dataType != SnowflakeDbDataType.Date) { var inputTimeTicksOfTheDay = inputTime.Ticks - inputTime.Date.Ticks; var actualTimeTicksOfTheDay = actualTime.Ticks - actualTime.Date.Ticks; var allowedPrecisionLossInTicks = precision < 7 ? Math.Pow(10, (double)(7 - precision)) - 1 : 0d; Assert.AreEqual(inputTimeTicksOfTheDay, actualTimeTicksOfTheDay, allowedPrecisionLossInTicks); } - if (dataType == SnowflakeDataType.TimestampNtz) + if (dataType == SnowflakeDbDataType.TimestampNtz) { if (precision == 9) { @@ -439,13 +439,13 @@ private void TestGetDateAndOrTime(string inputTimeStr, int? precision, Snowflake [TestCase("1900-09-03 12:12:12.0000000", 1)] public void TestGetTimestampNTZ(string inputTimeStr, int? precision) { - TestGetDateAndOrTime(inputTimeStr, precision, SnowflakeDataType.TimestampNtz); + TestGetDateAndOrTime(inputTimeStr, precision, SnowflakeDbDataType.TimestampNtz); } [Test] public void TestGetTimestampTZ() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -489,7 +489,7 @@ public void TestGetTimestampTZ() [Test] public void TestGetTimestampLTZ() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -504,11 +504,11 @@ public void TestGetTimestampLTZ() var insertCommand = "insert into testgettimestampltz values (?)"; cmd.CommandText = insertCommand; - var p1 = (SnowflakeParameter)cmd.CreateParameter(); + var p1 = (SnowflakeDbParameter)cmd.CreateParameter(); p1.ParameterName = "1"; p1.Value = now; p1.DbType = DbType.DateTimeOffset; - p1.SFDataType = SnowflakeDataType.TimestampLtz; + p1.SFDataType = SnowflakeDbDataType.TimestampLtz; cmd.Parameters.Add(p1); count = cmd.ExecuteNonQuery(); @@ -534,7 +534,7 @@ public void TestGetTimestampLTZ() [Test] public void TestGetBoolean() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -574,7 +574,7 @@ public void TestGetBoolean() [Test] public void TestGetBinary() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -718,7 +718,7 @@ public void TestGetBinary() [Test] public void TestGetChars() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -863,7 +863,7 @@ public void TestGetChars() [Test] public void TestGetStream() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -937,7 +937,7 @@ public void TestGetStream() [Test] public void TestGetValueIndexOutOfBound() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -953,9 +953,9 @@ public void TestGetValueIndexOutOfBound() reader.GetInt16(-1); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.ColumnIndexOutOfBound, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.ColumnIndexOutOfBound, e.SnowflakeError); } try @@ -963,9 +963,9 @@ public void TestGetValueIndexOutOfBound() reader.GetInt16(1); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.ColumnIndexOutOfBound, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.ColumnIndexOutOfBound, e.SnowflakeError); } reader.Close(); @@ -976,7 +976,7 @@ public void TestGetValueIndexOutOfBound() [Test] public void TestBasicDataReader() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -988,7 +988,7 @@ public void TestBasicDataReader() { Assert.AreEqual(2, reader.FieldCount); Assert.AreEqual(0, reader.Depth); - Assert.IsTrue(((SnowflakeDataReader)reader).HasRows); + Assert.IsTrue(((SnowflakeDbDataReader)reader).HasRows); Assert.IsFalse(reader.IsClosed); Assert.AreEqual("COLONE", reader.GetName(0)); Assert.AreEqual("COLTWO", reader.GetName(1)); @@ -1014,9 +1014,9 @@ public void TestBasicDataReader() reader.Read(); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.DataReaderAlreadyClosed, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.DataReaderAlreadyClosed, e.SnowflakeError); } try @@ -1024,9 +1024,9 @@ public void TestBasicDataReader() reader.GetInt16(0); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.DataReaderAlreadyClosed, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.DataReaderAlreadyClosed, e.SnowflakeError); } } } @@ -1038,7 +1038,7 @@ public void TestBasicDataReader() [Test] public void TestReadOutNullVal() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -1074,7 +1074,7 @@ public void TestReadOutNullVal() [Test] public void TestGetGuid() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -1125,7 +1125,7 @@ public void TestGetGuid() [Test] public void TestCopyCmdUpdateCount() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -1163,7 +1163,7 @@ public void TestCopyCmdUpdateCount() [Test] public void TestCopyCmdResultSet() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -1211,7 +1211,7 @@ public void TestCopyCmdResultSet() [Test] public void TestRetrieveSemiStructuredData() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -1237,7 +1237,7 @@ public void TestRetrieveSemiStructuredData() [Test] public void TestResultSetMetadata() { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); @@ -1259,20 +1259,20 @@ public void TestResultSetMetadata() Assert.AreEqual(0, row[SchemaTableColumn.ColumnOrdinal]); Assert.AreEqual(20, row[SchemaTableColumn.NumericPrecision]); Assert.AreEqual(4, row[SchemaTableColumn.NumericScale]); - Assert.AreEqual(SnowflakeDataType.Fixed, (SnowflakeDataType)row[SchemaTableColumn.ProviderType]); + Assert.AreEqual(SnowflakeDbDataType.Fixed, (SnowflakeDbDataType)row[SchemaTableColumn.ProviderType]); Assert.AreEqual(true, row[SchemaTableColumn.AllowDBNull]); row = dataTable.Rows[1]; Assert.AreEqual("C2", row[SchemaTableColumn.ColumnName]); Assert.AreEqual(1, row[SchemaTableColumn.ColumnOrdinal]); Assert.AreEqual(100, row[SchemaTableColumn.ColumnSize]); - Assert.AreEqual(SnowflakeDataType.Text, (SnowflakeDataType)row[SchemaTableColumn.ProviderType]); + Assert.AreEqual(SnowflakeDbDataType.Text, (SnowflakeDbDataType)row[SchemaTableColumn.ProviderType]); Assert.AreEqual(true, row[SchemaTableColumn.AllowDBNull]); row = dataTable.Rows[2]; Assert.AreEqual("C3", row[SchemaTableColumn.ColumnName]); Assert.AreEqual(2, row[SchemaTableColumn.ColumnOrdinal]); - Assert.AreEqual(SnowflakeDataType.Real, (SnowflakeDataType)row[SchemaTableColumn.ProviderType]); + Assert.AreEqual(SnowflakeDbDataType.Real, (SnowflakeDbDataType)row[SchemaTableColumn.ProviderType]); Assert.AreEqual(true, row[SchemaTableColumn.AllowDBNull]); row = dataTable.Rows[3]; @@ -1280,19 +1280,19 @@ public void TestResultSetMetadata() Assert.AreEqual(3, row[SchemaTableColumn.ColumnOrdinal]); Assert.AreEqual(0, row[SchemaTableColumn.NumericPrecision]); Assert.AreEqual(9, row[SchemaTableColumn.NumericScale]); - Assert.AreEqual(SnowflakeDataType.TimestampNtz, (SnowflakeDataType)row[SchemaTableColumn.ProviderType]); + Assert.AreEqual(SnowflakeDbDataType.TimestampNtz, (SnowflakeDbDataType)row[SchemaTableColumn.ProviderType]); Assert.AreEqual(true, row[SchemaTableColumn.AllowDBNull]); row = dataTable.Rows[4]; Assert.AreEqual("C5", row[SchemaTableColumn.ColumnName]); Assert.AreEqual(4, row[SchemaTableColumn.ColumnOrdinal]); - Assert.AreEqual(SnowflakeDataType.Variant, (SnowflakeDataType)row[SchemaTableColumn.ProviderType]); + Assert.AreEqual(SnowflakeDbDataType.Variant, (SnowflakeDbDataType)row[SchemaTableColumn.ProviderType]); Assert.AreEqual(false, row[SchemaTableColumn.AllowDBNull]); row = dataTable.Rows[5]; Assert.AreEqual("C6", row[SchemaTableColumn.ColumnName]); Assert.AreEqual(5, row[SchemaTableColumn.ColumnOrdinal]); - Assert.AreEqual(SnowflakeDataType.Boolean, (SnowflakeDataType)row[SchemaTableColumn.ProviderType]); + Assert.AreEqual(SnowflakeDbDataType.Boolean, (SnowflakeDbDataType)row[SchemaTableColumn.ProviderType]); Assert.AreEqual(true, row[SchemaTableColumn.AllowDBNull]); } diff --git a/Snowflake.Data.Tests/SFDbFactoryIT.cs b/Snowflake.Data.Tests/SFDbFactoryIT.cs index ae7eb37..d5791e2 100755 --- a/Snowflake.Data.Tests/SFDbFactoryIT.cs +++ b/Snowflake.Data.Tests/SFDbFactoryIT.cs @@ -16,7 +16,7 @@ public void TestSimpleDbFactory() // In .NET Standard, DbProviderFactories is gone. // Reference https://weblog.west-wind.com/posts/2017/Nov/27/Working-around-the-lack-of-dynamic-DbProviderFactory-loading-in-NET-Core // for more details - DbProviderFactory factory = Tortuga.Data.Snowflake.SnowflakeProviderFactory.Instance; + DbProviderFactory factory = Tortuga.Data.Snowflake.SnowflakeDbProviderFactory.Instance; DbCommand command = factory.CreateCommand(); DbConnection connection = factory.CreateConnection(); connection.ConnectionString = ConnectionString; diff --git a/Snowflake.Data.Tests/SFDbTransactionIT.cs b/Snowflake.Data.Tests/SFDbTransactionIT.cs index 671df43..e70a743 100644 --- a/Snowflake.Data.Tests/SFDbTransactionIT.cs +++ b/Snowflake.Data.Tests/SFDbTransactionIT.cs @@ -14,7 +14,7 @@ class SFDbTransactionIT : SFBaseTest // Test that when a transaction is disposed, rollback would be sent out public void TestTransactionDispose() { - var conn = new SnowflakeConnection(); + var conn = new SnowflakeDbConnection(); try { conn.ConnectionString = ConnectionString; diff --git a/Snowflake.Data.Tests/SFOktaTest.cs b/Snowflake.Data.Tests/SFOktaTest.cs index c41d487..0de5ef1 100644 --- a/Snowflake.Data.Tests/SFOktaTest.cs +++ b/Snowflake.Data.Tests/SFOktaTest.cs @@ -19,13 +19,13 @@ public void TestSsoTokenUrlMismatch() TokenUrl = "https://snowflakecomputing.okta1.com/api/v1/sessions?additionalFields=cookieToken", SSOUrl = "https://snowflakecomputing.okta.com/app/snowflake_testaccountdev_1/blah/sso/saml", }; - var sfSession = new SFSession("account=test;user=test;password=test;authenticator=https://snowflake.okta.com", null, restRequester, SnowflakeConfiguration.Default); + var sfSession = new SFSession("account=test;user=test;password=test;authenticator=https://snowflake.okta.com", null, restRequester, SnowflakeDbConfiguration.Default); sfSession.Open(); Assert.Fail("Should not pass"); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.IdpSsoTokenUrlMismatch, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.IdpSsoTokenUrlMismatch, e.SnowflakeError); } } @@ -40,13 +40,13 @@ public void TestMissingPostbackUrl() SSOUrl = "https://snowflakecomputing.okta.com/app/snowflake_testaccountdev_1/blah/sso/saml", ResponseContent = noPostbackContent, }; - var sfSession = new SFSession("account=test;user=test;password=test;authenticator=https://snowflakecomputing.okta.com;host=test", null, restRequester, SnowflakeConfiguration.Default); + var sfSession = new SFSession("account=test;user=test;password=test;authenticator=https://snowflakecomputing.okta.com;host=test", null, restRequester, SnowflakeDbConfiguration.Default); sfSession.Open(); Assert.Fail("Should not pass"); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.IdpSamlPostbackNotFound, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.IdpSamlPostbackNotFound, e.SnowflakeError); } } @@ -61,13 +61,13 @@ public void TestWrongPostbackUrl() SSOUrl = "https://snowflakecomputing.okta.com/app/snowflake_testaccountdev_1/blah/sso/saml", ResponseContent = wrongPostbackContent, }; - var sfSession = new SFSession("account=test;user=test;password=test;authenticator=https://snowflakecomputing.okta.com;host=test", null, restRequester, SnowflakeConfiguration.Default); + var sfSession = new SFSession("account=test;user=test;password=test;authenticator=https://snowflakecomputing.okta.com;host=test", null, restRequester, SnowflakeDbConfiguration.Default); sfSession.Open(); Assert.Fail("Should not pass"); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.IdpSamlPostbackInvalid, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.IdpSamlPostbackInvalid, e.SnowflakeError); } } } diff --git a/Snowflake.Data.Tests/SFPutGetTest.cs b/Snowflake.Data.Tests/SFPutGetTest.cs index 4614570..1cec6c4 100644 --- a/Snowflake.Data.Tests/SFPutGetTest.cs +++ b/Snowflake.Data.Tests/SFPutGetTest.cs @@ -68,7 +68,7 @@ public void TestPutGetCommand(string compressionType) { foreach (var autoCompressType in autoCompressTypes) { - using (var conn = new SnowflakeConnection()) + using (var conn = new SnowflakeDbConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); diff --git a/Snowflake.Data.Tests/SFReusableChunkTest.cs b/Snowflake.Data.Tests/SFReusableChunkTest.cs index 3b45cda..76e4c9a 100755 --- a/Snowflake.Data.Tests/SFReusableChunkTest.cs +++ b/Snowflake.Data.Tests/SFReusableChunkTest.cs @@ -177,9 +177,9 @@ public async Task TestParserError1() await parser.ParseChunkAsync(chunk); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.InternalError, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.InternalError, e.SnowflakeError); } } @@ -207,9 +207,9 @@ public async Task TestParserError2() await parser.ParseChunkAsync(chunk); Assert.Fail(); } - catch (SnowflakeException e) + catch (SnowflakeDbException e) { - Assert.AreEqual(SnowflakeError.InternalError, e.SnowflakeError); + Assert.AreEqual(SnowflakeDbError.InternalError, e.SnowflakeError); } } diff --git a/Snowflake.Data.Tests/SFSessionTest.cs b/Snowflake.Data.Tests/SFSessionTest.cs index 868cdc9..972328f 100644 --- a/Snowflake.Data.Tests/SFSessionTest.cs +++ b/Snowflake.Data.Tests/SFSessionTest.cs @@ -15,7 +15,7 @@ class SFSessionTest public void TestSessionGoneWhenClose() { Mock.MockCloseSessionGone restRequester = new Mock.MockCloseSessionGone(); - SFSession sfSession = new SFSession("account=test;user=test;password=test", null, restRequester, SnowflakeConfiguration.Default); + SFSession sfSession = new SFSession("account=test;user=test;password=test", null, restRequester, SnowflakeDbConfiguration.Default); sfSession.Open(); sfSession.Close(); // no exception is raised. } diff --git a/Snowflake.Data.Tests/SFStatementTest.cs b/Snowflake.Data.Tests/SFStatementTest.cs index 41ad5c6..7b1413a 100755 --- a/Snowflake.Data.Tests/SFStatementTest.cs +++ b/Snowflake.Data.Tests/SFStatementTest.cs @@ -21,7 +21,7 @@ class SFStatementTest public void TestSessionRenew() { Mock.MockRestSessionExpired restRequester = new Mock.MockRestSessionExpired(); - SFSession sfSession = new SFSession("account=test;user=test;password=test", null, restRequester, SnowflakeConfiguration.Default); + SFSession sfSession = new SFSession("account=test;user=test;password=test", null, restRequester, SnowflakeDbConfiguration.Default); sfSession.Open(); SFStatement statement = new SFStatement(sfSession); SFBaseResultSet resultSet = statement.Execute(0, "select 1", null, false); @@ -37,7 +37,7 @@ public void TestSessionRenew() public void TestSessionRenewDuringQueryExec() { Mock.MockRestSessionExpiredInQueryExec restRequester = new Mock.MockRestSessionExpiredInQueryExec(); - SFSession sfSession = new SFSession("account=test;user=test;password=test", null, restRequester, SnowflakeConfiguration.Default); + SFSession sfSession = new SFSession("account=test;user=test;password=test", null, restRequester, SnowflakeDbConfiguration.Default); sfSession.Open(); SFStatement statement = new SFStatement(sfSession); SFBaseResultSet resultSet = statement.Execute(0, "select 1", null, false); @@ -53,7 +53,7 @@ public void TestSessionRenewDuringQueryExec() public void TestServiceName() { var restRequester = new Mock.MockServiceName(); - var sfSession = new SFSession("account=test;user=test;password=test", null, restRequester, SnowflakeConfiguration.Default); + var sfSession = new SFSession("account=test;user=test;password=test", null, restRequester, SnowflakeDbConfiguration.Default); sfSession.Open(); var expectServiceName = Mock.MockServiceName.INIT_SERVICE_NAME; Assert.AreEqual(expectServiceName, sfSession.ParameterMap[SFSessionParameter.SERVICE_NAME]); diff --git a/Snowflake.Data/Core/Authenticators/ExternalBrowserAuthenticator.cs b/Snowflake.Data/Core/Authenticators/ExternalBrowserAuthenticator.cs index ef3c74f..c603df6 100644 --- a/Snowflake.Data/Core/Authenticators/ExternalBrowserAuthenticator.cs +++ b/Snowflake.Data/Core/Authenticators/ExternalBrowserAuthenticator.cs @@ -176,7 +176,7 @@ static void StartBrowser(string url) } else { - throw new SnowflakeException(SnowflakeError.UnsupportedPlatform); + throw new SnowflakeDbException(SnowflakeDbError.UnsupportedPlatform); } #endif } @@ -185,12 +185,12 @@ static string ValidateAndExtractToken(HttpListenerRequest request) { if (request.HttpMethod != "GET") { - throw new SnowflakeException(SnowflakeError.BrowserResponseWrongMethod, request.HttpMethod); + throw new SnowflakeDbException(SnowflakeDbError.BrowserResponseWrongMethod, request.HttpMethod); } if (request.Url?.Query == null || !request.Url.Query.StartsWith(TokenRequestPrefix, StringComparison.Ordinal)) { - throw new SnowflakeException(SnowflakeError.BrowserResponseInvalidPrefix, request.Url?.Query); + throw new SnowflakeDbException(SnowflakeDbError.BrowserResponseInvalidPrefix, request.Url?.Query); } return Uri.UnescapeDataString(request.Url.Query.Substring(TokenRequestPrefix.Length)); diff --git a/Snowflake.Data/Core/Authenticators/KeyPairAuthenticator.cs b/Snowflake.Data/Core/Authenticators/KeyPairAuthenticator.cs index 803d15d..96fb2d1 100644 --- a/Snowflake.Data/Core/Authenticators/KeyPairAuthenticator.cs +++ b/Snowflake.Data/Core/Authenticators/KeyPairAuthenticator.cs @@ -15,7 +15,7 @@ using Tortuga.Data.Snowflake.Core.Messages; using Tortuga.Data.Snowflake.Core.Sessions; using static Tortuga.Data.Snowflake.Core.Sessions.SFSessionProperty; -using static Tortuga.Data.Snowflake.SnowflakeError; +using static Tortuga.Data.Snowflake.SnowflakeDbError; namespace Tortuga.Data.Snowflake.Core.Authenticators; @@ -44,7 +44,7 @@ internal KeyPairAuthenticator(SFSession session) : base(session) if (!session.m_Properties.ContainsKey(PRIVATE_KEY_FILE) && !session.m_Properties.ContainsKey(PRIVATE_KEY)) { // There is no PRIVATE_KEY_FILE defined, can't authenticate with key-pair - throw new SnowflakeException(InvalidConnectionString, "Missing required PRIVATE_KEY_FILE or PRIVATE_KEY for key pair authentication"); + throw new SnowflakeDbException(InvalidConnectionString, "Missing required PRIVATE_KEY_FILE or PRIVATE_KEY for key pair authentication"); } m_RsaProvider = new RSACryptoServiceProvider(); @@ -127,12 +127,12 @@ private string GenerateJwtToken() } if (keypair == null) { - throw new SnowflakeException(SnowflakeError.InternalError, "Unknown error."); + throw new SnowflakeDbException(SnowflakeDbError.InternalError, "Unknown error."); } } catch (Exception e) { - throw new SnowflakeException(JwtErrorReadingPk, hasPkPath ? pkPath : "with value passed in connection string", e.ToString(), e); + throw new SnowflakeDbException(JwtErrorReadingPk, hasPkPath ? pkPath : "with value passed in connection string", e.ToString(), e); } } diff --git a/Snowflake.Data/Core/Authenticators/OAuthAuthenticator.cs b/Snowflake.Data/Core/Authenticators/OAuthAuthenticator.cs index 97e3073..9044a99 100644 --- a/Snowflake.Data/Core/Authenticators/OAuthAuthenticator.cs +++ b/Snowflake.Data/Core/Authenticators/OAuthAuthenticator.cs @@ -1,7 +1,7 @@ using Tortuga.Data.Snowflake.Core.Messages; using Tortuga.Data.Snowflake.Core.Sessions; using static Tortuga.Data.Snowflake.Core.Sessions.SFSessionProperty; -using static Tortuga.Data.Snowflake.SnowflakeError; +using static Tortuga.Data.Snowflake.SnowflakeDbError; namespace Tortuga.Data.Snowflake.Core.Authenticators; @@ -24,7 +24,7 @@ internal OAuthAuthenticator(SFSession session) : base(session) if (!session.m_Properties.ContainsKey(TOKEN)) { // There is no TOKEN defined, can't authenticate with oauth - throw new SnowflakeException(InvalidConnectionString, "Missing required TOKEN for Oauth authentication"); + throw new SnowflakeDbException(InvalidConnectionString, "Missing required TOKEN for Oauth authentication"); } } diff --git a/Snowflake.Data/Core/Authenticators/OktaAuthenticator.cs b/Snowflake.Data/Core/Authenticators/OktaAuthenticator.cs index 9d7084a..de93f84 100644 --- a/Snowflake.Data/Core/Authenticators/OktaAuthenticator.cs +++ b/Snowflake.Data/Core/Authenticators/OktaAuthenticator.cs @@ -156,7 +156,7 @@ void VerifyPostbackUrl() } catch (Exception e) { - throw new SnowflakeException(SnowflakeError.IdpSamlPostbackNotFound, e); + throw new SnowflakeDbException(SnowflakeDbError.IdpSamlPostbackNotFound, e); } var sessionHost = Session.m_Properties[SFSessionProperty.HOST]; @@ -164,7 +164,7 @@ void VerifyPostbackUrl() if (postBackUrl.Host != sessionHost || postBackUrl.Scheme != sessionScheme) { - throw new SnowflakeException(SnowflakeError.IdpSamlPostbackInvalid, postBackUrl.ToString(), sessionScheme + ":\\\\" + sessionHost); + throw new SnowflakeDbException(SnowflakeDbError.IdpSamlPostbackInvalid, postBackUrl.ToString(), sessionScheme + ":\\\\" + sessionHost); } } @@ -172,7 +172,7 @@ void VerifyUrls(Uri tokenOrSsoUrl, Uri sessionUrl) { if (tokenOrSsoUrl.Scheme != sessionUrl.Scheme || tokenOrSsoUrl.Host != sessionUrl.Host) { - throw new SnowflakeException(SnowflakeError.IdpSsoTokenUrlMismatch, tokenOrSsoUrl.ToString(), m_OktaUrl.ToString()); + throw new SnowflakeDbException(SnowflakeDbError.IdpSsoTokenUrlMismatch, tokenOrSsoUrl.ToString(), m_OktaUrl.ToString()); } } } diff --git a/Snowflake.Data/Core/FileTransfer/SFFileTransferAgent.cs b/Snowflake.Data/Core/FileTransfer/SFFileTransferAgent.cs index 7239590..db99b23 100644 --- a/Snowflake.Data/Core/FileTransfer/SFFileTransferAgent.cs +++ b/Snowflake.Data/Core/FileTransfer/SFFileTransferAgent.cs @@ -306,7 +306,7 @@ void InitFileMetadata(List files) if (!compressionType.IsSupported) { // SqlState.FEATURE_NOT_SUPPORTED = 0A000 - throw new SnowflakeException("0A000", SnowflakeError.InternalError, compressionType.Name); + throw new SnowflakeDbException("0A000", SnowflakeDbError.InternalError, compressionType.Name); } var fileMetadata = new SFFileMetadata() diff --git a/Snowflake.Data/Core/FileTransfer/StorageClient/SFRemoteStorage.cs b/Snowflake.Data/Core/FileTransfer/StorageClient/SFRemoteStorage.cs index cf7133d..5efe14a 100644 --- a/Snowflake.Data/Core/FileTransfer/StorageClient/SFRemoteStorage.cs +++ b/Snowflake.Data/Core/FileTransfer/StorageClient/SFRemoteStorage.cs @@ -155,7 +155,7 @@ internal static void UploadOneFile(SFFileMetadata fileMetadata) else { var msg = "Unknown Error in uploading a file: " + fileMetadata.DestFileName; - throw new SnowflakeException(SnowflakeError.InternalError, msg); + throw new SnowflakeDbException(SnowflakeDbError.InternalError, msg); } } @@ -311,7 +311,7 @@ internal override void DownloadOneFile(SFFileMetadata fileMetadata) else { var msg = "Unknown Error in downloading a file: " + fileMetadata.DestFileName; - throw new SnowflakeException(SnowflakeError.InternalError, msg); + throw new SnowflakeDbException(SnowflakeDbError.InternalError, msg); } } } diff --git a/Snowflake.Data/Core/Messages/BaseRestResponse.cs b/Snowflake.Data/Core/Messages/BaseRestResponse.cs index bb7133c..769dbe1 100644 --- a/Snowflake.Data/Core/Messages/BaseRestResponse.cs +++ b/Snowflake.Data/Core/Messages/BaseRestResponse.cs @@ -20,6 +20,6 @@ abstract class BaseRestResponse internal void FilterFailedResponse() { if (!Success) - throw new SnowflakeException("", Code, Message, ""); + throw new SnowflakeDbException("", Code, Message, ""); } } diff --git a/Snowflake.Data/Core/RequestProcessing/RestRequester.cs b/Snowflake.Data/Core/RequestProcessing/RestRequester.cs index 3c7261e..fc7c5b5 100644 --- a/Snowflake.Data/Core/RequestProcessing/RestRequester.cs +++ b/Snowflake.Data/Core/RequestProcessing/RestRequester.cs @@ -89,7 +89,7 @@ protected virtual HttpResponseMessage Send(HttpRequestMessage message, TimeSpan // Disposing of the response if not null now that we don't need it anymore response?.Dispose(); if (restRequestTimeout.IsCancellationRequested) - throw new SnowflakeException(SnowflakeError.RequestTimeout); + throw new SnowflakeDbException(SnowflakeDbError.RequestTimeout); else throw; } @@ -117,7 +117,7 @@ protected virtual async Task SendAsync(HttpRequestMessage m // Disposing of the response if not null now that we don't need it anymore response?.Dispose(); if (restRequestTimeout.IsCancellationRequested) - throw new SnowflakeException(SnowflakeError.RequestTimeout); + throw new SnowflakeDbException(SnowflakeDbError.RequestTimeout); else throw; } diff --git a/Snowflake.Data/Core/RequestProcessing/SFStatement.cs b/Snowflake.Data/Core/RequestProcessing/SFStatement.cs index bc305bd..062f2ce 100644 --- a/Snowflake.Data/Core/RequestProcessing/SFStatement.cs +++ b/Snowflake.Data/Core/RequestProcessing/SFStatement.cs @@ -51,7 +51,7 @@ private void AssignQueryRequestId() lock (m_RequestIdLock) { if (m_RequestId != null) - throw new SnowflakeException(SnowflakeError.StatementAlreadyRunningQuery); + throw new SnowflakeDbException(SnowflakeDbError.StatementAlreadyRunningQuery); m_RequestId = Guid.NewGuid().ToString(); } @@ -131,7 +131,7 @@ private SFBaseResultSet BuildResultSet(QueryExecResponse response, CancellationT if (response.Success) return new SFResultSet(response.Data!, this, cancellationToken); - throw new SnowflakeException(response.Data!.sqlState!, response.Code, response.Message, response.Data!.QueryId!); + throw new SnowflakeDbException(response.Data!.sqlState!, response.Code, response.Message, response.Data!.QueryId!); } /// @@ -368,7 +368,7 @@ internal T ExecuteHelper(int timeout, string sql, Dictionary public abstract void ParseChunk(IResultChunk chunk); - public static ChunkParser GetParser(SnowflakeConfiguration configuration, Stream stream) + public static ChunkParser GetParser(SnowflakeDbConfiguration configuration, Stream stream) { if (!configuration.UseV2JsonParser) return new ChunkDeserializer(stream); diff --git a/Snowflake.Data/Core/ResponseProcessing/Chunks/ReusableChunkParser.cs b/Snowflake.Data/Core/ResponseProcessing/Chunks/ReusableChunkParser.cs index 926b2b9..4917905 100644 --- a/Snowflake.Data/Core/ResponseProcessing/Chunks/ReusableChunkParser.cs +++ b/Snowflake.Data/Core/ResponseProcessing/Chunks/ReusableChunkParser.cs @@ -74,7 +74,7 @@ public override void ParseChunk(IResultChunk chunk) break; case -1: - throw new SnowflakeException(SnowflakeError.InternalError, $"Unexpected end of stream in escape sequence"); + throw new SnowflakeDbException(SnowflakeDbError.InternalError, $"Unexpected end of stream in escape sequence"); } ms.WriteByte((byte)c); } @@ -85,7 +85,7 @@ public override void ParseChunk(IResultChunk chunk) } } if (inString) - throw new SnowflakeException(SnowflakeError.InternalError, $"Unexpected end of stream in string"); + throw new SnowflakeDbException(SnowflakeDbError.InternalError, $"Unexpected end of stream in string"); } public override async Task ParseChunkAsync(IResultChunk chunk) diff --git a/Snowflake.Data/Core/ResponseProcessing/Chunks/SFChunkDownloaderV2.cs b/Snowflake.Data/Core/ResponseProcessing/Chunks/SFChunkDownloaderV2.cs index ff3d269..2ef4780 100644 --- a/Snowflake.Data/Core/ResponseProcessing/Chunks/SFChunkDownloaderV2.cs +++ b/Snowflake.Data/Core/ResponseProcessing/Chunks/SFChunkDownloaderV2.cs @@ -22,10 +22,10 @@ class SFChunkDownloaderV2 : IChunkDownloader, IDisposable const int prefetchSlot = 5; readonly IRestRequester m_RestRequester; - readonly SnowflakeConfiguration m_Configuration; + readonly SnowflakeDbConfiguration m_Configuration; readonly Dictionary m_ChunkHeaders; - public SFChunkDownloaderV2(int colCount, List chunkInfos, string qrmk, Dictionary chunkHeaders, CancellationToken cancellationToken, IRestRequester restRequester, SnowflakeConfiguration configuration) + public SFChunkDownloaderV2(int colCount, List chunkInfos, string qrmk, Dictionary chunkHeaders, CancellationToken cancellationToken, IRestRequester restRequester, SnowflakeDbConfiguration configuration) { m_Qrmk = qrmk; m_ChunkHeaders = chunkHeaders; diff --git a/Snowflake.Data/Core/ResponseProcessing/SFBaseResultSet.cs b/Snowflake.Data/Core/ResponseProcessing/SFBaseResultSet.cs index 5f097f4..eadce75 100644 --- a/Snowflake.Data/Core/ResponseProcessing/SFBaseResultSet.cs +++ b/Snowflake.Data/Core/ResponseProcessing/SFBaseResultSet.cs @@ -30,7 +30,7 @@ abstract class SFBaseResultSet /// True if it works, false otherwise. internal abstract bool Rewind(); - protected SFBaseResultSet(SnowflakeConfiguration configuration) + protected SFBaseResultSet(SnowflakeDbConfiguration configuration) { Configuration = configuration; } @@ -53,7 +53,7 @@ internal T GetValue(int columnIndex) var type = SFResultSetMetaData.GetColumnTypeByIndex(columnIndex); switch (type) { - case SnowflakeDataType.Date: + case SnowflakeDbDataType.Date: var val = GetValue(columnIndex); if (val == DBNull.Value) return null; @@ -82,7 +82,7 @@ internal object GetValue(int columnIndex) internal void Close() => m_IsClosed = true; - internal SnowflakeConfiguration Configuration { get; } + internal SnowflakeDbConfiguration Configuration { get; } internal int CalculateUpdateCount() { diff --git a/Snowflake.Data/Core/ResponseProcessing/SFResultSet.cs b/Snowflake.Data/Core/ResponseProcessing/SFResultSet.cs index a8c75b3..131f532 100644 --- a/Snowflake.Data/Core/ResponseProcessing/SFResultSet.cs +++ b/Snowflake.Data/Core/ResponseProcessing/SFResultSet.cs @@ -110,7 +110,7 @@ internal override async Task NextAsync() { if (m_IsClosed) { - throw new SnowflakeException(SnowflakeError.DataReaderAlreadyClosed); + throw new SnowflakeDbException(SnowflakeDbError.DataReaderAlreadyClosed); } m_CurrentChunkRowIdx++; @@ -142,7 +142,7 @@ internal override bool Next() { if (m_IsClosed) { - throw new SnowflakeException(SnowflakeError.DataReaderAlreadyClosed); + throw new SnowflakeDbException(SnowflakeDbError.DataReaderAlreadyClosed); } m_CurrentChunkRowIdx++; @@ -171,7 +171,7 @@ internal override bool Rewind() { if (m_IsClosed) { - throw new SnowflakeException(SnowflakeError.DataReaderAlreadyClosed); + throw new SnowflakeDbException(SnowflakeDbError.DataReaderAlreadyClosed); } if (m_CurrentChunkRowIdx >= 0) @@ -190,12 +190,12 @@ internal override bool Rewind() { if (m_IsClosed) { - throw new SnowflakeException(SnowflakeError.DataReaderAlreadyClosed); + throw new SnowflakeDbException(SnowflakeDbError.DataReaderAlreadyClosed); } if (columnIndex < 0 || columnIndex >= m_ColumnCount) { - throw new SnowflakeException(SnowflakeError.ColumnIndexOutOfBound, columnIndex); + throw new SnowflakeDbException(SnowflakeDbError.ColumnIndexOutOfBound, columnIndex); } return m_CurrentChunk.ExtractCell(m_CurrentChunkRowIdx, columnIndex); diff --git a/Snowflake.Data/Core/ResponseProcessing/SFResultSetMetaData.cs b/Snowflake.Data/Core/ResponseProcessing/SFResultSetMetaData.cs index 802f28a..f5ffa27 100644 --- a/Snowflake.Data/Core/ResponseProcessing/SFResultSetMetaData.cs +++ b/Snowflake.Data/Core/ResponseProcessing/SFResultSetMetaData.cs @@ -24,7 +24,7 @@ class SFResultSetMetaData internal readonly SFStatementType m_StatementType; - internal readonly List> m_ColumnTypes; + internal readonly List> m_ColumnTypes; /// /// This map is used to cache column name to column index. Index is 0-based. @@ -69,13 +69,13 @@ internal SFResultSetMetaData(PutGetResponseData putGetResponseData) m_ColumnTypes = InitColumnTypes(); } - List> InitColumnTypes() + List> InitColumnTypes() { - var types = new List>(); + var types = new List>(); for (var i = 0; i < m_ColumnCount; i++) { var column = m_RowTypes[i]; - var dataType = SnowflakeDataTypeExtensions.FromSql(column.Type!); + var dataType = SnowflakeDbDataTypeExtensions.FromSql(column.Type!); var nativeType = GetNativeTypeForColumn(dataType, column); types.Add(Tuple.Create(dataType, nativeType)); @@ -108,55 +108,55 @@ internal int GetColumnIndexByName(string targetColumnName) return -1; } - internal SnowflakeDataType GetColumnTypeByIndex(int targetIndex) + internal SnowflakeDbDataType GetColumnTypeByIndex(int targetIndex) { if (targetIndex < 0 || targetIndex >= m_ColumnCount) - throw new SnowflakeException(SnowflakeError.ColumnIndexOutOfBound, targetIndex); + throw new SnowflakeDbException(SnowflakeDbError.ColumnIndexOutOfBound, targetIndex); return m_ColumnTypes[targetIndex].Item1; } - internal Tuple GetTypesByIndex(int targetIndex) + internal Tuple GetTypesByIndex(int targetIndex) { if (targetIndex < 0 || targetIndex >= m_ColumnCount) - throw new SnowflakeException(SnowflakeError.ColumnIndexOutOfBound, targetIndex); + throw new SnowflakeDbException(SnowflakeDbError.ColumnIndexOutOfBound, targetIndex); return m_ColumnTypes[targetIndex]; } - static Type GetNativeTypeForColumn(SnowflakeDataType sfType, ExecResponseRowType col) + static Type GetNativeTypeForColumn(SnowflakeDbDataType sfType, ExecResponseRowType col) { switch (sfType) { - case SnowflakeDataType.Fixed: + case SnowflakeDbDataType.Fixed: return col.Scale == 0 ? typeof(long) : typeof(decimal); - case SnowflakeDataType.Real: + case SnowflakeDbDataType.Real: return typeof(double); - case SnowflakeDataType.Text: - case SnowflakeDataType.Variant: - case SnowflakeDataType.Object: - case SnowflakeDataType.Array: + case SnowflakeDbDataType.Text: + case SnowflakeDbDataType.Variant: + case SnowflakeDbDataType.Object: + case SnowflakeDbDataType.Array: return typeof(string); - case SnowflakeDataType.Date: - case SnowflakeDataType.Time: - case SnowflakeDataType.TimestampNtz: + case SnowflakeDbDataType.Date: + case SnowflakeDbDataType.Time: + case SnowflakeDbDataType.TimestampNtz: return typeof(DateTime); - case SnowflakeDataType.TimestampLtz: - case SnowflakeDataType.TimestampTz: + case SnowflakeDbDataType.TimestampLtz: + case SnowflakeDbDataType.TimestampTz: return typeof(DateTimeOffset); - case SnowflakeDataType.Binary: + case SnowflakeDbDataType.Binary: return typeof(byte[]); - case SnowflakeDataType.Boolean: + case SnowflakeDbDataType.Boolean: return typeof(bool); default: - throw new SnowflakeException(SnowflakeError.InternalError, + throw new SnowflakeDbException(SnowflakeDbError.InternalError, $"Unknow column type: {sfType}"); } } @@ -164,7 +164,7 @@ static Type GetNativeTypeForColumn(SnowflakeDataType sfType, ExecResponseRowType internal Type GetCSharpTypeByIndex(int targetIndex) { if (targetIndex < 0 || targetIndex >= m_ColumnCount) - throw new SnowflakeException(SnowflakeError.ColumnIndexOutOfBound, targetIndex); + throw new SnowflakeDbException(SnowflakeDbError.ColumnIndexOutOfBound, targetIndex); var sfType = GetColumnTypeByIndex(targetIndex); return GetNativeTypeForColumn(sfType, m_RowTypes[targetIndex]); @@ -173,7 +173,7 @@ internal Type GetCSharpTypeByIndex(int targetIndex) internal string? getColumnNameByIndex(int targetIndex) { if (targetIndex < 0 || targetIndex >= m_ColumnCount) - throw new SnowflakeException(SnowflakeError.ColumnIndexOutOfBound, targetIndex); + throw new SnowflakeDbException(SnowflakeDbError.ColumnIndexOutOfBound, targetIndex); return m_RowTypes[targetIndex].Name; } diff --git a/Snowflake.Data/Core/SFDataConverter.cs b/Snowflake.Data/Core/SFDataConverter.cs index 59acccf..d3acfc6 100755 --- a/Snowflake.Data/Core/SFDataConverter.cs +++ b/Snowflake.Data/Core/SFDataConverter.cs @@ -16,7 +16,7 @@ static class SFDataConverter // Method with the same signature as before the performance work // Used by unit tests only - internal static object ConvertToCSharpVal(string srcVal, SnowflakeDataType srcType, Type destType) + internal static object ConvertToCSharpVal(string srcVal, SnowflakeDbDataType srcType, Type destType) { // Create an UTF8Buffer with an offset to get better testing var b1 = Encoding.UTF8.GetBytes(srcVal); @@ -26,7 +26,7 @@ internal static object ConvertToCSharpVal(string srcVal, SnowflakeDataType srcTy return ConvertToCSharpVal(v, srcType, destType); } - internal static object ConvertToCSharpVal(UTF8Buffer? srcVal, SnowflakeDataType srcType, Type destType) + internal static object ConvertToCSharpVal(UTF8Buffer? srcVal, SnowflakeDbDataType srcType, Type destType) { if (srcVal == null) return DBNull.Value; @@ -69,7 +69,7 @@ internal static object ConvertToCSharpVal(UTF8Buffer? srcVal, SnowflakeDataType } else if (destType == typeof(byte[])) { - return srcType == SnowflakeDataType.Binary ? + return srcType == SnowflakeDbDataType.Binary ? HexToBytes(srcVal.ToString()) : srcVal.GetBytes(); } else if (destType == typeof(short)) @@ -98,12 +98,12 @@ internal static object ConvertToCSharpVal(UTF8Buffer? srcVal, SnowflakeDataType } else if (destType == typeof(char[])) { - var data = srcType == SnowflakeDataType.Binary ? HexToBytes(srcVal.ToString()) : srcVal.GetBytes(); + var data = srcType == SnowflakeDbDataType.Binary ? HexToBytes(srcVal.ToString()) : srcVal.GetBytes(); return Encoding.UTF8.GetString(data).ToCharArray(); } else { - throw new SnowflakeException(SnowflakeError.InternalError, "Invalid destination type."); + throw new SnowflakeDbException(SnowflakeDbError.InternalError, "Invalid destination type."); } } catch (OverflowException e) @@ -112,48 +112,48 @@ internal static object ConvertToCSharpVal(UTF8Buffer? srcVal, SnowflakeDataType } } - static object ConvertToTimeSpan(UTF8Buffer srcVal, SnowflakeDataType srcType) + static object ConvertToTimeSpan(UTF8Buffer srcVal, SnowflakeDbDataType srcType) { switch (srcType) { - case SnowflakeDataType.Time: + case SnowflakeDbDataType.Time: // Convert fractional seconds since midnight to TimeSpan // A single tick represents one hundred nanoseconds or one ten-millionth of a second. // There are 10,000 ticks in a millisecond return TimeSpan.FromTicks(GetTicksFromSecondAndNanosecond(srcVal)); default: - throw new SnowflakeException(SnowflakeError.InvalidDataConversion, srcVal, srcType, typeof(TimeSpan)); + throw new SnowflakeDbException(SnowflakeDbError.InvalidDataConversion, srcVal, srcType, typeof(TimeSpan)); } } - static DateTime ConvertToDateTime(UTF8Buffer srcVal, SnowflakeDataType srcType) + static DateTime ConvertToDateTime(UTF8Buffer srcVal, SnowflakeDbDataType srcType) { switch (srcType) { - case SnowflakeDataType.Date: + case SnowflakeDbDataType.Date: var srcValLong = FastParser.FastParseInt64(srcVal.Buffer, srcVal.offset, srcVal.length); return UnixEpoch.AddDays(srcValLong); - case SnowflakeDataType.Time: - case SnowflakeDataType.TimestampNtz: + case SnowflakeDbDataType.Time: + case SnowflakeDbDataType.TimestampNtz: var tickDiff = GetTicksFromSecondAndNanosecond(srcVal); return UnixEpoch.AddTicks(tickDiff); default: - throw new SnowflakeException(SnowflakeError.InvalidDataConversion, srcVal, srcType, typeof(DateTime)); + throw new SnowflakeDbException(SnowflakeDbError.InvalidDataConversion, srcVal, srcType, typeof(DateTime)); } } - static DateTimeOffset ConvertToDateTimeOffset(UTF8Buffer srcVal, SnowflakeDataType srcType) + static DateTimeOffset ConvertToDateTimeOffset(UTF8Buffer srcVal, SnowflakeDbDataType srcType) { switch (srcType) { - case SnowflakeDataType.TimestampTz: + case SnowflakeDbDataType.TimestampTz: var spaceIndex = Array.IndexOf(srcVal.Buffer, (byte)' ', srcVal.offset, srcVal.length); ; if (spaceIndex == -1) { - throw new SnowflakeException(SnowflakeError.InternalError, + throw new SnowflakeDbException(SnowflakeDbError.InternalError, $"Invalid timestamp_tz value: {srcVal}"); } else @@ -164,11 +164,11 @@ static DateTimeOffset ConvertToDateTimeOffset(UTF8Buffer srcVal, SnowflakeDataTy var offSetTimespan = new TimeSpan((offset - 1440) / 60, 0, 0); return new DateTimeOffset(UnixEpoch.Ticks + GetTicksFromSecondAndNanosecond(timeVal), TimeSpan.Zero).ToOffset(offSetTimespan); } - case SnowflakeDataType.TimestampLtz: + case SnowflakeDbDataType.TimestampLtz: return new DateTimeOffset(UnixEpoch.Ticks + GetTicksFromSecondAndNanosecond(srcVal), TimeSpan.Zero).ToLocalTime(); default: - throw new SnowflakeException(SnowflakeError.InvalidDataConversion, srcVal, srcType, typeof(DateTimeOffset).ToString()); + throw new SnowflakeDbException(SnowflakeDbError.InvalidDataConversion, srcVal, srcType, typeof(DateTimeOffset).ToString()); } } @@ -220,7 +220,7 @@ static long GetTicksFromSecondAndNanosecond(UTF8Buffer srcVal) internal static Tuple CSharpTypeValToSfTypeVal(DbType srcType, object? srcVal) { - SnowflakeDataType destType; + SnowflakeDbDataType destType; string? destVal; switch (srcType) @@ -235,48 +235,48 @@ static long GetTicksFromSecondAndNanosecond(UTF8Buffer srcVal) case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: - destType = SnowflakeDataType.Fixed; + destType = SnowflakeDbDataType.Fixed; break; case DbType.Boolean: - destType = SnowflakeDataType.Boolean; + destType = SnowflakeDbDataType.Boolean; break; case DbType.Double: case DbType.Single: - destType = SnowflakeDataType.Real; + destType = SnowflakeDbDataType.Real; break; case DbType.Guid: case DbType.String: case DbType.StringFixedLength: - destType = SnowflakeDataType.Text; + destType = SnowflakeDbDataType.Text; break; case DbType.Date: - destType = SnowflakeDataType.Date; + destType = SnowflakeDbDataType.Date; break; case DbType.Time: - destType = SnowflakeDataType.Time; + destType = SnowflakeDbDataType.Time; break; case DbType.DateTime: case DbType.DateTime2: - destType = SnowflakeDataType.TimestampNtz; + destType = SnowflakeDbDataType.TimestampNtz; break; // By default map DateTimeoffset to TIMESTAMP_TZ case DbType.DateTimeOffset: - destType = SnowflakeDataType.TimestampTz; + destType = SnowflakeDbDataType.TimestampTz; break; case DbType.Binary: - destType = SnowflakeDataType.Binary; + destType = SnowflakeDbDataType.Binary; break; default: - throw new SnowflakeException(SnowflakeError.UnsupportedDotnetType, srcType); + throw new SnowflakeDbException(SnowflakeDbError.UnsupportedDotnetType, srcType); } destVal = csharpValToSfVal(destType, srcVal); return Tuple.Create(destType.ToSql(), destVal); @@ -301,7 +301,7 @@ static byte[] HexToBytes(string hex) return bytes; } - internal static string? csharpValToSfVal(SnowflakeDataType sfDataType, object? srcVal) + internal static string? csharpValToSfVal(SnowflakeDbDataType sfDataType, object? srcVal) { if ((srcVal == DBNull.Value) || (srcVal == null)) return null; @@ -310,11 +310,11 @@ static byte[] HexToBytes(string hex) switch (sfDataType) { - case SnowflakeDataType.TimestampLtz: + case SnowflakeDbDataType.TimestampLtz: if (srcVal.GetType() != typeof(DateTimeOffset)) { - throw new SnowflakeException(SnowflakeError.InvalidDataConversion, srcVal, - srcVal.GetType().ToString(), SnowflakeDataType.TimestampLtz.ToString()); + throw new SnowflakeDbException(SnowflakeDbError.InvalidDataConversion, srcVal, + srcVal.GetType().ToString(), SnowflakeDbDataType.TimestampLtz.ToString()); } else { @@ -322,17 +322,17 @@ static byte[] HexToBytes(string hex) } break; - case SnowflakeDataType.Fixed: - case SnowflakeDataType.Boolean: - case SnowflakeDataType.Real: - case SnowflakeDataType.Text: + case SnowflakeDbDataType.Fixed: + case SnowflakeDbDataType.Boolean: + case SnowflakeDbDataType.Real: + case SnowflakeDbDataType.Text: destVal = string.Format(CultureInfo.InvariantCulture, "{0}", srcVal); break; - case SnowflakeDataType.Time: + case SnowflakeDbDataType.Time: if (srcVal.GetType() != typeof(DateTime)) { - throw new SnowflakeException(SnowflakeError.InvalidDataConversion, srcVal, srcVal.GetType().ToString(), DbType.Time.ToString()); + throw new SnowflakeDbException(SnowflakeDbError.InvalidDataConversion, srcVal, srcVal.GetType().ToString(), DbType.Time.ToString()); } else { @@ -343,10 +343,10 @@ static byte[] HexToBytes(string hex) } break; - case SnowflakeDataType.Date: + case SnowflakeDbDataType.Date: if (srcVal.GetType() != typeof(DateTime)) { - throw new SnowflakeException(SnowflakeError.InvalidDataConversion, srcVal, srcVal.GetType().ToString(), DbType.Date.ToString()); + throw new SnowflakeDbException(SnowflakeDbError.InvalidDataConversion, srcVal, srcVal.GetType().ToString(), DbType.Date.ToString()); } else { @@ -357,10 +357,10 @@ static byte[] HexToBytes(string hex) } break; - case SnowflakeDataType.TimestampNtz: + case SnowflakeDbDataType.TimestampNtz: if (srcVal.GetType() != typeof(DateTime)) { - throw new SnowflakeException(SnowflakeError.InvalidDataConversion, srcVal, + throw new SnowflakeDbException(SnowflakeDbError.InvalidDataConversion, srcVal, srcVal.GetType().ToString(), DbType.DateTime.ToString()); } else @@ -372,10 +372,10 @@ static byte[] HexToBytes(string hex) } break; - case SnowflakeDataType.TimestampTz: + case SnowflakeDbDataType.TimestampTz: if (srcVal.GetType() != typeof(DateTimeOffset)) { - throw new SnowflakeException(SnowflakeError.InvalidDataConversion, srcVal, srcVal.GetType().ToString(), DbType.DateTimeOffset.ToString()); + throw new SnowflakeDbException(SnowflakeDbError.InvalidDataConversion, srcVal, srcVal.GetType().ToString(), DbType.DateTimeOffset.ToString()); } else { @@ -384,10 +384,10 @@ static byte[] HexToBytes(string hex) } break; - case SnowflakeDataType.Binary: + case SnowflakeDbDataType.Binary: if (srcVal.GetType() != typeof(byte[])) { - throw new SnowflakeException(SnowflakeError.InvalidDataConversion, srcVal, srcVal.GetType().ToString(), DbType.Binary.ToString()); + throw new SnowflakeDbException(SnowflakeDbError.InvalidDataConversion, srcVal, srcVal.GetType().ToString(), DbType.Binary.ToString()); } else { @@ -396,8 +396,8 @@ static byte[] HexToBytes(string hex) break; default: - throw new SnowflakeException( - SnowflakeError.UnsupportedSnowflakeTypeForParam, sfDataType.ToString()); + throw new SnowflakeDbException( + SnowflakeDbError.UnsupportedSnowflakeTypeForParam, sfDataType.ToString()); } return destVal; } diff --git a/Snowflake.Data/Core/Sessions/SFSession.cs b/Snowflake.Data/Core/Sessions/SFSession.cs index fd4e7c4..23be24d 100644 --- a/Snowflake.Data/Core/Sessions/SFSession.cs +++ b/Snowflake.Data/Core/Sessions/SFSession.cs @@ -14,7 +14,7 @@ using Tortuga.Data.Snowflake.Core.RequestProcessing; using Tortuga.Data.Snowflake.Legacy; using static System.StringComparison; -using static Tortuga.Data.Snowflake.SnowflakeError; +using static Tortuga.Data.Snowflake.SnowflakeDbError; namespace Tortuga.Data.Snowflake.Core.Sessions; @@ -62,7 +62,7 @@ internal void ProcessLoginResponse(LoginResponse authnResponse) } else { - throw new SnowflakeException(SnowflakeException.CONNECTION_FAILURE_SSTATE, authnResponse.Code, authnResponse.Message, ""); + throw new SnowflakeDbException(SnowflakeDbException.CONNECTION_FAILURE_SSTATE, authnResponse.Code, authnResponse.Message, ""); } } @@ -88,7 +88,7 @@ internal Uri BuildLoginUrl() /// Constructor /// /// A string in the form of "key1=value1;key2=value2" - internal SFSession(string connectionString, SecureString? password, SnowflakeConfiguration configuration) + internal SFSession(string connectionString, SecureString? password, SnowflakeDbConfiguration configuration) { Configuration = configuration; m_Properties = SFSessionProperties.parseConnectionString(connectionString, password); @@ -97,7 +97,7 @@ internal SFSession(string connectionString, SecureString? password, SnowflakeCon m_Properties.TryGetValue(SFSessionProperty.APPLICATION, out var applicationNameSetting); if (!string.IsNullOrEmpty(applicationNameSetting) && !APPLICATION_REGEX.IsMatch(applicationNameSetting)) { - throw new SnowflakeException(SnowflakeException.CONNECTION_FAILURE_SSTATE, SnowflakeError.InvalidConnectionParameterValue, applicationNameSetting, SFSessionProperty.APPLICATION.ToString()); + throw new SnowflakeDbException(SnowflakeDbException.CONNECTION_FAILURE_SSTATE, SnowflakeDbError.InvalidConnectionParameterValue, applicationNameSetting, SFSessionProperty.APPLICATION.ToString()); } ParameterMap = new(); @@ -140,13 +140,13 @@ internal SFSession(string connectionString, SecureString? password, SnowflakeCon } catch (Exception e) { - throw new SnowflakeException(e, SnowflakeException.CONNECTION_FAILURE_SSTATE, SnowflakeError.InvalidConnectionString, "Unable to connect"); + throw new SnowflakeDbException(e, SnowflakeDbException.CONNECTION_FAILURE_SSTATE, SnowflakeDbError.InvalidConnectionString, "Unable to connect"); } m_ConnectionTimeout = timeoutInSec > 0 ? TimeSpan.FromSeconds(timeoutInSec) : Timeout.InfiniteTimeSpan; } - internal SFSession(String connectionString, SecureString password, IMockRestRequester restRequester, SnowflakeConfiguration configuration) : this(connectionString, password, configuration) + internal SFSession(String connectionString, SecureString password, IMockRestRequester restRequester, SnowflakeDbConfiguration configuration) : this(connectionString, password, configuration) { // Inject the HttpClient to use with the Mock requester restRequester.setHttpClient(m_HttpClient); @@ -270,7 +270,7 @@ internal void renewSession() var response = RestRequester.Post(renewSessionRequest); if (!response.Success) { - throw new SnowflakeException("", response.Code, response.Message, ""); + throw new SnowflakeDbException("", response.Code, response.Message, ""); } else { @@ -299,14 +299,14 @@ internal void UpdateSessionParameterMap(List parameterList) } } - internal SnowflakeConfiguration Configuration { get; } + internal SnowflakeDbConfiguration Configuration { get; } /// /// Generate the authenticator given the session /// /// session that requires the authentication /// authenticator - /// when authenticator is unknown + /// when authenticator is unknown Authenticator GetAuthenticator() { var type = m_Properties[SFSessionProperty.AUTHENTICATOR]; @@ -333,7 +333,7 @@ Authenticator GetAuthenticator() return new OktaAuthenticator(this, type); } - throw new SnowflakeException(UnknownAuthenticator, type); + throw new SnowflakeDbException(UnknownAuthenticator, type); } static readonly ConcurrentDictionary s_HttpClients = new(); diff --git a/Snowflake.Data/Core/Sessions/SFSessionProperties.cs b/Snowflake.Data/Core/Sessions/SFSessionProperties.cs index 270ee62..34d7a77 100644 --- a/Snowflake.Data/Core/Sessions/SFSessionProperties.cs +++ b/Snowflake.Data/Core/Sessions/SFSessionProperties.cs @@ -106,7 +106,7 @@ internal static SFSessionProperties parseConnectionString(string connectionStrin // An equal sign was not doubled or something else happened // making the connection invalid var invalidStringDetail = $"Invalid key value pair {keyVal}"; - throw new SnowflakeException(SnowflakeError.InvalidConnectionString, new object[] { invalidStringDetail }); + throw new SnowflakeDbException(SnowflakeDbError.InvalidConnectionString, new object[] { invalidStringDetail }); } } @@ -132,7 +132,7 @@ internal static SFSessionProperties parseConnectionString(string connectionStrin catch (Exception e) { // The useProxy setting is not a valid boolean value - throw new SnowflakeException(e, SnowflakeError.InvalidConnectionString, e.Message); + throw new SnowflakeDbException(e, SnowflakeDbError.InvalidConnectionString, e.Message); } } @@ -180,7 +180,7 @@ private static void CheckSessionProperties(SFSessionProperties properties, bool // if required property, check if exists in the dictionary if (isRequired && !properties.ContainsKey(sessionProperty)) { - throw new SnowflakeException(SnowflakeError.MissingConnectionProperty, sessionProperty); + throw new SnowflakeDbException(SnowflakeDbError.MissingConnectionProperty, sessionProperty); } // add default value to the map diff --git a/Snowflake.Data/SnowflakeDataType.cs b/Snowflake.Data/SnowflakeDataType.cs deleted file mode 100644 index 888f036..0000000 --- a/Snowflake.Data/SnowflakeDataType.cs +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved. - */ - -namespace Tortuga.Data.Snowflake; - -public enum SnowflakeDataType -{ - None = 0, - Fixed = 1, - Real = 2, - Text = 3, - Date = 4, - Variant = 5, - TimestampLtz = 6, - TimestampNtz = 7, - TimestampTz = 8, -#pragma warning disable CA1720 // Identifier contains type name - Object = 9, -#pragma warning restore CA1720 // Identifier contains type name - Binary = 10, - Time = 11, - Boolean = 12, - Array = 13 -} - -static class SnowflakeDataTypeExtensions -{ - /// - /// Converts a SFDataType to its SQL representation. - /// - /// Type of the data. - public static string ToSql(this SnowflakeDataType dataType) - { - return dataType switch - { - SnowflakeDataType.None => "", - SnowflakeDataType.Fixed => "FIXED", - SnowflakeDataType.Real => "REAL", - SnowflakeDataType.Text => "TEXT", - SnowflakeDataType.Date => "DATE", - SnowflakeDataType.Variant => "VARIANT", - SnowflakeDataType.TimestampLtz => "TIMESTAMP_LTZ", - SnowflakeDataType.TimestampNtz => "TIMESTAMP_NTZ", - SnowflakeDataType.TimestampTz => "TIMESTAMP_TZ", - SnowflakeDataType.Object => "OBJECT", - SnowflakeDataType.Binary => "BINARY", - SnowflakeDataType.Time => "TIME", - SnowflakeDataType.Boolean => "BOOLEAN", - SnowflakeDataType.Array => "ARRAY", - _ => throw new ArgumentOutOfRangeException(nameof(dataType), dataType, "Unknown data type") - }; - } - - /// - /// Froms the SQL. - /// - /// The type. - /// SFDataType. - /// type - /// Unknow column type: {type} - public static SnowflakeDataType FromSql(string type) - { - if (string.IsNullOrEmpty(type)) - throw new ArgumentException($"{nameof(type)} is null or empty.", nameof(type)); - - bool CheckName(SnowflakeDataType candidate) - { - return string.Equals(candidate.ToString(), type, StringComparison.OrdinalIgnoreCase) - || string.Equals(candidate.ToSql(), type, StringComparison.OrdinalIgnoreCase); - } - - if (CheckName(SnowflakeDataType.None)) return SnowflakeDataType.None; - if (CheckName(SnowflakeDataType.Fixed)) return SnowflakeDataType.Fixed; - if (CheckName(SnowflakeDataType.Real)) return SnowflakeDataType.Real; - if (CheckName(SnowflakeDataType.Text)) return SnowflakeDataType.Text; - if (CheckName(SnowflakeDataType.Date)) return SnowflakeDataType.Date; - if (CheckName(SnowflakeDataType.Variant)) return SnowflakeDataType.Variant; - if (CheckName(SnowflakeDataType.TimestampLtz)) return SnowflakeDataType.TimestampLtz; - if (CheckName(SnowflakeDataType.TimestampNtz)) return SnowflakeDataType.TimestampNtz; - if (CheckName(SnowflakeDataType.TimestampTz)) return SnowflakeDataType.TimestampTz; - if (CheckName(SnowflakeDataType.Object)) return SnowflakeDataType.Object; - if (CheckName(SnowflakeDataType.Binary)) return SnowflakeDataType.Binary; - if (CheckName(SnowflakeDataType.Time)) return SnowflakeDataType.Time; - if (CheckName(SnowflakeDataType.Boolean)) return SnowflakeDataType.Boolean; - if (CheckName(SnowflakeDataType.Array)) return SnowflakeDataType.Array; - - throw new SnowflakeException(SnowflakeError.InternalError, $"Unknow column type: {type}"); - } -} diff --git a/Snowflake.Data/SnowflakeCommand.cs b/Snowflake.Data/SnowflakeDbCommand.cs similarity index 92% rename from Snowflake.Data/SnowflakeCommand.cs rename to Snowflake.Data/SnowflakeDbCommand.cs index 262b4e4..1db7df4 100644 --- a/Snowflake.Data/SnowflakeCommand.cs +++ b/Snowflake.Data/SnowflakeDbCommand.cs @@ -13,18 +13,18 @@ namespace Tortuga.Data.Snowflake; [System.ComponentModel.DesignerCategory("Code")] -public class SnowflakeCommand : DbCommand +public class SnowflakeDbCommand : DbCommand { - readonly SnowflakeParameterCollection m_ParameterCollection = new(); + readonly SnowflakeDbParameterCollection m_ParameterCollection = new(); string m_CommandText = ""; - SnowflakeConnection? m_Connection; + SnowflakeDbConnection? m_Connection; SFStatement? m_SFStatement; - public SnowflakeCommand() + public SnowflakeDbCommand() { } - public SnowflakeCommand(SnowflakeConnection connection) + public SnowflakeDbCommand(SnowflakeDbConnection connection) { m_Connection = connection; } @@ -82,7 +82,7 @@ protected override DbConnection? DbConnection else throw new InvalidOperationException("Unsetting the connection not supported."); - case SnowflakeConnection sfc: + case SnowflakeDbConnection sfc: m_Connection = sfc; return; @@ -144,18 +144,18 @@ public override object ExecuteScalar() [EditorBrowsable(EditorBrowsableState.Never)] public override void Prepare() => throw new NotSupportedException(); - protected override DbParameter CreateDbParameter() => new SnowflakeParameter(); + protected override DbParameter CreateDbParameter() => new SnowflakeDbParameter(); protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { var resultSet = ExecuteInternal(); - return new SnowflakeDataReader(resultSet, m_Connection!, behavior); + return new SnowflakeDbDataReader(resultSet, m_Connection!, behavior); } protected override async Task ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { var result = await ExecuteInternalAsync(cancellationToken).ConfigureAwait(false); - return new SnowflakeDataReader(result, m_Connection!, behavior); + return new SnowflakeDbDataReader(result, m_Connection!, behavior); } Dictionary ConvertToBindList() @@ -188,7 +188,7 @@ effectiveValue is not char[] && // if the user is using interface, SFDataType will be None and there will // a conversion from DbType to SFDataType // if the user is using concrete class, they should specify SFDataType. - if (parameter.SFDataType == SnowflakeDataType.None) + if (parameter.SFDataType == SnowflakeDbDataType.None) { var typeAndVal = SFDataConverter.CSharpTypeValToSfTypeVal(parameter.DbType, val); @@ -205,7 +205,7 @@ effectiveValue is not char[] && } else { - if (parameter.SFDataType == SnowflakeDataType.None) + if (parameter.SFDataType == SnowflakeDbDataType.None) { var typeAndVal = SFDataConverter.CSharpTypeValToSfTypeVal(parameter.DbType, parameter.Value); bindingType = typeAndVal.Item1; diff --git a/Snowflake.Data/SnowflakeCommandBuilder.cs b/Snowflake.Data/SnowflakeDbCommandBuilder.cs similarity index 91% rename from Snowflake.Data/SnowflakeCommandBuilder.cs rename to Snowflake.Data/SnowflakeDbCommandBuilder.cs index 87a1abe..ce6fcec 100644 --- a/Snowflake.Data/SnowflakeCommandBuilder.cs +++ b/Snowflake.Data/SnowflakeDbCommandBuilder.cs @@ -9,23 +9,23 @@ namespace Tortuga.Data.Snowflake; -public class SnowflakeCommandBuilder : DbCommandBuilder +public class SnowflakeDbCommandBuilder : DbCommandBuilder { const string QuoteCharacter = "\""; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public SnowflakeCommandBuilder() + public SnowflakeDbCommandBuilder() : this(null) { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The adapter. - public SnowflakeCommandBuilder(SnowlfakeDataAdapter? adapter) + public SnowflakeDbCommandBuilder(SnowlfakeDbDataAdapter? adapter) { DataAdapter = adapter; QuotePrefix = QuoteCharacter; @@ -81,7 +81,7 @@ protected override void ApplyParameterInfo(DbParameter parameter, DataRow row, S if (row == null) throw new ArgumentNullException(nameof(row), $"{nameof(row)} is null."); - var param = (SnowflakeParameter)parameter; + var param = (SnowflakeDbParameter)parameter; param.DbType = (DbType)row[SchemaTableColumn.ProviderType]; } diff --git a/Snowflake.Data/SnowflakeConfiguration.cs b/Snowflake.Data/SnowflakeDbConfiguration.cs similarity index 76% rename from Snowflake.Data/SnowflakeConfiguration.cs rename to Snowflake.Data/SnowflakeDbConfiguration.cs index dc8817b..07a3273 100644 --- a/Snowflake.Data/SnowflakeConfiguration.cs +++ b/Snowflake.Data/SnowflakeDbConfiguration.cs @@ -4,9 +4,9 @@ namespace Tortuga.Data.Snowflake; -public record SnowflakeConfiguration +public record SnowflakeDbConfiguration { - public SnowflakeConfiguration(bool useV2JsonParser, bool useV2ChunkDownloader, int chunkDownloaderVersion) + public SnowflakeDbConfiguration(bool useV2JsonParser, bool useV2ChunkDownloader, int chunkDownloaderVersion) { UseV2JsonParser = useV2JsonParser; UseV2ChunkDownloader = useV2ChunkDownloader; @@ -22,6 +22,6 @@ public SnowflakeConfiguration(bool useV2JsonParser, bool useV2ChunkDownloader, i public int ChunkDownloaderVersion { get; init; } - public static SnowflakeConfiguration Default { get; set; } = + public static SnowflakeDbConfiguration Default { get; set; } = new(useV2JsonParser: true, useV2ChunkDownloader: false, chunkDownloaderVersion: 3); } diff --git a/Snowflake.Data/SnowflakeConnection.cs b/Snowflake.Data/SnowflakeDbConnection.cs similarity index 88% rename from Snowflake.Data/SnowflakeConnection.cs rename to Snowflake.Data/SnowflakeDbConnection.cs index 81d2321..c21161a 100644 --- a/Snowflake.Data/SnowflakeConnection.cs +++ b/Snowflake.Data/SnowflakeDbConnection.cs @@ -14,14 +14,14 @@ namespace Tortuga.Data.Snowflake; [DesignerCategory("Code")] -public class SnowflakeConnection : DbConnection +public class SnowflakeDbConnection : DbConnection { internal ConnectionState m_ConnectionState; internal int m_ConnectionTimeout; string m_ConnectionString = ""; - public SnowflakeConnection() + public SnowflakeDbConnection() { m_ConnectionState = ConnectionState.Closed; m_ConnectionTimeout = int.Parse(SFSessionProperty.CONNECTION_TIMEOUT.GetAttribute()?.DefaultValue ?? "0", CultureInfo.InvariantCulture); @@ -56,14 +56,14 @@ public override string ConnectionString public override ConnectionState State => m_ConnectionState; internal SFSession? SfSession { get; set; } - SnowflakeConfiguration m_Configuration = SnowflakeConfiguration.Default; + SnowflakeDbConfiguration m_Configuration = SnowflakeDbConfiguration.Default; /// /// Gets or sets the configuration. /// /// The configuration. /// This defaults to SnowflakeDbConfiguration.Default. - public SnowflakeConfiguration Configuration + public SnowflakeDbConfiguration Configuration { get => m_Configuration; set @@ -123,7 +123,7 @@ public override void Open() { SfSession!.Open(); } - catch (SnowflakeException) + catch (SnowflakeDbException) { m_ConnectionState = ConnectionState.Closed; throw; @@ -132,7 +132,7 @@ public override void Open() { // Otherwise when Dispose() is called, the close request would timeout. m_ConnectionState = ConnectionState.Closed; - throw new SnowflakeException(e, SnowflakeException.CONNECTION_FAILURE_SSTATE, SnowflakeError.InternalError, "Unable to connect. " + e.Message); + throw new SnowflakeDbException(e, SnowflakeDbException.CONNECTION_FAILURE_SSTATE, SnowflakeDbError.InternalError, "Unable to connect. " + e.Message); } m_ConnectionState = ConnectionState.Open; } @@ -145,7 +145,7 @@ public override async Task OpenAsync(CancellationToken cancellationToken) { await SfSession!.OpenAsync(cancellationToken).ConfigureAwait(false); } - catch (SnowflakeException) + catch (SnowflakeDbException) { m_ConnectionState = ConnectionState.Closed; throw; @@ -159,7 +159,7 @@ public override async Task OpenAsync(CancellationToken cancellationToken) { // Otherwise when Dispose() is called, the close request would timeout. m_ConnectionState = ConnectionState.Closed; - throw new SnowflakeException(ex, SnowflakeException.CONNECTION_FAILURE_SSTATE, SnowflakeError.InternalError, "Unable to connect. " + ex.Message); + throw new SnowflakeDbException(ex, SnowflakeDbException.CONNECTION_FAILURE_SSTATE, SnowflakeDbError.InternalError, "Unable to connect. " + ex.Message); } m_ConnectionState = ConnectionState.Open; } @@ -186,12 +186,12 @@ protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLeve isolationLevel = IsolationLevel.ReadCommitted; } - return new SnowflakeTransaction(isolationLevel, this); + return new SnowflakeDbTransaction(isolationLevel, this); } protected override DbCommand CreateDbCommand() { - return new SnowflakeCommand(this); + return new SnowflakeDbCommand(this); } protected override void Dispose(bool disposing) @@ -210,7 +210,7 @@ protected override void Dispose(bool disposing) /// /// Create a new SFSession with the connection string settings. /// - /// If the connection string can't be processed + /// If the connection string can't be processed private void SetSession() { if (ConnectionString == null) diff --git a/Snowflake.Data/SnowflakeConnectionStringBuilder.cs b/Snowflake.Data/SnowflakeDbConnectionStringBuilder.cs similarity index 90% rename from Snowflake.Data/SnowflakeConnectionStringBuilder.cs rename to Snowflake.Data/SnowflakeDbConnectionStringBuilder.cs index 5d48192..253bfdb 100644 --- a/Snowflake.Data/SnowflakeConnectionStringBuilder.cs +++ b/Snowflake.Data/SnowflakeDbConnectionStringBuilder.cs @@ -8,7 +8,7 @@ namespace Tortuga.Data.Snowflake; #pragma warning disable CA1710 // Identifiers should have correct suffix -public class SnowflakeConnectionStringBuilder : DbConnectionStringBuilder, ICollection> +public class SnowflakeDbConnectionStringBuilder : DbConnectionStringBuilder, ICollection> { public void Add(KeyValuePair item) => Add(item.Key, item.Value); diff --git a/Snowflake.Data/SnowflakeDataReader.cs b/Snowflake.Data/SnowflakeDbDataReader.cs similarity index 96% rename from Snowflake.Data/SnowflakeDataReader.cs rename to Snowflake.Data/SnowflakeDbDataReader.cs index ea70c2e..1b7fb5a 100644 --- a/Snowflake.Data/SnowflakeDataReader.cs +++ b/Snowflake.Data/SnowflakeDbDataReader.cs @@ -11,17 +11,17 @@ namespace Tortuga.Data.Snowflake; -public class SnowflakeDataReader : DbDataReader, IEnumerable +public class SnowflakeDbDataReader : DbDataReader, IEnumerable { readonly CommandBehavior m_CommandBehavior; - readonly SnowflakeConnection m_Connection; + readonly SnowflakeDbConnection m_Connection; #pragma warning disable CA2213 // Disposable fields should be disposed readonly DataTable m_SchemaTable; #pragma warning restore CA2213 // Disposable fields should be disposed bool m_IsClosed; readonly SFBaseResultSet m_ResultSet; - internal SnowflakeDataReader(SFBaseResultSet resultSet, SnowflakeConnection connection, CommandBehavior commandBehavior) + internal SnowflakeDbDataReader(SFBaseResultSet resultSet, SnowflakeDbConnection connection, CommandBehavior commandBehavior) { m_ResultSet = resultSet ?? throw new ArgumentNullException(nameof(resultSet), $"{nameof(resultSet)} is null."); ; m_Connection = connection ?? throw new ArgumentNullException(nameof(connection), $"{nameof(connection)} is null."); @@ -195,7 +195,7 @@ static DataTable PopulateSchemaTable(SFBaseResultSet resultSet) table.Columns.Add(SchemaTableColumn.NumericScale, typeof(int)); table.Columns.Add(SchemaTableColumn.DataType, typeof(Type)); table.Columns.Add(SchemaTableColumn.AllowDBNull, typeof(bool)); - table.Columns.Add(SchemaTableColumn.ProviderType, typeof(SnowflakeDataType)); + table.Columns.Add(SchemaTableColumn.ProviderType, typeof(SnowflakeDbDataType)); if (resultSet.SFResultSetMetaData == null) throw new ArgumentException($"{nameof(resultSet.SFResultSetMetaData)} is null.", nameof(resultSet)); @@ -287,7 +287,7 @@ long ReadSubset(int ordinal, long dataOffset, T[]? buffer, int bufferOffset, } } - IEnumerator IEnumerable.GetEnumerator() + IEnumerator IEnumerable.GetEnumerator() { while (Read()) { diff --git a/Snowflake.Data/SnowflakeDbDataTypeExtensions.cs b/Snowflake.Data/SnowflakeDbDataTypeExtensions.cs new file mode 100644 index 0000000..905b86b --- /dev/null +++ b/Snowflake.Data/SnowflakeDbDataTypeExtensions.cs @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved. + */ + +namespace Tortuga.Data.Snowflake; + +public enum SnowflakeDbDataType +{ + None = 0, + Fixed = 1, + Real = 2, + Text = 3, + Date = 4, + Variant = 5, + TimestampLtz = 6, + TimestampNtz = 7, + TimestampTz = 8, +#pragma warning disable CA1720 // Identifier contains type name + Object = 9, +#pragma warning restore CA1720 // Identifier contains type name + Binary = 10, + Time = 11, + Boolean = 12, + Array = 13 +} + +static class SnowflakeDbDataTypeExtensions +{ + /// + /// Converts a SFDataType to its SQL representation. + /// + /// Type of the data. + public static string ToSql(this SnowflakeDbDataType dataType) + { + return dataType switch + { + SnowflakeDbDataType.None => "", + SnowflakeDbDataType.Fixed => "FIXED", + SnowflakeDbDataType.Real => "REAL", + SnowflakeDbDataType.Text => "TEXT", + SnowflakeDbDataType.Date => "DATE", + SnowflakeDbDataType.Variant => "VARIANT", + SnowflakeDbDataType.TimestampLtz => "TIMESTAMP_LTZ", + SnowflakeDbDataType.TimestampNtz => "TIMESTAMP_NTZ", + SnowflakeDbDataType.TimestampTz => "TIMESTAMP_TZ", + SnowflakeDbDataType.Object => "OBJECT", + SnowflakeDbDataType.Binary => "BINARY", + SnowflakeDbDataType.Time => "TIME", + SnowflakeDbDataType.Boolean => "BOOLEAN", + SnowflakeDbDataType.Array => "ARRAY", + _ => throw new ArgumentOutOfRangeException(nameof(dataType), dataType, "Unknown data type") + }; + } + + /// + /// Froms the SQL. + /// + /// The type. + /// SFDataType. + /// type + /// Unknow column type: {type} + public static SnowflakeDbDataType FromSql(string type) + { + if (string.IsNullOrEmpty(type)) + throw new ArgumentException($"{nameof(type)} is null or empty.", nameof(type)); + + bool CheckName(SnowflakeDbDataType candidate) + { + return string.Equals(candidate.ToString(), type, StringComparison.OrdinalIgnoreCase) + || string.Equals(candidate.ToSql(), type, StringComparison.OrdinalIgnoreCase); + } + + if (CheckName(SnowflakeDbDataType.None)) return SnowflakeDbDataType.None; + if (CheckName(SnowflakeDbDataType.Fixed)) return SnowflakeDbDataType.Fixed; + if (CheckName(SnowflakeDbDataType.Real)) return SnowflakeDbDataType.Real; + if (CheckName(SnowflakeDbDataType.Text)) return SnowflakeDbDataType.Text; + if (CheckName(SnowflakeDbDataType.Date)) return SnowflakeDbDataType.Date; + if (CheckName(SnowflakeDbDataType.Variant)) return SnowflakeDbDataType.Variant; + if (CheckName(SnowflakeDbDataType.TimestampLtz)) return SnowflakeDbDataType.TimestampLtz; + if (CheckName(SnowflakeDbDataType.TimestampNtz)) return SnowflakeDbDataType.TimestampNtz; + if (CheckName(SnowflakeDbDataType.TimestampTz)) return SnowflakeDbDataType.TimestampTz; + if (CheckName(SnowflakeDbDataType.Object)) return SnowflakeDbDataType.Object; + if (CheckName(SnowflakeDbDataType.Binary)) return SnowflakeDbDataType.Binary; + if (CheckName(SnowflakeDbDataType.Time)) return SnowflakeDbDataType.Time; + if (CheckName(SnowflakeDbDataType.Boolean)) return SnowflakeDbDataType.Boolean; + if (CheckName(SnowflakeDbDataType.Array)) return SnowflakeDbDataType.Array; + + throw new SnowflakeDbException(SnowflakeDbError.InternalError, $"Unknow column type: {type}"); + } +} diff --git a/Snowflake.Data/SnowflakeError.cs b/Snowflake.Data/SnowflakeDbError.cs similarity index 96% rename from Snowflake.Data/SnowflakeError.cs rename to Snowflake.Data/SnowflakeDbError.cs index e3ecda8..e0e7ed6 100644 --- a/Snowflake.Data/SnowflakeError.cs +++ b/Snowflake.Data/SnowflakeDbError.cs @@ -4,7 +4,7 @@ namespace Tortuga.Data.Snowflake; -public enum SnowflakeError +public enum SnowflakeDbError { None = 0, diff --git a/Snowflake.Data/SnowflakeDbException.cs b/Snowflake.Data/SnowflakeDbException.cs new file mode 100644 index 0000000..8d5babb --- /dev/null +++ b/Snowflake.Data/SnowflakeDbException.cs @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2012-2021 Snowflake Computing Inc. All rights reserved. + */ + +using System.Data.Common; +using System.Globalization; + +namespace Tortuga.Data.Snowflake; + +#pragma warning disable CA2237 // Mark ISerializable types with serializable +#pragma warning disable CA1032 // Implement standard exception constructors + +/// +/// Wraps the exception. +/// If the exception is thrown in the client side, error code from +/// 270000 to 279999 will be used. Otherwise, server side error code +/// will be used. +/// + +public sealed class SnowflakeDbException : DbException +{ + // Sql states not coming directly from the server. + internal const string CONNECTION_FAILURE_SSTATE = "08006"; + + readonly SnowflakeDbError _errorCode; + + readonly string? _sqlState; + + public SnowflakeDbException(string sqlState, int vendorCode, string? errorMessage, string queryId) : + base(errorMessage) + { + _sqlState = sqlState; + _errorCode = (SnowflakeDbError)vendorCode; + QueryId = queryId; + } + + public SnowflakeDbException(SnowflakeDbError error, params object?[] args) : + base(string.Format(CultureInfo.InvariantCulture, GetFormatString(error), args)) + { + _errorCode = error; + } + + public SnowflakeDbException(string sqlState, SnowflakeDbError error, params object[] args) : + base(string.Format(CultureInfo.InvariantCulture, GetFormatString(error), args)) + { + _errorCode = error; + _sqlState = sqlState; + } + + /// This is used to re-throw an exception without losing the stack trace when crossing a thread boundary. + internal SnowflakeDbException(SnowflakeDbException innerException) : this(innerException.Message, innerException, innerException.SnowflakeError) + { + } + + public SnowflakeDbException(string message, Exception innerException, SnowflakeDbError error) + : base(message, innerException) + { + _errorCode = error; + } + + public SnowflakeDbException(Exception innerException, SnowflakeDbError error, params object[] args) + : base(string.Format(CultureInfo.InvariantCulture, GetFormatString(error), args), innerException) + { + _errorCode = error; + } + + public SnowflakeDbException(Exception innerException, string sqlState, SnowflakeDbError error, params object[] args) + : base(string.Format(CultureInfo.InvariantCulture, GetFormatString(error), args), innerException) + { + _errorCode = error; + _sqlState = sqlState; + } + + public override int ErrorCode => (int)_errorCode; + public string? QueryId { get; } + public SnowflakeDbError SnowflakeError => _errorCode; + +#if NET5_0_OR_GREATER + public override string? SqlState { get => _sqlState; } +#else + public string? SqlState { get => _sqlState; } +#endif + + public override string ToString() + { + return $"Error: {Message} SqlState: {SqlState}, VendorCode: {_errorCode}, QueryId: {QueryId}"; + } + + static string GetFormatString(SnowflakeDbError error) + { + return error switch + { + SnowflakeDbError.InternalError => "Snowflake Internal Error: {0}", + SnowflakeDbError.ColumnIndexOutOfBound => "Column index {0} is out of bound of valid index.", + SnowflakeDbError.InvalidDataConversion => "Failed to convert data {0} from type {1} to type {2}.", + SnowflakeDbError.StatementAlreadyRunningQuery => "Another query is already running against this statement.", + SnowflakeDbError.QueryCancelled => "Query has been cancelled.", + SnowflakeDbError.MissingConnectionProperty => "Required property {0} is not provided.", + SnowflakeDbError.RequestTimeout => "Request reach its timeout.", + SnowflakeDbError.InvalidConnectionString => "Connection string is invalid: {0}", + SnowflakeDbError.UnsupportedFeature => "Feature is not supported. ", + SnowflakeDbError.DataReaderAlreadyClosed => "Data reader has already been closed.", + SnowflakeDbError.UnknownAuthenticator => "Unknown authenticator: {0}", + SnowflakeDbError.UnsupportedPlatform => "OS platform is not supported.", + SnowflakeDbError.IdpSsoTokenUrlMismatch => "Scheme/Hostname mismatch: token/sso url 1: {0} session url: {1}", + SnowflakeDbError.IdpSamlPostbackNotFound => "Cannot found the postback url from the SAML response", + SnowflakeDbError.IdpSamlPostbackInvalid => "Scheme/Hostname mismatch: postback lrl: {0} session url: {1}", + SnowflakeDbError.BrowserResponseWrongMethod => "Expect GET, but got {0}", + SnowflakeDbError.BrowserResponseInvalidPrefix => "Expect ?token=, but got {0}", + SnowflakeDbError.JwtErrorReadingPk => "Could not read private key {0}. \n Error : {1}", + SnowflakeDbError.UnsupportedDotnetType => "No corresponding Snowflake type for type {0}.", + SnowflakeDbError.UnsupportedSnowflakeTypeForParam => "Snowflake type {0} is not supported for parameters.", + SnowflakeDbError.InvalidConnectionParameterValue => "Invalid parameter value {0} for {1}", + _ => error.ToString(), + }; + } +} diff --git a/Snowflake.Data/SnowflakeParameter.cs b/Snowflake.Data/SnowflakeDbParameter.cs similarity index 80% rename from Snowflake.Data/SnowflakeParameter.cs rename to Snowflake.Data/SnowflakeDbParameter.cs index a05817f..69e4c33 100644 --- a/Snowflake.Data/SnowflakeParameter.cs +++ b/Snowflake.Data/SnowflakeDbParameter.cs @@ -9,24 +9,24 @@ namespace Tortuga.Data.Snowflake; -public class SnowflakeParameter : DbParameter +public class SnowflakeDbParameter : DbParameter { string m_ParameterName = ""; string m_SourceColumn = ""; - readonly SnowflakeDataType m_OriginType; + readonly SnowflakeDbDataType m_OriginType; - public SnowflakeParameter() + public SnowflakeDbParameter() { } - public SnowflakeParameter(string parameterName, SnowflakeDataType sfDataType) + public SnowflakeDbParameter(string parameterName, SnowflakeDbDataType sfDataType) { ParameterName = parameterName; SFDataType = sfDataType; m_OriginType = sfDataType; } - public SnowflakeParameter(int parameterIndex, SnowflakeDataType sfDataType) + public SnowflakeDbParameter(int parameterIndex, SnowflakeDbDataType sfDataType) { ParameterName = parameterIndex.ToString(CultureInfo.InvariantCulture); SFDataType = sfDataType; @@ -53,7 +53,7 @@ public override ParameterDirection Direction [AllowNull] public override string ParameterName { get => m_ParameterName; set => m_ParameterName = value ?? ""; } - public SnowflakeDataType SFDataType { get; set; } + public SnowflakeDbDataType SFDataType { get; set; } public override int Size { get; set; } [AllowNull] diff --git a/Snowflake.Data/SnowflakeParameterCollection.cs b/Snowflake.Data/SnowflakeDbParameterCollection.cs similarity index 59% rename from Snowflake.Data/SnowflakeParameterCollection.cs rename to Snowflake.Data/SnowflakeDbParameterCollection.cs index 36f0360..c67a5d9 100644 --- a/Snowflake.Data/SnowflakeParameterCollection.cs +++ b/Snowflake.Data/SnowflakeDbParameterCollection.cs @@ -7,13 +7,13 @@ namespace Tortuga.Data.Snowflake; -public class SnowflakeParameterCollection : DbParameterCollection, IList +public class SnowflakeDbParameterCollection : DbParameterCollection, IList { readonly object m_SyncRoot = new(); - readonly List m_ParameterList = new(); + readonly List m_ParameterList = new(); - internal SnowflakeParameterCollection() + internal SnowflakeDbParameterCollection() { } @@ -23,19 +23,19 @@ internal SnowflakeParameterCollection() public override int Add(object value) { - m_ParameterList.Add((SnowflakeParameter)value); + m_ParameterList.Add((SnowflakeDbParameter)value); return m_ParameterList.Count - 1; } - public int Add(SnowflakeParameter value) + public int Add(SnowflakeDbParameter value) { m_ParameterList.Add(value); return m_ParameterList.Count - 1; } - public SnowflakeParameter Add(string parameterName, SnowflakeDataType dataType) + public SnowflakeDbParameter Add(string parameterName, SnowflakeDbDataType dataType) { - var parameter = new SnowflakeParameter(parameterName, dataType); + var parameter = new SnowflakeDbParameter(parameterName, dataType); m_ParameterList.Add(parameter); return parameter; } @@ -45,7 +45,7 @@ public override void AddRange(Array values) if (values == null) throw new ArgumentNullException(nameof(values), $"{nameof(values)} is null."); - foreach (SnowflakeParameter? value in values) + foreach (SnowflakeDbParameter? value in values) m_ParameterList.Add(value ?? throw new ArgumentException("The values array contains a null.", nameof(values))); } @@ -55,7 +55,7 @@ public override void AddRange(Array values) public override bool Contains(object value) { - return value is SnowflakeParameter parameter && m_ParameterList.Contains(parameter); + return value is SnowflakeDbParameter parameter && m_ParameterList.Contains(parameter); } public override void CopyTo(Array array, int index) @@ -80,12 +80,12 @@ public override int IndexOf(string parameterName) public override int IndexOf(object value) { - return value is not SnowflakeParameter parameter ? -1 : m_ParameterList.IndexOf(parameter); + return value is not SnowflakeDbParameter parameter ? -1 : m_ParameterList.IndexOf(parameter); } - public override void Insert(int index, object value) => m_ParameterList.Insert(index, (SnowflakeParameter)value); + public override void Insert(int index, object value) => m_ParameterList.Insert(index, (SnowflakeDbParameter)value); - public override void Remove(object value) => m_ParameterList.Remove((SnowflakeParameter)value); + public override void Remove(object value) => m_ParameterList.Remove((SnowflakeDbParameter)value); public override void RemoveAt(string parameterName) => m_ParameterList.RemoveAt(IndexOf(parameterName)); @@ -97,29 +97,29 @@ public override int IndexOf(object value) protected override void SetParameter(string parameterName, DbParameter value) { - m_ParameterList[IndexOf(parameterName)] = (SnowflakeParameter)value; + m_ParameterList[IndexOf(parameterName)] = (SnowflakeDbParameter)value; } protected override void SetParameter(int index, DbParameter value) { - m_ParameterList[index] = (SnowflakeParameter)value; + m_ParameterList[index] = (SnowflakeDbParameter)value; } - public int IndexOf(SnowflakeParameter item) => m_ParameterList.IndexOf(item); + public int IndexOf(SnowflakeDbParameter item) => m_ParameterList.IndexOf(item); - public void Insert(int index, SnowflakeParameter item) => m_ParameterList.Insert(index, item); + public void Insert(int index, SnowflakeDbParameter item) => m_ParameterList.Insert(index, item); - void ICollection.Add(SnowflakeParameter item) => Add(item); + void ICollection.Add(SnowflakeDbParameter item) => Add(item); - public bool Contains(SnowflakeParameter item) => m_ParameterList.Contains(item); + public bool Contains(SnowflakeDbParameter item) => m_ParameterList.Contains(item); - public void CopyTo(SnowflakeParameter[] array, int arrayIndex) => m_ParameterList.CopyTo(array, arrayIndex); + public void CopyTo(SnowflakeDbParameter[] array, int arrayIndex) => m_ParameterList.CopyTo(array, arrayIndex); - public bool Remove(SnowflakeParameter item) => m_ParameterList.Remove(item); + public bool Remove(SnowflakeDbParameter item) => m_ParameterList.Remove(item); - IEnumerator IEnumerable.GetEnumerator() => m_ParameterList.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => m_ParameterList.GetEnumerator(); - public new SnowflakeParameter this[int index] + public new SnowflakeDbParameter this[int index] { get => m_ParameterList[index]; set => m_ParameterList[index] = value; diff --git a/Snowflake.Data/SnowflakeProviderFactory.cs b/Snowflake.Data/SnowflakeDbProviderFactory.cs similarity index 71% rename from Snowflake.Data/SnowflakeProviderFactory.cs rename to Snowflake.Data/SnowflakeDbProviderFactory.cs index 1163c06..6f9dd47 100644 --- a/Snowflake.Data/SnowflakeProviderFactory.cs +++ b/Snowflake.Data/SnowflakeDbProviderFactory.cs @@ -6,37 +6,37 @@ namespace Tortuga.Data.Snowflake; -public sealed class SnowflakeProviderFactory : DbProviderFactory +public sealed class SnowflakeDbProviderFactory : DbProviderFactory { - public static readonly SnowflakeProviderFactory Instance = new(); + public static readonly SnowflakeDbProviderFactory Instance = new(); /// /// Returns a strongly typed instance. /// - public override DbCommand CreateCommand() => new SnowflakeCommand(); + public override DbCommand CreateCommand() => new SnowflakeDbCommand(); /// /// Returns a strongly typed instance. /// - public override DbConnection CreateConnection() => new SnowflakeConnection(); + public override DbConnection CreateConnection() => new SnowflakeDbConnection(); /// /// Returns a strongly typed instance. /// - public override DbParameter CreateParameter() => new SnowflakeParameter(); + public override DbParameter CreateParameter() => new SnowflakeDbParameter(); /// /// Returns a strongly typed instance. /// - public override DbConnectionStringBuilder CreateConnectionStringBuilder() => new SnowflakeConnectionStringBuilder(); + public override DbConnectionStringBuilder CreateConnectionStringBuilder() => new SnowflakeDbConnectionStringBuilder(); /// /// Returns a strongly typed instance. /// - public override DbCommandBuilder CreateCommandBuilder() => new SnowflakeCommandBuilder(); + public override DbCommandBuilder CreateCommandBuilder() => new SnowflakeDbCommandBuilder(); /// /// Returns a strongly typed instance. /// - public override DbDataAdapter CreateDataAdapter() => new SnowlfakeDataAdapter(); + public override DbDataAdapter CreateDataAdapter() => new SnowlfakeDbDataAdapter(); } diff --git a/Snowflake.Data/SnowflakeTransaction.cs b/Snowflake.Data/SnowflakeDbTransaction.cs similarity index 89% rename from Snowflake.Data/SnowflakeTransaction.cs rename to Snowflake.Data/SnowflakeDbTransaction.cs index c4be46e..c9720d6 100644 --- a/Snowflake.Data/SnowflakeTransaction.cs +++ b/Snowflake.Data/SnowflakeDbTransaction.cs @@ -7,13 +7,13 @@ namespace Tortuga.Data.Snowflake; -public class SnowflakeTransaction : DbTransaction +public class SnowflakeDbTransaction : DbTransaction { - readonly SnowflakeConnection m_Connection; + readonly SnowflakeDbConnection m_Connection; bool m_Disposed; readonly IsolationLevel m_IsolationLevel; - public SnowflakeTransaction(IsolationLevel isolationLevel, SnowflakeConnection connection) + public SnowflakeDbTransaction(IsolationLevel isolationLevel, SnowflakeDbConnection connection) { if (isolationLevel != IsolationLevel.ReadCommitted) throw new ArgumentOutOfRangeException(nameof(isolationLevel), isolationLevel, "Only IsolationLevel.ReadCommitted is supported."); diff --git a/Snowflake.Data/SnowflakeException.cs b/Snowflake.Data/SnowflakeException.cs deleted file mode 100644 index 086bf72..0000000 --- a/Snowflake.Data/SnowflakeException.cs +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2012-2021 Snowflake Computing Inc. All rights reserved. - */ - -using System.Data.Common; -using System.Globalization; - -namespace Tortuga.Data.Snowflake; - -#pragma warning disable CA2237 // Mark ISerializable types with serializable -#pragma warning disable CA1032 // Implement standard exception constructors - -/// -/// Wraps the exception. -/// If the exception is thrown in the client side, error code from -/// 270000 to 279999 will be used. Otherwise, server side error code -/// will be used. -/// - -public sealed class SnowflakeException : DbException -{ - // Sql states not coming directly from the server. - internal const string CONNECTION_FAILURE_SSTATE = "08006"; - - readonly SnowflakeError _errorCode; - - readonly string? _sqlState; - - public SnowflakeException(string sqlState, int vendorCode, string? errorMessage, string queryId) : - base(errorMessage) - { - _sqlState = sqlState; - _errorCode = (SnowflakeError)vendorCode; - QueryId = queryId; - } - - public SnowflakeException(SnowflakeError error, params object?[] args) : - base(string.Format(CultureInfo.InvariantCulture, GetFormatString(error), args)) - { - _errorCode = error; - } - - public SnowflakeException(string sqlState, SnowflakeError error, params object[] args) : - base(string.Format(CultureInfo.InvariantCulture, GetFormatString(error), args)) - { - _errorCode = error; - _sqlState = sqlState; - } - - /// This is used to re-throw an exception without losing the stack trace when crossing a thread boundary. - internal SnowflakeException(SnowflakeException innerException) : this(innerException.Message, innerException, innerException.SnowflakeError) - { - } - - public SnowflakeException(string message, Exception innerException, SnowflakeError error) - : base(message, innerException) - { - _errorCode = error; - } - - public SnowflakeException(Exception innerException, SnowflakeError error, params object[] args) - : base(string.Format(CultureInfo.InvariantCulture, GetFormatString(error), args), innerException) - { - _errorCode = error; - } - - public SnowflakeException(Exception innerException, string sqlState, SnowflakeError error, params object[] args) - : base(string.Format(CultureInfo.InvariantCulture, GetFormatString(error), args), innerException) - { - _errorCode = error; - _sqlState = sqlState; - } - - public override int ErrorCode => (int)_errorCode; - public string? QueryId { get; } - public SnowflakeError SnowflakeError => _errorCode; - -#if NET5_0_OR_GREATER - public override string? SqlState { get => _sqlState; } -#else - public string? SqlState { get => _sqlState; } -#endif - - public override string ToString() - { - return $"Error: {Message} SqlState: {SqlState}, VendorCode: {_errorCode}, QueryId: {QueryId}"; - } - - static string GetFormatString(SnowflakeError error) - { - return error switch - { - SnowflakeError.InternalError => "Snowflake Internal Error: {0}", - SnowflakeError.ColumnIndexOutOfBound => "Column index {0} is out of bound of valid index.", - SnowflakeError.InvalidDataConversion => "Failed to convert data {0} from type {1} to type {2}.", - SnowflakeError.StatementAlreadyRunningQuery => "Another query is already running against this statement.", - SnowflakeError.QueryCancelled => "Query has been cancelled.", - SnowflakeError.MissingConnectionProperty => "Required property {0} is not provided.", - SnowflakeError.RequestTimeout => "Request reach its timeout.", - SnowflakeError.InvalidConnectionString => "Connection string is invalid: {0}", - SnowflakeError.UnsupportedFeature => "Feature is not supported. ", - SnowflakeError.DataReaderAlreadyClosed => "Data reader has already been closed.", - SnowflakeError.UnknownAuthenticator => "Unknown authenticator: {0}", - SnowflakeError.UnsupportedPlatform => "OS platform is not supported.", - SnowflakeError.IdpSsoTokenUrlMismatch => "Scheme/Hostname mismatch: token/sso url 1: {0} session url: {1}", - SnowflakeError.IdpSamlPostbackNotFound => "Cannot found the postback url from the SAML response", - SnowflakeError.IdpSamlPostbackInvalid => "Scheme/Hostname mismatch: postback lrl: {0} session url: {1}", - SnowflakeError.BrowserResponseWrongMethod => "Expect GET, but got {0}", - SnowflakeError.BrowserResponseInvalidPrefix => "Expect ?token=, but got {0}", - SnowflakeError.JwtErrorReadingPk => "Could not read private key {0}. \n Error : {1}", - SnowflakeError.UnsupportedDotnetType => "No corresponding Snowflake type for type {0}.", - SnowflakeError.UnsupportedSnowflakeTypeForParam => "Snowflake type {0} is not supported for parameters.", - SnowflakeError.InvalidConnectionParameterValue => "Invalid parameter value {0} for {1}", - _ => error.ToString(), - }; - } -} diff --git a/Snowflake.Data/SnowlfakeDataAdapter.cs b/Snowflake.Data/SnowlfakeDataAdapter.cs deleted file mode 100644 index 33b14c0..0000000 --- a/Snowflake.Data/SnowlfakeDataAdapter.cs +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved. - */ - -using System.Data.Common; - -namespace Tortuga.Data.Snowflake; - -public class SnowlfakeDataAdapter : DbDataAdapter -{ - public SnowlfakeDataAdapter() - { - } - - public SnowlfakeDataAdapter(SnowflakeCommand selectCommand) : this() - { - SelectCommand = selectCommand; - } - - public SnowlfakeDataAdapter(string selectCommandText, SnowflakeConnection selectConnection) : this() - { - SelectCommand = new SnowflakeCommand(selectConnection) { CommandText = selectCommandText }; - } - - new public SnowflakeCommand? DeleteCommand - { - get { return (SnowflakeCommand?)base.DeleteCommand; } - set { base.DeleteCommand = value; } - } - - new public SnowflakeCommand? InsertCommand - { - get { return (SnowflakeCommand?)base.InsertCommand; } - set { base.InsertCommand = value; } - } - - new public SnowflakeCommand? SelectCommand - { - get { return (SnowflakeCommand?)base.SelectCommand; } - set { base.SelectCommand = value; } - } - - new public SnowflakeCommand? UpdateCommand - { - get { return (SnowflakeCommand?)base.UpdateCommand; } - set { base.UpdateCommand = value; } - } -} diff --git a/Snowflake.Data/SnowlfakeDbDataAdapter.cs b/Snowflake.Data/SnowlfakeDbDataAdapter.cs new file mode 100644 index 0000000..3be9d47 --- /dev/null +++ b/Snowflake.Data/SnowlfakeDbDataAdapter.cs @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved. + */ + +using System.Data.Common; + +namespace Tortuga.Data.Snowflake; + +public class SnowlfakeDbDataAdapter : DbDataAdapter +{ + public SnowlfakeDbDataAdapter() + { + } + + public SnowlfakeDbDataAdapter(SnowflakeDbCommand selectCommand) : this() + { + SelectCommand = selectCommand; + } + + public SnowlfakeDbDataAdapter(string selectCommandText, SnowflakeDbConnection selectConnection) : this() + { + SelectCommand = new SnowflakeDbCommand(selectConnection) { CommandText = selectCommandText }; + } + + new public SnowflakeDbCommand? DeleteCommand + { + get { return (SnowflakeDbCommand?)base.DeleteCommand; } + set { base.DeleteCommand = value; } + } + + new public SnowflakeDbCommand? InsertCommand + { + get { return (SnowflakeDbCommand?)base.InsertCommand; } + set { base.InsertCommand = value; } + } + + new public SnowflakeDbCommand? SelectCommand + { + get { return (SnowflakeDbCommand?)base.SelectCommand; } + set { base.SelectCommand = value; } + } + + new public SnowflakeDbCommand? UpdateCommand + { + get { return (SnowflakeDbCommand?)base.UpdateCommand; } + set { base.UpdateCommand = value; } + } +} diff --git a/Snowflake.Data/Tortuga.Data.Snowflake.csproj b/Snowflake.Data/Tortuga.Data.Snowflake.csproj index cea28a2..6877b98 100644 --- a/Snowflake.Data/Tortuga.Data.Snowflake.csproj +++ b/Snowflake.Data/Tortuga.Data.Snowflake.csproj @@ -12,7 +12,7 @@ Snowflake Connector for .NET howryu, tchen, Jonathan Allen Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved. Modifications Jonathan Allen 2022 - 3.0.1 + 3.0.2 10.0 true true