public void MaxPreparedStmtCount() { InitCollection(); Collection coll = GetCollection(); try { ((Session)coll.Session).SQL("SET GLOBAL max_prepared_stmt_count=0").Execute(); var findStmt = coll.Find("_id = :id and pages = :pages").Bind("id", 1).Bind("pages", 20); DocResult doc = ExecuteFindStatement(findStmt); Assert.AreEqual("Book 1", doc.FetchAll()[0]["title"].ToString()); Assert.False(findStmt._isPrepared); Assert.True(findStmt.Session.SupportsPreparedStatements); ValidatePreparedStatements(0, 0, null); doc = ExecuteFindStatement(findStmt.Bind("id", 2).Bind("pages", 30).Limit(1)); Assert.AreEqual($"Book 2", doc.FetchAll()[0]["title"].ToString()); Assert.False(findStmt._isPrepared); Assert.False(findStmt.Session.SupportsPreparedStatements); doc = ExecuteFindStatement(findStmt.Bind("id", 3).Bind("pages", 40).Limit(1)); Assert.AreEqual($"Book 3", doc.FetchAll()[0]["title"].ToString()); Assert.False(findStmt._isPrepared); Assert.False(findStmt.Session.SupportsPreparedStatements); } finally { ((Session)coll.Session).SQL("SET GLOBAL max_prepared_stmt_count=16382").Execute(); } }
/// <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 Rollback() { Collection coll = CreateCollection("test"); var docs = new[] { new { _id = 1, title = "Book 1", pages = 20 }, new { _id = 2, title = "Book 2", pages = 30 }, new { _id = 3, title = "Book 3", pages = 40 }, new { _id = 4, title = "Book 4", pages = 50 }, }; // start the transaction coll.Session.StartTransaction(); Result r = coll.Add(docs).Execute(); Assert.Equal <ulong>(4, r.RecordsAffected); // now roll it back coll.Session.Rollback(); DocResult foundDocs = coll.Find().Execute(); Assert.False(foundDocs.Next()); }
public void FindWithChanges() { InitCollection(); Collection coll = GetCollection(); 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); foundDoc = ExecuteFindStatement(findStmt.Limit(1)); Assert.AreEqual("Book 1", foundDoc.FetchAll()[0]["title"].ToString()); Assert.True(findStmt._isPrepared || !findStmt.Session.SupportsPreparedStatements); ValidatePreparedStatements(1, 1, $"SELECT doc FROM `{schemaName}`.`{_collectionName}` WHERE (JSON_EXTRACT(doc,'$._id') = 1) LIMIT ?, ?"); for (int i = 1; i <= _docs.Length; i++) { DocResult foundDoc2 = ExecuteFindStatement(findStmt.Where($"_id = {i}")); Assert.AreEqual($"Book {i}", foundDoc2.FetchAll()[0]["title"].ToString()); Assert.False(findStmt._isPrepared); } ValidatePreparedStatements(0, 0, null); }
public void Rollback() { Collection coll = CreateCollection("test"); var docs = new[] { new { _id = 1, title = "Book 1", pages = 20 }, new { _id = 2, title = "Book 2", pages = 30 }, new { _id = 3, title = "Book 3", pages = 40 }, new { _id = 4, title = "Book 4", pages = 50 }, }; // start the transaction coll.Session.StartTransaction(); Result r = ExecuteAddStatement(coll.Add(docs)); Assert.AreEqual(4, r.AffectedItemsCount); // now roll it back coll.Session.Rollback(); DocResult foundDocs = ExecuteFindStatement(coll.Find()); Assert.False(foundDocs.Next()); }
public DocResult FindDocs(FindStatement fs) { protocol.SendFind(fs.Target.Schema.Name, fs.Target.Name, false, fs.FilterData, fs.findParams); DocResult result = new DocResult(this); return(result); }
public TResult ExecutePreparedStatement <TResult>(int stmtId, IEnumerable args) where TResult : BaseResult { protocol.SendExecutePreparedStatement((uint)stmtId, args); BaseResult result = null; if (typeof(TResult) == typeof(DocResult)) { result = new DocResult(this); } else if (typeof(TResult) == typeof(RowResult)) { result = new RowResult(this); } else if (typeof(TResult) == typeof(SqlResult)) { result = new SqlResult(this); } else if (typeof(TResult) == typeof(Result)) { result = new Result(this); } else { throw new ArgumentNullException(typeof(TResult).Name); } return((TResult)result); }
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); } }
static public void printResult(Object result) { Result res = result as Result; DocResult doc = result as DocResult; RowResult row = result as RowResult; SqlResult sql = result as SqlResult; if (res != null) { PrintResult(res); } else if (doc != null) { PrintDocResult(doc); } else if (row != null) { PrintRowResult(row); } else if (sql != null) { PrintSqlResult(sql); } else if (result == null) { Console.Write("null"); } else { Console.Write(result.ToString()); } }
/// <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 BindDbDoc() { Collection coll = CreateCollection("test"); var docs = new[] { new { _id = 1, title = "Book 1", pages = 20 }, new { _id = 2, title = "Book 2", pages = 30 }, new { _id = 3, title = "Book 3", pages = 40 }, new { _id = 4, title = "Book 4", pages = 50 }, }; Result r = coll.Add(docs).Execute(); Assert.Equal <ulong>(4, r.RecordsAffected); //var s = MySql.Data.ResourcesX.TestingResources; DbDoc docParams = new DbDoc(new { pages1 = 30, pages2 = 40 }); DocResult foundDocs = coll.Find("pages = :Pages1 || pages = :Pages2").Bind(docParams).Execute(); Assert.True(foundDocs.Next()); Assert.Equal("Book 2", foundDocs.Current["title"]); Assert.True(foundDocs.Next()); Assert.Equal("Book 3", foundDocs.Current["title"]); Assert.False(foundDocs.Next()); }
/// <summary> /// Prints a <see cref="DocResult"/> in the output window showing extended information about the execution result (documents returned, execution time, etc.). /// </summary> /// <param name="statement">The executed statement.</param> /// <param name="docResult">A <see cref="DocResult"/> instance.</param> private void PrintDocResult(string statement, DocResult docResult) { string executionTime = docResult.ExecutionTime; var dictionariesList = docResult.Documents; PrintGenericResult(statement, dictionariesList, executionTime); PrintWarnings(statement, docResult, executionTime); }
/// <summary> /// An async method to read all the logs in a specified month. /// </summary> /// <param name="year">Year needed to get specific month.</param> /// <param name="month">Month needed to get specific logs.</param> /// <param name="amountOfDays">Amount of days needed for organization.</param> /// <returns>A list of list of the LogResult ofbject.</returns> public async Task <List <List <LogResult> > > ReadSpecificMonthAsync(string year, string month, int amountOfDays) { List <List <LogResult> > logsForMonth = new List <List <LogResult> >(); // Get the session inside a using statement to properly dispose/close. using (Session session = MySQLX.GetSession(NOSQLConnection)) { // Get log schema. Schema schema = session.GetSchema(Constants.LogsSchemaName); // Use the amountOfDays variable to loop to get dates. for (int date = 1; date < amountOfDays + 1; date++) { // Make group name based on year and month. string groupName = year + month; string day = ""; if (date < 10) { // If the date is less than 10, a "0" has to be added for formatting purposes. day += "0"; } // Convert date into a string for use. day += Convert.ToString(date); groupName += day; // Get logs for a specific day. var collection = schema.GetCollection(Constants.LogsCollectionPrefix + groupName); // Need to check if collection exists beforehand. List <LogResult> logsForDay = new List <LogResult>(); if (collection.ExistsInDatabase()) { DocResult result = await collection.Find().ExecuteAsync().ConfigureAwait(false); while (result.Next()) { LogResult logObject = new LogResult((string)result.Current[Constants.LogsTimestampField], (string)result.Current[Constants.LogsOperationField], (string)result.Current[Constants.LogsIdentifierField], (string)result.Current[Constants.LogsIPAddressField], (string)result.Current[Constants.LogsErrorTypeField]); logsForDay.Add(logObject); } } logsForMonth.Add(logsForDay); } } return(logsForMonth); }
private static void PrintDocResult(DocResult doc) { List <Dictionary <string, object> > data = doc.FetchAll(); foreach (Dictionary <string, object> row in data) { StringBuilder sb = new StringBuilder(); sb.AppendLine("{"); int i = 0; foreach (KeyValuePair <string, object> kvp in row) { sb.AppendFormat("\t\"{0}\" : \"{1}\"{2}\n", kvp.Key, kvp.Value, (i == row.Count - 1) ? "" : ","); i++; } sb.AppendLine("},"); Console.Write(sb); } }
public void ExclusiveLockAfterSharedLock() { 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(); Collection coll = CreateCollection("test"); coll.CreateIndex("myIndex", true).Field("$._id", "INT", true).Execute(); var docs = new[] { new { _id = 1, a = 1 }, new { _id = 2, a = 1 }, new { _id = 3, a = 1 }, }; coll.Add(docs).Execute(); Collection coll2 = session2.GetSchema("test").GetCollection("test"); session.SQL("START TRANSACTION").Execute(); DocResult docResult = coll.Find("_id in (1, 3)").LockShared().Execute(); Assert.Equal(2, docResult.FetchAll().Count); session2.SQL("START TRANSACTION").Execute(); // Should return immediately since document isn't locked. docResult = coll2.Find("_id = 2").LockExclusive().Execute(); // Should return immediately due to LockShared() allows reading by other sessions. docResult = coll2.Find("_id = 2").LockShared().Execute(); Assert.Equal(1, docResult.FetchAll().Count); // Session2 blocks due to to LockExclusive() not allowing to read locked documents. session2.SQL("SET SESSION innodb_lock_wait_timeout=1").Execute(); Exception ex = Assert.Throws <MySqlException>(() => coll2.Find("_id = 1").LockExclusive().Execute()); Assert.Equal("Lock wait timeout exceeded; try restarting transaction", ex.Message); // Session unlocks documents. session.SQL("ROLLBACK").Execute(); docResult = coll2.Find("_id = 1").LockExclusive().Execute(); Assert.Equal(1, docResult.FetchAll().Count); session2.SQL("ROLLBACK").Execute(); } }
public void SharedLockForbidsToModifyDocuments() { 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(); Collection coll = CreateCollection("test"); var docs = new[] { new { _id = 1, a = 1 }, new { _id = 2, a = 1 }, new { _id = 3, a = 1 }, }; coll.Add(docs).Execute(); Collection coll2 = session2.GetSchema("test").GetCollection("test"); session.SQL("START TRANSACTION").Execute(); DocResult docResult = coll.Find("_id = 1").LockShared().Execute(); Assert.Equal(1, docResult.FetchAll().Count); session2.SQL("START TRANSACTION").Execute(); // Reading the same document is allowed with LockShared(). docResult = coll2.Find("_id = 1").Execute(); Assert.Equal(1, docResult.FetchAll().Count); // Modify() is allowed for non-locked documents. Result result = coll2.Modify("_id = 2").Set("a", 2).Execute(); Assert.Equal <ulong>(1, result.RecordsAffected); // Session1 blocks, Modify() is not allowed for locked documents. session2.SQL("SET SESSION innodb_lock_wait_timeout=1").Execute(); Exception ex = Assert.Throws <MySqlException>(() => coll2.Modify("_id = 1").Set("a", 2).Execute()); Assert.Equal("Lock wait timeout exceeded; try restarting transaction", ex.Message); session.SQL("ROLLBACK").Execute(); // Modify() is allowed since document isn't locked anymore. coll2.Modify("_id = 1").Set("a", 2).Execute(); session2.SQL("COMMIT").Execute(); } }
/// <summary> /// Find the id of the record that was inserted into the data store. /// </summary> /// <param name="record">The record to find (INOSQLRecord)</param> /// <param name="groupName">The name of the group where the record is located (string)</param> /// <returns>Task (string), the id of the record</returns> public async Task <string> FindIdFieldAsync(INOSQLRecord record, string groupName) { // Try converting the INOSQLRecord to a LogRecord, if it failed throw an argument exception. try { LogRecord temp = (LogRecord)record; } catch { throw new ArgumentException(Constants.LogFindInvalidArgument); } LogRecord logRecord = (LogRecord)record; // 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); // The items of the log record which all need to be found. var documentParams = new DbDoc(new { timestamp = logRecord.Timestamp, operation = logRecord.Operation, identifier = logRecord.Identifier, ip = logRecord.IPAddress }); // Asynchronously execute a find on the fields that correspond to the parameter values above. DocResult result = await collection.Find($"{Constants.LogsTimestampField} = :timestamp && {Constants.LogsOperationField} = :operation && {Constants.LogsIdentifierField} = :identifier && {Constants.LogsIPAddressField} = :ip").Bind(documentParams).ExecuteAsync().ConfigureAwait(false); // Prepare string to be returned string resultstring = ""; while (result.Next()) { resultstring = (string)result.Current[Constants.LogsIdField]; } if (resultstring.Equals("")) { throw new ArgumentException(Constants.LogFindDNE); } return(resultstring); } }
public void FindConditional() { Collection coll = CreateCollection("test"); var docs = new[] { new { _id = 1, title = "Book 1", pages = 20 }, new { _id = 2, title = "Book 2", pages = 30 }, new { _id = 3, title = "Book 3", pages = 40 }, new { _id = 4, title = "Book 4", pages = 50 }, }; Result r = coll.Add(docs).Execute(); Assert.Equal <ulong>(4, r.RecordsAffected); DocResult foundDocs = coll.Find("pages = :Pages").Bind("pAges", 40).Execute(); Assert.True(foundDocs.Next()); Assert.True(foundDocs.Current["title"] == "Book 3"); Assert.False(foundDocs.Next()); }
/// <summary> /// Method to get all the specific months of existing snapshots. /// </summary> /// <returns></returns> public async Task <List <string> > GetYearAndMonthAsync() { var yearMonthList = new List <string>(); using (Session session = MySQLX.GetSession(NOSQLConnection)) { Schema schema = session.GetSchema(Constants.SnapshotSchemaName); var collection = schema.GetCollection(Constants.SnapshotCollectionPrefix); // Get all the snapshots in the collection. DocResult result = await collection.Find().ExecuteAsync().ConfigureAwait(false); while (result.Next()) { var stringYearMonth = (string)result.Current[Constants.SnapshotMonth]; yearMonthList.Add(stringYearMonth); } } return(yearMonthList); }
public void Find() { InitCollection(); Collection coll = GetCollection(); var findStmt = coll.Find("_id = :id and pages = :pages").Bind("id", 1).Bind("pages", 20); DocResult doc = ExecuteFindStatement(findStmt); Assert.AreEqual("Book 1", doc.FetchAll()[0]["title"].ToString()); Assert.False(findStmt._isPrepared); ValidatePreparedStatements(0, 0, null); for (int i = 1; i <= _docs.Length; i++) { doc = ExecuteFindStatement(findStmt.Bind("id", i).Bind("pages", i * 10 + 10).Limit(1)); Assert.AreEqual($"Book {i}", doc.FetchAll()[0]["title"].ToString()); Assert.True(findStmt._isPrepared || !findStmt.Session.SupportsPreparedStatements); } ValidatePreparedStatements(1, 4, $"SELECT doc FROM `{schemaName}`.`{_collectionName}` WHERE ((JSON_EXTRACT(doc,'$._id') = ?) AND (JSON_EXTRACT(doc,'$.pages') = ?)) LIMIT ?, ?"); }
/// <summary> /// Method to read a snapshot pertaining to a specific month. /// </summary> /// <param name="year">Year needed to get specific snapshot.</param> /// <param name="month">Month needed to get specific snapshot.</param> /// <returns>A SnapShotResult object that has all the information.</returns> public async Task <SnapShotResult> ReadMonthlySnapshotAsync(string year, string month) { using (Session session = MySQLX.GetSession(NOSQLConnection)) { Schema schema = session.GetSchema(Constants.SnapshotSchemaName); string specificMonth = year + month; var collection = schema.GetCollection(Constants.SnapshotCollectionPrefix); // Snapshot for specific month. DocResult result = await collection.Find($"{Constants.SnapshotMonth} = :_month").Bind("_month", specificMonth).ExecuteAsync().ConfigureAwait(false); // Making a snapshot object with the result. 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]); return(snapshot); } }
public void ArrayAppend() { Collection collection = CreateCollection("test"); ExecuteAddStatement(collection.Add("{ \"x\":[1,2] }")); // Append values of different types, null and spaces. ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", 43)); ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", "string")); ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", true)); ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", null)); ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", " ")); DocResult result = ExecuteFindStatement(collection.Find()); DbDoc document = result.FetchOne(); var x = (object[])document.values["x"]; Assert.AreEqual(7, x.Length); Assert.AreEqual(1, (int)x[0]); Assert.AreEqual(2, (int)x[1]); Assert.AreEqual(43, (int)x[2]); Assert.AreEqual("string", x[3]); Assert.AreEqual(true, x[4]); Assert.Null(x[5]); Assert.AreEqual(" ", x[6]); // No value is appended if the array doesn't exist. ExecuteModifyStatement(collection.Modify("true").ArrayAppend("y", 45)); result = ExecuteFindStatement(collection.Find()); document = result.FetchOne(); Assert.False(document.values.ContainsKey("y")); var ex = Assert.Throws <ArgumentException>(() => ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", ""))); StringAssert.Contains("String can't be empty.", ex.Message); ex = Assert.Throws <ArgumentException>(() => ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", string.Empty))); StringAssert.Contains("String can't be empty.", ex.Message); }
public void BindJsonAsString() { Collection coll = CreateCollection("test"); var docs = new[] { new { _id = 1, title = "Book 1", pages = 20 }, new { _id = 2, title = "Book 2", pages = 30 }, new { _id = 3, title = "Book 3", pages = 40 }, new { _id = 4, title = "Book 4", pages = 50 }, }; Result r = coll.Add(docs).Execute(); Assert.Equal <ulong>(4, r.RecordsAffected); var jsonParams = "{ \"pages1\" : 30, \"pages2\" : 40 }"; DocResult foundDocs = coll.Find("pages = :Pages1 || pages = :Pages2").Bind(jsonParams).Execute(); Assert.True(foundDocs.Next()); Assert.Equal("Book 2", foundDocs.Current["title"]); Assert.True(foundDocs.Next()); Assert.Equal("Book 3", foundDocs.Current["title"]); Assert.False(foundDocs.Next()); }
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(); Collection coll = CreateCollection("test"); var docs = new[] { new { _id = 1, a = 1 }, new { _id = 2, a = 1 }, new { _id = 3, a = 1 }, }; coll.Add(docs).Execute(); Collection coll2 = session2.GetSchema("test").GetCollection("test"); session.SQL("START TRANSACTION").Execute(); DocResult docResult = coll.Find("_id = 1").LockShared().Execute(); Assert.Equal(1, docResult.FetchAll().Count); session2.SQL("START TRANSACTION").Execute(); // Should return immediately since document isn't locked. docResult = coll2.Find("_id = 2").LockShared().Execute(); Assert.Equal(1, docResult.FetchAll().Count); // Should return immediately due to LockShared() allows reading by other sessions. docResult = coll2.Find("_id = 1").LockShared().Execute(); Assert.Equal(1, docResult.FetchAll().Count); session.SQL("ROLLBACK").Execute(); session2.SQL("ROLLBACK").Execute(); } }
public void SimpleFindWithLimit() { Collection coll = CreateCollection("test"); var docs = new[] { new { _id = 1, title = "Book 1", pages = 20 }, new { _id = 2, title = "Book 2", pages = 30 }, new { _id = 3, title = "Book 3", pages = 40 }, new { _id = 4, title = "Book 4", pages = 50 }, }; Result r = coll.Add(docs).Execute(); Assert.Equal <ulong>(4, r.RecordsAffected); DocResult foundDocs = coll.Find("pages > 20").Limit(1).Execute(); Assert.True(foundDocs.Next()); Assert.True(foundDocs.Current["title"] == "Book 2"); Assert.False(foundDocs.Next()); // Limit out of range. Assert.Throws <ArgumentOutOfRangeException>(() => coll.Find().Limit(0).Execute()); Assert.Throws <ArgumentOutOfRangeException>(() => coll.Find().Limit(-1).Execute()); }
public void SimpleFindWithSort() { Collection coll = CreateCollection("test"); var docs = new[] { new { _id = 1, title = "Book 1", pages = 20 }, new { _id = 2, title = "Book 2", pages = 30 }, new { _id = 3, title = "Book 3", pages = 40 }, new { _id = 4, title = "Book 4", pages = 50 }, }; Result r = coll.Add(docs).Execute(); Assert.Equal <ulong>(4, r.RecordsAffected); DocResult foundDocs = coll.Find("pages > 20").OrderBy("pages DESC").Execute(); Assert.True(foundDocs.Next()); Assert.True(foundDocs.Current["title"] == "Book 4"); Assert.True(foundDocs.Next()); Assert.True(foundDocs.Current["title"] == "Book 3"); Assert.True(foundDocs.Next()); Assert.True(foundDocs.Current["title"] == "Book 2"); Assert.False(foundDocs.Next()); }