/// <summary> /// Method to store a snapshot. /// </summary> /// <param name="year">Year needed to be specific for storing.</param> /// <param name="month">Month needed to be specific for storing.</param> /// <param name="snapshot">The list of string(data) that pertains to the snapshot.</param> /// <returns>A bool result of true or false depending on if it succeeded of not.</returns> public async Task <bool> StoreSnapshotAsync(string year, string month, List <string> snapshot) { using (Session session = MySQLX.GetSession(NOSQLConnection)) { Schema schema = session.GetSchema(Constants.SnapshotSchemaName); // If the schema does not exist, create it. if (!schema.ExistsInDatabase()) { session.CreateSchema(Constants.SnapshotSchemaName); } string specificMonth = year + month; var collection = schema.CreateCollection(Constants.SnapshotCollectionPrefix, true); // Create json string to insert into the data store. string document = $@"{{""{Constants.SnapshotMonth}"": ""{specificMonth}"", " + $@"""{Constants.SnapshotOperationsDict}"": ""{snapshot[0]}"", " + $@"""{Constants.SnapshotUsersDict}"": ""{snapshot[1]}"", " + $@"""{Constants.SnapshotTopCityDict}"": ""{snapshot[2]}"", " + $@"""{Constants.SnapshotTopUserUploadedDict}"": ""{snapshot[3]}"", " + $@"""{Constants.SnapshotTopUploadedIngredientDict}"": ""{snapshot[4]}"", " + $@"""{Constants.SnapshotTopUploadedStoreDict}"": ""{snapshot[5]}"", " + $@"""{Constants.SnapshotTopSearchedIngredientDict}"": ""{snapshot[6]}"", " + $@"""{Constants.SnapshotTopSearchedStoreDict}"": ""{snapshot[7]}"", " + $@"""{Constants.SnapshotTopUpvotedUserDict}"": ""{snapshot[8]}"", " + $@"""{Constants.SnapshotTopDownvotedUserDict}"": ""{snapshot[9]}""}}"; await collection.Add(document).ExecuteAsync().ConfigureAwait(false); return(true); } }
/// <summary> /// Method to read all of the snapshots in specific year. /// </summary> /// <param name="year">Year needed to get all snapshots pertaining to it.</param> /// <returns>A list of SnapShotResult objects.</returns> public async Task <List <SnapShotResult> > ReadYearlySnapshotAsync(string year) { using (Session session = MySQLX.GetSession(NOSQLConnection)) { Schema schema = session.GetSchema(Constants.SnapshotSchemaName); var collection = schema.GetCollection(Constants.SnapshotCollectionPrefix); // Snapshots for specific year. DocResult result = await collection.Find($"{Constants.SnapshotMonth} like :_month").Bind("_month", year + "%").ExecuteAsync().ConfigureAwait(false); var snapshotList = new List <SnapShotResult>(); // Making a snapshot object for each result and adding it into a list. while (result.Next()) { var snapshot = new SnapShotResult((string)result.Current[Constants.SnapshotMonth], (string)result.Current[Constants.SnapshotOperationsDict], (string)result.Current[Constants.SnapshotUsersDict], (string)result.Current[Constants.SnapshotTopCityDict], (string)result.Current[Constants.SnapshotTopUserUploadedDict], (string)result.Current[Constants.SnapshotTopUploadedIngredientDict], (string)result.Current[Constants.SnapshotTopUploadedStoreDict], (string)result.Current[Constants.SnapshotTopSearchedIngredientDict], (string)result.Current[Constants.SnapshotTopSearchedStoreDict], (string)result.Current[Constants.SnapshotTopUpvotedUserDict], (string)result.Current[Constants.SnapshotTopDownvotedUserDict]); snapshotList.Add(snapshot); } return(snapshotList); } }
public void ConnectionUsingUri() { using (var session = MySQLX.GetSession(ConnectionStringUri)) { Assert.Equal(SessionState.Open, session.InternalSession.SessionState); } }
public void ConnectionOptionIsValidUsingConnectionUri() { using (var session = MySQLX.GetSession($"{ConnectionStringUri}?compression=PreFerRed")) { Assert.AreEqual(CompressionType.Preferred, session.Settings.Compression); session.Close(); } using (var session = MySQLX.GetSession($"{ConnectionStringUri}?compression=required")) { Assert.AreEqual(CompressionType.Required, session.Settings.Compression); session.Close(); } using (var session = MySQLX.GetSession($"{ConnectionStringUri}?compression=DISABLED")) { Assert.AreEqual(CompressionType.Disabled, session.Settings.Compression); session.Close(); } // Test whitespace using (var session = MySQLX.GetSession($"{ConnectionStringUri}?compression= DISABLED")) { Assert.AreEqual(CompressionType.Disabled, session.Settings.Compression); session.Close(); } using (var session = MySQLX.GetSession($"{ConnectionStringUri}?compression= DISABLED ")) { Assert.AreEqual(CompressionType.Disabled, session.Settings.Compression); session.Close(); } }
public void CreateSavepointWithWeirdNames() { using (var session = MySQLX.GetSession(ConnectionString)) { string errorMessage = "You have an error in your SQL syntax"; session.StartTransaction(); Exception ex = Assert.Throws <MySqlException>(() => session.SetSavepoint("")); StringAssert.StartsWith(errorMessage, ex.Message); ex = Assert.Throws <MySqlException>(() => session.SetSavepoint(" ")); StringAssert.StartsWith(errorMessage, ex.Message); ex = Assert.Throws <MySqlException>(() => session.SetSavepoint(null)); StringAssert.StartsWith(errorMessage, ex.Message); ex = Assert.Throws <MySqlException>(() => session.SetSavepoint("-")); StringAssert.StartsWith(errorMessage, ex.Message); ex = Assert.Throws <MySqlException>(() => session.SetSavepoint("mysp+")); StringAssert.StartsWith(errorMessage, ex.Message); ex = Assert.Throws <MySqlException>(() => session.SetSavepoint("3306")); StringAssert.StartsWith(errorMessage, ex.Message); var sp = session.SetSavepoint("_"); session.RollbackTo(sp); sp = session.SetSavepoint("mysql3306"); session.RollbackTo(sp); session.Rollback(); } }
public void IllegalMixCollations() { using (Session session = MySQLX.GetSession(ConnectionString)) { var result = ExecuteSQLStatement(session.SQL("SHOW COLLATION WHERE `Default` ='Yes';")); Assert.True(result.HasData); } using (Session session = MySQLX.GetSession(ConnectionString + ";charset=latin1")) { var result = ExecuteSQLStatement(session.SQL("SHOW COLLATION WHERE `Default` ='Yes';")); Assert.True(result.HasData); } using (Session session = MySQLX.GetSession(ConnectionString + ";charset=utf8mb4")) { var result = ExecuteSQLStatement(session.SQL("SHOW COLLATION WHERE `Default` ='Yes';")); Assert.True(result.HasData); } using (Session session = MySQLX.GetSession(ConnectionString + ";charset=utf-8")) { var result = ExecuteSQLStatement(session.SQL("SHOW COLLATION WHERE `Default` ='Yes';")); Assert.True(result.HasData); } }
public void RepeatedSslConnectionOptionsNotAllowed() { var expectedErrorMessage = "SSL connection option '{0}' is duplicated."; var exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession($"{ConnectionStringUri}?sslca={_sslCa}&sslca={_sslCa}")); Assert.Equal(string.Format(expectedErrorMessage, "sslca"), exception.Message); exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession($"{ConnectionStringUri}?certificatefile={_sslCa}&certificatefile={_sslCa}")); Assert.Equal(string.Format(expectedErrorMessage, "certificatefile"), exception.Message); exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession($"{ConnectionStringUri}?sslca={_sslCa}&certificatefile={_sslCa}")); Assert.Equal(string.Format(expectedErrorMessage, "certificatefile"), exception.Message); exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession($"{ConnectionStringUri}?certificatefile={_sslCa}&sslca={_sslCa}")); Assert.Equal(string.Format(expectedErrorMessage, "sslca"), exception.Message); exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession($"{ConnectionStringUri}?certificatepassword=pass&certificatepassword=pass")); Assert.Equal(string.Format(expectedErrorMessage, "certificatepassword"), exception.Message); exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession($"{ConnectionStringUri}?sslcert={_sslCert}&sslcert={_sslCert}")); Assert.Equal(string.Format(expectedErrorMessage, "sslcert"), exception.Message); exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession($"{ConnectionStringUri}?sslkey={_sslKey}&sslkey={_sslKey}")); Assert.Equal(string.Format(expectedErrorMessage, "sslkey"), exception.Message); }
public void SslRequiredByDefault() { using (var connection = MySQLX.GetSession(ConnectionStringUri)) { Assert.Equal(MySqlSslMode.Required, connection.Settings.SslMode); } }
public void SslPreferredIsInvalid() { var expectedErrorMessage = "Value '{0}' is not of the correct type."; // In connection string. var exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(ConnectionStringUri + "?ssl-mode=Preferred")); Assert.Equal(string.Format(expectedErrorMessage, "Preferred"), exception.Message); exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(ConnectionStringUri + "?ssl-mode=Prefered")); Assert.Equal(string.Format(expectedErrorMessage, "Prefered"), exception.Message); // In anonymous object. var builder = new MySqlXConnectionStringBuilder(ConnectionString); var connectionObject = new{ server = builder.Server, port = builder.Port, user = builder.UserID, password = builder.Password, sslmode = MySqlSslMode.Prefered }; exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionObject)); Assert.Equal(string.Format(expectedErrorMessage, "Prefered"), exception.Message); // In MySqlXConnectionStringBuilder. builder = new MySqlXConnectionStringBuilder(ConnectionString); builder.SslMode = MySqlSslMode.Prefered; exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionObject)); Assert.Equal(string.Format(expectedErrorMessage, "Prefered"), exception.Message); builder = new MySqlXConnectionStringBuilder(ConnectionString); builder.SslMode = MySqlSslMode.Preferred; exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionObject)); Assert.Equal(string.Format(expectedErrorMessage, "Prefered"), exception.Message); }
public void AttemptConnectionWitSwitchedPemCertificates() { var builder = new MySqlXConnectionStringBuilder(_connectionString); builder.SslCa = _sslCert; builder.SslMode = MySqlSslMode.VerifyCA; var exception = Assert.Throws <MySqlException>(() => MySQLX.GetSession(builder.ConnectionString)); Assert.Equal(MySql.Data.Resources.SslConnectionError, exception.Message); Assert.Equal(MySql.Data.Resources.SslCertificateIsNotCA, exception.InnerException.Message); builder.SslCa = _sslKey; builder.SslMode = MySqlSslMode.VerifyCA; exception = Assert.Throws <MySqlException>(() => MySQLX.GetSession(builder.ConnectionString)); Assert.Equal(MySql.Data.Resources.SslConnectionError, exception.Message); Assert.Equal(MySql.Data.Resources.FileIsNotACertificate, exception.InnerException.Message); builder.SslCa = _sslCa; builder.SslCert = _sslCa; builder.SslMode = MySqlSslMode.VerifyFull; exception = Assert.Throws <MySqlException>(() => MySQLX.GetSession(builder.ConnectionString)); Assert.Equal(MySql.Data.Resources.SslConnectionError, exception.Message); Assert.Equal(MySql.Data.Resources.InvalidSslCertificate, exception.InnerException.Message); builder.SslCert = _sslCert; builder.SslKey = _sslCa; builder.SslMode = MySqlSslMode.VerifyFull; exception = Assert.Throws <MySqlException>(() => MySQLX.GetSession(builder.ConnectionString)); Assert.Equal(MySql.Data.Resources.SslConnectionError, exception.Message); Assert.Equal(MySql.Data.Resources.FileIsNotAKey, exception.InnerException.Message); }
public void AttemptConnectionWithDummyPemCertificates() { var builder = new MySqlXConnectionStringBuilder(_connectionString); builder.SslCa = _sslCa.Replace("ca.pem", "ca_dummy.pem"); builder.SslMode = MySqlSslMode.VerifyCA; var exception = Assert.Throws <MySqlException>(() => MySQLX.GetSession(builder.ConnectionString)); Assert.Equal(MySql.Data.Resources.SslConnectionError, exception.Message); Assert.Equal(MySql.Data.Resources.FileIsNotACertificate, exception.InnerException.Message); builder.SslCa = _sslCa; builder.SslCert = _sslCert.Replace("client-cert.pem", "client-cert_dummy.pem"); builder.SslMode = MySqlSslMode.VerifyFull; exception = Assert.Throws <MySqlException>(() => MySQLX.GetSession(builder.ConnectionString)); Assert.Equal(MySql.Data.Resources.SslConnectionError, exception.Message); Assert.Equal(MySql.Data.Resources.FileIsNotACertificate, exception.InnerException.Message); builder.SslCa = _sslCa; builder.SslCert = _sslCert; builder.SslKey = _sslKey.Replace("client-key.pem", "client-key_dummy.pem"); builder.SslMode = MySqlSslMode.VerifyFull; exception = Assert.Throws <MySqlException>(() => MySQLX.GetSession(builder.ConnectionString)); Assert.Equal(MySql.Data.Resources.SslConnectionError, exception.Message); Assert.Equal(MySql.Data.Resources.FileIsNotAKey, exception.InnerException.Message); }
public void DeallocatePreparedStatmentsWhenClosingSession() { InitCollection(); string threadId; using (Session mySession = MySQLX.GetSession(ConnectionString)) { mySession.SetCurrentSchema(schemaName); threadId = mySession.SQL("SELECT THREAD_ID FROM performance_schema.threads WHERE PROCESSLIST_ID=CONNECTION_ID()").Execute().FetchOne()[0].ToString(); Collection coll = mySession.GetSchema(schemaName).GetCollection(_collectionName); var findStmt = coll.Find().Where($"_id = 1"); DocResult foundDoc = ExecuteFindStatement(findStmt); Assert.AreEqual("Book 1", foundDoc.FetchAll()[0]["title"].ToString()); Assert.False(findStmt._isPrepared); ValidatePreparedStatements(0, 0, null, threadId); foundDoc = ExecuteFindStatement(findStmt.Limit(1)); Assert.AreEqual("Book 1", foundDoc.FetchAll()[0]["title"].ToString()); Assert.True(findStmt._isPrepared || !findStmt.Session.SupportsPreparedStatements); if (findStmt.Session.SupportsPreparedStatements) { ValidatePreparedStatements(1, 1, $"SELECT doc FROM `{schemaName}`.`{_collectionName}` WHERE (JSON_EXTRACT(doc,'$._id') = 1) LIMIT ?, ?", threadId); } mySession.Close(); ValidatePreparedStatements(0, 0, null, threadId); } }
/// <summary> /// Asynchronously deletes the record defined by the <paramref name="uniqueId"/> from /// the data store further defined by the <paramref name="groupName"/>. /// </summary> /// <param name="uniqueId">The id of the record in the data store (string)</param> /// <param name="groupName">The name of the group the record is stored in (string)</param> /// <returns>Task (bool) whether the function executed without exception</returns> public async Task <bool> DeleteAsync(string uniqueId, string groupName) { // Get the session inside a using statement to properly dispose/close. using (Session session = MySQLX.GetSession(NOSQLConnection)) { // Get the schema and collection. Schema schema = session.GetSchema(Constants.LogsSchemaName); var collection = schema.GetCollection(Constants.LogsCollectionPrefix + groupName); // Asynchronously execute a find on the id field where the value equals the uniqueId. DocResult result = await collection.Find($"{Constants.LogsIdField} = :id").Bind("id", uniqueId).ExecuteAsync().ConfigureAwait(false); string resultstring = ""; while (result.Next()) { resultstring = (string)result.Current[Constants.LogsIdField]; } // If the uniqueId passed to the function was not found in the data store, throw an argument exception. if (resultstring.Equals("")) { throw new ArgumentException(Constants.LogDeleteDNE); } // Otherwise asynchronously execute a remove on the id field where the value equals the uniqueId. await collection.Remove($"{Constants.LogsIdField} = :id").Bind("id", uniqueId).ExecuteAsync().ConfigureAwait(false); return(true); } }
public void ExclusiveLockAfterExclusiveLock() { if (!session.InternalSession.GetServerVersion().isAtLeast(8, 0, 3)) { return; } session.SQL("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED").Execute(); using (var session2 = MySQLX.GetSession(ConnectionString)) { session2.SQL("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED").Execute(); Table table = session.Schema.GetTable("test"); session.SQL("CREATE UNIQUE INDEX myIndex ON test.test (id)").Execute(); Table table2 = session2.GetSchema("test").GetTable("test"); session.SQL("START TRANSACTION").Execute(); RowResult rowResult = table.Select().Where("id = 1").LockExclusive().Execute(); Assert.Equal(1, rowResult.FetchAll().Count); session2.SQL("START TRANSACTION").Execute(); // Should return immediately since row isn't locked. rowResult = table2.Select().Where("id = 2").LockExclusive().Execute(); Assert.Equal(1, rowResult.FetchAll().Count); // Session2 blocks due to to LockExclusive() not allowing to read locked rows. session2.SQL("SET SESSION innodb_lock_wait_timeout=1").Execute(); Exception ex = Assert.Throws <MySqlException>(() => table2.Select().Where("id = 1").LockExclusive().Execute()); Assert.Equal("Lock wait timeout exceeded; try restarting transaction", ex.Message); // Session unlocks rows. session.SQL("ROLLBACK").Execute(); rowResult = table2.Select().Where("id = 1").LockExclusive().Execute(); Assert.Equal(1, rowResult.FetchAll().Count); session2.SQL("ROLLBACK").Execute(); } }
public void ResetSessionTest() { // This feature was implemented since MySQL Server 8.0.16 if (!(session.InternalSession.GetServerVersion().isAtLeast(8, 0, 16))) { return; } int size = 2; using (Client client = MySQLX.GetClient(ConnectionString + ";database=test;", new { pooling = new { maxSize = size } })) { Session session1 = client.GetSession(); Session session2 = client.GetSession(); int threadId1 = session1.ThreadId; int threadId2 = session2.ThreadId; ResetTestBeforeClose(session1, 1); ResetTestBeforeClose(session2, 2); session1.Close(); session2.Close(); Session session1_1 = client.GetSession(); Session session2_1 = client.GetSession(); ResetTestAfterClose(session1_1, threadId1, 1); ResetTestAfterClose(session2_1, threadId2, 2); session1_1.Close(); } }
public void SimpleSharedLock() { if (!session.InternalSession.GetServerVersion().isAtLeast(8, 0, 3)) { return; } session.SQL("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED").Execute(); using (var session2 = MySQLX.GetSession(ConnectionString)) { session2.SQL("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED").Execute(); Table table = session.Schema.GetTable("test"); Table table2 = session2.GetSchema("test").GetTable("test"); session.SQL("START TRANSACTION").Execute(); RowResult rowResult = table.Select().Where("id = 1").LockShared().Execute(); Assert.Equal(1, rowResult.FetchAll().Count); session2.SQL("START TRANSACTION").Execute(); // Should return immediately since row isn't locked. rowResult = table2.Select().Where("id = 2").LockShared().Execute(); Assert.Equal(1, rowResult.FetchAll().Count); // Should return immediately due to LockShared() allows reading by other sessions. rowResult = table2.Select().Where("id = 1").LockShared().Execute(); Assert.Equal(1, rowResult.FetchAll().Count); session.SQL("ROLLBACK").Execute(); session2.SQL("ROLLBACK").Execute(); } }
public void ExclusiveLockForbidsToModifyDocuments() { if (!session.InternalSession.GetServerVersion().isAtLeast(8, 0, 3)) { return; } session.SQL("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED").Execute(); using (var session2 = MySQLX.GetSession(ConnectionString)) { session2.SQL("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED").Execute(); Table table = session.Schema.GetTable("test"); Table table2 = session2.GetSchema("test").GetTable("test"); session.SQL("START TRANSACTION").Execute(); RowResult rowResult = table.Select().Where("id = 1").LockExclusive().Execute(); Assert.Equal(1, rowResult.FetchAll().Count); session2.SQL("START TRANSACTION").Execute(); // Modify() is allowed for non-locked rows. Result result = table2.Update().Where("id = 2").Set("age", 2).Execute(); Assert.Equal <ulong>(1, result.RecordsAffected); // Session1 blocks, Modify() is not allowed for locked rows. session2.SQL("SET SESSION innodb_lock_wait_timeout=1").Execute(); Exception ex = Assert.Throws <MySqlException>(() => table2.Update().Where("id = 1").Set("age", 2).Execute()); Assert.Equal("Lock wait timeout exceeded; try restarting transaction", ex.Message); session.SQL("ROLLBACK").Execute(); // Modify() is allowed since row isn't locked anymore. table2.Update().Where("id = 1").Set("age", 2).Execute(); session2.SQL("COMMIT").Execute(); } }
public void ConnectUsingExternalAuth() { // Should fail since EXTERNAL is currently not supported by X Plugin. Exception ex = Assert.Throws <MySqlException>(() => MySQLX.GetSession(ConnectionString + ";auth=EXTERNAL")); Assert.Equal("Unable to connect: Invalid authentication method EXTERNAL", ex.Message); }
public void ConnectUsingSha256PasswordPlugin() { string userName = "******"; string password = "******"; string pluginName = "sha256_password"; string connectionStringUri = ConnectionStringUri.Replace("test:test", string.Format("{0}:{1}", userName, password)); // User with password over TLS connection. using (var session = MySQLX.GetSession(connectionStringUri)) { Assert.Equal(SessionState.Open, session.InternalSession.SessionState); var result = session.SQL(string.Format("SELECT `User`, `plugin` FROM `mysql`.`user` WHERE `User` = '{0}';", userName)).Execute().FetchAll(); Assert.Equal(userName, session.Settings.UserID); Assert.Equal(session.Settings.UserID, result[0][0].ToString()); Assert.Equal(pluginName, result[0][1].ToString()); } // Connect over non-TLS connection. Should fail since sha256_password plugin isn't supported over non-TLS connections in X Plugin. Assert.Throws <MySqlException>(() => MySQLX.GetSession(connectionStringUri + "?sslmode=none")); // User without password over TLS connection. ExecuteSQL(String.Format("ALTER USER {0}@'localhost' IDENTIFIED BY ''", userName)); using (var session = MySQLX.GetSession(ConnectionStringUri.Replace("test:test", string.Format("{0}:{1}", userName, "")))) { Assert.Equal(SessionState.Open, session.InternalSession.SessionState); var result = session.SQL(string.Format("SELECT `User`, `plugin` FROM `mysql`.`user` WHERE `User` = '{0}';", userName)).Execute().FetchAll(); Assert.Equal(userName, session.Settings.UserID); Assert.Equal(session.Settings.UserID, result[0][0].ToString()); Assert.Equal(pluginName, result[0][1].ToString()); } }
public void SslCertificatePathKeepsCase() { var certificatePath = "../../../../MySql.Data.Tests/client.pfx"; // Connection string in basic format. string connString = ConnectionString + ";ssl-ca=" + certificatePath + ";ssl-ca-pwd=pass;"; var stringBuilder = new MySqlXConnectionStringBuilder(connString); Assert.Equal(certificatePath, stringBuilder.CertificateFile); Assert.Equal(certificatePath, stringBuilder.SslCa); Assert.True(stringBuilder.ConnectionString.Contains(certificatePath)); connString = stringBuilder.ToString(); Assert.True(connString.Contains(certificatePath)); // Connection string in uri format. string connStringUri = ConnectionStringUri + "/?ssl-ca=" + certificatePath + "& ssl-ca-pwd=pass;"; using (var session = MySQLX.GetSession(connStringUri)) { Assert.Equal(certificatePath, session.Settings.CertificateFile); Assert.Equal(certificatePath, session.Settings.SslCa); Assert.True(session.Settings.ConnectionString.Contains(certificatePath)); connString = session.Settings.ToString(); Assert.True(connString.Contains(certificatePath)); } }
public void ConnectionWithParenthesisEnclosedSockets() { if (Platform.IsWindows()) { return; } using (var session = MySQLX.GetSession("mysqlx://root:@(" + defaultUnixSocket + ")?protocol=unix&sslmode=none")) { Assert.Equal(SessionState.Open, session.InternalSession.SessionState); Assert.Equal(defaultUnixSocket, session.Settings.Server); } using (var session = MySQLX.GetSession("server=(" + defaultUnixSocket + ");uid=root;protocol=unix;sslmode=none")) { Assert.Equal(SessionState.Open, session.InternalSession.SessionState); Assert.Equal(defaultUnixSocket, session.Settings.Server); } using (var session = MySQLX.GetSession(new { server = "(" + defaultUnixSocket + ")", uid = "root", protocol = "unix", sslmode = MySqlSslMode.None })) { Assert.Equal(SessionState.Open, session.InternalSession.SessionState); Assert.Equal(defaultUnixSocket, session.Settings.Server); } }
public void SessionClose() { Session session = MySQLX.GetSession(ConnectionString); Assert.Equal(SessionState.Open, session.InternalSession.SessionState); session.Close(); Assert.Equal(SessionState.Closed, session.InternalSession.SessionState); }
public void DnsResolverNoHostsPooling() { using (var client = MySQLX.GetClient("mysqlx+srv://test:[email protected]?dns-srv=true;", new { pooling = new { enabled = true } })) { var ex = Assert.Throws <MySqlException>(() => client.GetSession()); Assert.AreEqual(string.Format(MySql.Data.Resources.DnsSrvNoHostsAvailable, "localhost"), ex.Message); } }
public void SessionCreateWithURI() { using (var internalSession = MySQLX.GetSession(_connectionURI)) { } _session = MySQLX.GetSession(_connectionURI); _session.Close(); }
public void CompressionAlgorithms_Bugs() { bool success = true; try { // Bug #31544072 #if NET452 // Different algorithms available in server hence default compression expected using (var session = MySQLX.GetSession(ConnectionString + ";compression=required;compression-algorithms=[];")) { var compressionAlgorithm = session.XSession.GetCompressionAlgorithm(true); Assert.IsNotNull(compressionAlgorithm); } // With only deflate available,Exeption expected ExecuteSqlAsRoot(@"SET GLOBAL mysqlx_compression_algorithms = ""DEFLATE_STREAM"" "); Exception ex_bug1 = Assert.Throws <System.NotSupportedException>(() => MySQLX.GetSession(ConnectionString + ";compression=required;compression-algorithms=[];")); StringAssert.Contains("Compression requested but the compression algorithm negotiation failed", ex_bug1.Message); #else using (var session = MySQLX.GetSession(ConnectionString + ";compression=required;compression-algorithms=[];")) { var compressionAlgorithm = session.XSession.GetCompressionAlgorithm(true); Assert.IsNotNull(compressionAlgorithm); } // With only deflate available,compression is expected ExecuteSqlAsRoot(@"SET GLOBAL mysqlx_compression_algorithms = ""DEFLATE_STREAM"" "); using (var session = MySQLX.GetSession(ConnectionString + ";compression=required;compression-algorithms=[];")) { var compressionAlgorithm = session.XSession.GetCompressionAlgorithm(true); Assert.AreEqual(CompressionAlgorithms.deflate_stream.ToString(), compressionAlgorithm); } #endif // Bug #31541819 ExecuteSqlAsRoot(@"SET GLOBAL mysqlx_compression_algorithms = ""DEFLATE_STREAM"" "); #if NET452 // Exeption expected due to compression=required Exception ex_bug2 = Assert.Throws <System.NotSupportedException>(() => MySQLX.GetSession(ConnectionString + ";compression=required;compression-algorithms=deflate_stream;")); StringAssert.Contains("is not supported in .NET Framework", ex_bug2.Message); #else using (var session = MySQLX.GetSession(ConnectionString + ";compression=required;compression-algorithms=deflate_stream;")) { var compressionAlgorithm = session.XSession.GetCompressionAlgorithm(true); Assert.AreEqual(CompressionAlgorithms.deflate_stream.ToString(), compressionAlgorithm); } #endif } catch (Exception ex) { success = false; } finally { // This line ensures that the list of supported compression algorithms is set to its default value. ExecuteSqlAsRoot(@"SET GLOBAL mysqlx_compression_algorithms = ""ZSTD_STREAM,LZ4_MESSAGE,DEFLATE_STREAM"" "); Assert.True(success); } }
public void SSlOptions() { string connectionString = ConnectionStringUri; // sslmode is valid. using (var connection = MySQLX.GetSession(connectionString + "?sslmode=none")) { Assert.Equal(SessionState.Open, connection.InternalSession.SessionState); } using (var connection = MySQLX.GetSession(connectionString + "?ssl-mode=none")) { Assert.Equal(SessionState.Open, connection.InternalSession.SessionState); } // sslenable is invalid. Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionString + "?sslenable")); Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionString + "?ssl-enable")); // sslmode=Required is default value. using (var connection = MySQLX.GetSession(connectionString)) { Assert.Equal(connection.Settings.SslMode, MySqlSslMode.Required); } // sslmode=Preferred is invalid. Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionString + "?ssl-mode=Preferred")); // sslmode=Required is default value. using (var connection = MySQLX.GetSession(connectionString)) { Assert.Equal(MySqlSslMode.Required, connection.Settings.SslMode); } // sslmode case insensitive. using (var connection = MySQLX.GetSession(connectionString + "?SsL-mOdE=none")) { Assert.Equal(SessionState.Open, connection.InternalSession.SessionState); } using (var connection = MySQLX.GetSession(connectionString + "?SsL-mOdE=VeRiFyca&ssl-ca=../../../../MySql.Data.Tests/client.pfx&ssl-ca-pwd=pass")) { Assert.Equal(SessionState.Open, connection.InternalSession.SessionState); } // Duplicate SSL connection options send error message. ArgumentException ex = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionString + "?sslmode=Required&ssl mode=None")); Assert.EndsWith("is duplicated.", ex.Message); ex = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionString + "?ssl-ca-pwd=pass&ssl-ca-pwd=pass")); Assert.EndsWith("is duplicated.", ex.Message); ex = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionString + "?certificatepassword=pass&certificatepassword=pass")); Assert.EndsWith("is duplicated.", ex.Message); ex = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionString + "?certificatepassword=pass&ssl-ca-pwd=pass")); Assert.EndsWith("is duplicated.", ex.Message); // send error if sslmode=None and another ssl parameter exists. Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connectionString + "?sslmode=None&ssl-ca=../../../../MySql.Data.Tests/certificates/client.pfx").InternalSession.SessionState); }
public void SslSession() { using (var s3 = MySQLX.GetSession(ConnectionStringUri)) { Assert.Equal(SessionState.Open, s3.InternalSession.SessionState); var result = ExecuteSQLStatement(s3.SQL("SHOW SESSION STATUS LIKE 'Mysqlx_ssl_version';")).FetchAll(); Assert.StartsWith("TLSv1", result[0][1].ToString()); } }
public void DnsSrvConnectionStringUriInvalidConfiguration(string connStringUri, string exceptionMessage) { var exception = Assert.Throws <ArgumentException>(() => MySQLX.GetSession(connStringUri)); Assert.AreEqual(exceptionMessage, exception.Message); exception = Assert.Throws <ArgumentException>(() => MySQLX.GetClient(connStringUri, new { pooling = new { enabled = true } })); Assert.AreEqual(exceptionMessage, exception.Message); }
public void IPv6AsAnonymous() { MySqlConnectionStringBuilder csBuilder = new MySqlConnectionStringBuilder(ConnectionString); using (Session session = MySQLX.GetSession(new { server = "::1", user = csBuilder.UserID, password = csBuilder.Password, port = XPort })) { Assert.Equal(SessionState.Open, session.InternalSession.SessionState); } }
public void SslCertificatePathVariations(string certificatePath) { string connStringUri = ConnectionStringUri + "/?ssl-ca=" + certificatePath + "& ssl-ca-pwd=pass;"; using (var session = MySQLX.GetSession(connStringUri)) { Assert.Equal(SessionState.Open, session.InternalSession.SessionState); } }