diff --git a/samples/YesSql.Bench/Program.cs b/samples/YesSql.Bench/Program.cs index 7f79aeb6..cc4bea40 100644 --- a/samples/YesSql.Bench/Program.cs +++ b/samples/YesSql.Bench/Program.cs @@ -19,28 +19,26 @@ static async Task MainAsync(string[] args) .UseSqlServer(@"Data Source =.; Initial Catalog = yessql; Integrated Security = True") .SetTablePrefix("Bench"); - using (var connection = configuration.ConnectionFactory.CreateConnection()) + await using (var connection = configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(configuration.IsolationLevel); + var builder = new SchemaBuilder(configuration, transaction); - builder.CreateMapIndexTable(c => c - .Column("Name") - .Column("Adult") - .Column("Age") - ); + await builder.CreateMapIndexTableAsync(c => c + .Column("Name") + .Column("Adult") + .Column("Age") + ); - transaction.Commit(); - } + await transaction.CommitAsync(); } var store = await StoreFactory.CreateAndInitializeAsync(configuration); store.RegisterIndexes(); - using (var session = store.CreateSession()) + await using (var session = store.CreateSession()) { var user = await session.Query().FirstOrDefaultAsync(); @@ -51,13 +49,11 @@ static async Task MainAsync(string[] args) Age = 1 }; - - session.Save(bill); - + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = store.CreateSession()) + await using (var session = store.CreateSession()) { var user = await session.Query().Where(x => x.Adult == true).FirstOrDefaultAsync(); diff --git a/samples/YesSql.Samples.FullText/Program.cs b/samples/YesSql.Samples.FullText/Program.cs index fc18ef0f..71a78d69 100644 --- a/samples/YesSql.Samples.FullText/Program.cs +++ b/samples/YesSql.Samples.FullText/Program.cs @@ -25,37 +25,36 @@ public static async Task Main(string[] args) var store = await StoreFactory.CreateAndInitializeAsync(configuration); - using (var connection = store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = store.Configuration.ConnectionFactory.CreateConnection()) { - connection.Open(); + await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(store.Configuration.IsolationLevel)) - { - new SchemaBuilder(store.Configuration, transaction) - .CreateReduceIndexTable(table => table - .Column("Count") - .Column("Word") - ); + await using var transaction = await connection.BeginTransactionAsync(store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(store.Configuration, transaction); - transaction.Commit(); - } + await builder.CreateReduceIndexTableAsync(table => table + .Column("Count") + .Column("Word") + ); + + await transaction.CommitAsync(); } // register available indexes store.RegisterIndexes(); // creating articles - using (var session = store.CreateSession()) + await using (var session = store.CreateSession()) { - session.Save(new Article { Content = "This is a green fox" }); - session.Save(new Article { Content = "This is a yellow cat" }); - session.Save(new Article { Content = "This is a pink elephant" }); - session.Save(new Article { Content = "This is a green tiger" }); + await session.SaveAsync(new Article { Content = "This is a green fox" }); + await session.SaveAsync(new Article { Content = "This is a yellow cat" }); + await session.SaveAsync(new Article { Content = "This is a pink elephant" }); + await session.SaveAsync(new Article { Content = "This is a green tiger" }); await session.SaveChangesAsync(); } - using (var session = store.CreateSession()) + await using (var session = store.CreateSession()) { Console.WriteLine("Simple term: 'green'"); var simple = await session diff --git a/samples/YesSql.Samples.Hi/Program.cs b/samples/YesSql.Samples.Hi/Program.cs index b290f5e1..2925eeda 100644 --- a/samples/YesSql.Samples.Hi/Program.cs +++ b/samples/YesSql.Samples.Hi/Program.cs @@ -22,23 +22,23 @@ static async Task MainAsync(string[] args) .SetTablePrefix("Hi") ); - using (var connection = store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = store.Configuration.ConnectionFactory.CreateConnection()) { - connection.Open(); + await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(store.Configuration.IsolationLevel)) - { - new SchemaBuilder(store.Configuration, transaction) - .CreateMapIndexTable(table => table - .Column("Author") - ) - .CreateReduceIndexTable(table => table - .Column("Count") - .Column("Day") + await using var transaction = await connection.BeginTransactionAsync(store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(store.Configuration, transaction); + + await builder.CreateMapIndexTableAsync(table => table + .Column("Author") ); - transaction.Commit(); - } + await builder.CreateReduceIndexTableAsync(table => table + .Column("Count") + .Column("Day") + ); + + await transaction.CommitAsync(); }; // register available indexes @@ -55,22 +55,21 @@ static async Task MainAsync(string[] args) }; // saving the post to the database - using (var session = store.CreateSession()) + await using (var session = store.CreateSession()) { - session.Save(post); - + await session.SaveAsync(post); await session.SaveChangesAsync(); } // loading a single blog post - using (var session = store.CreateSession()) + await using (var session = store.CreateSession()) { var p = await session.Query().For().FirstOrDefaultAsync(); Console.WriteLine(p.Title); // > Hello YesSql } // loading blog posts by author - using (var session = store.CreateSession()) + await using (var session = store.CreateSession()) { var ps = await session.Query().Where(x => x.Author.StartsWith("B")).ListAsync(); @@ -81,7 +80,7 @@ static async Task MainAsync(string[] args) } // loading blog posts by day of publication - using (var session = store.CreateSession()) + await using (var session = store.CreateSession()) { var ps = await session.Query(x => x.Day == DateTime.UtcNow.ToString("yyyyMMdd")).ListAsync(); @@ -92,7 +91,7 @@ static async Task MainAsync(string[] args) } // counting blog posts by day - using (var session = store.CreateSession()) + await using (var session = store.CreateSession()) { var days = await session.QueryIndex().ListAsync(); diff --git a/samples/YesSql.Samples.Performance/Benchmarks.cs b/samples/YesSql.Samples.Performance/Benchmarks.cs index cb21243f..700ed68a 100644 --- a/samples/YesSql.Samples.Performance/Benchmarks.cs +++ b/samples/YesSql.Samples.Performance/Benchmarks.cs @@ -1,4 +1,5 @@ using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Engines; using System; using System.Collections.Generic; using System.Diagnostics; @@ -7,14 +8,13 @@ using YesSql.Provider.PostgreSql; using YesSql.Services; using YesSql.Sql; -using BenchmarkDotNet.Engines; namespace YesSql.Samples.Performance { [MemoryDiagnoser, ShortRunJob] public class Benchmarks { - private Consumer _consumer = new Consumer(); + private readonly Consumer _consumer = new Consumer(); IStore _store; @@ -29,43 +29,41 @@ private async Task InitializeAsync() .UsePostgreSql(@"Server=localhost;Port=5432;Database=yessql;User Id=root;Password=Password12!;") .SetTablePrefix("Performance") ; - + try { - using (var connection = configuration.ConnectionFactory.CreateConnection()) - { - connection.Open(); + await using var connection = configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction()) - { - new SchemaBuilder(configuration, transaction) - .DropTable("UserByName") - .DropTable("Identifiers") - .DropTable(configuration.TableNameConvention.GetDocumentTable("")); + await using var transaction = await connection.BeginTransactionAsync(); + var builder = new SchemaBuilder(configuration, transaction); - transaction.Commit(); - } - } + await builder.DropTableAsync("UserByName"); + await builder.DropTableAsync("Identifiers"); + await builder.DropTableAsync(configuration.TableNameConvention.GetDocumentTable("")); + + await transaction.CommitAsync(); } catch { } _store = await StoreFactory.CreateAndInitializeAsync(configuration); - using (var connection = configuration.ConnectionFactory.CreateConnection()) + await using (var connection = configuration.ConnectionFactory.CreateConnection()) { - connection.Open(); + await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction()) - { - new SchemaBuilder(configuration, transaction).CreateMapIndexTable(table => table - .Column("Name") - ) - .AlterTable("UserByName", table => table - .CreateIndex("IX_Name", "Name") - ); - - transaction.Commit(); - } + await using var transaction = await connection.BeginTransactionAsync(); + var builder = new SchemaBuilder(configuration, transaction); + + await builder.CreateMapIndexTableAsync(table => table + .Column("Name") + ); + + await builder.AlterTableAsync("UserByName", table => table + .CreateIndex("IX_Name", "Name") + ); + + await transaction.CommitAsync(); } _store.RegisterIndexes(); @@ -74,7 +72,7 @@ private async Task InitializeAsync() await CreateUsersAsync(); // pre initialize configuration - _store.CreateSession().Dispose(); + await _store.CreateSession().DisposeAsync(); await WriteAllWithYesSql(); } @@ -85,12 +83,10 @@ public async Task QueryIndexByFullName1() var rnd = new Random(); var names = Enumerable.Range(1, 1).Select(x => Names[rnd.Next(Names.Length - 1)]).ToArray(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + foreach (var user in await session.QueryIndex(x => x.Name.IsIn(names)).ListAsync()) { - foreach (var user in await session.QueryIndex(x => x.Name.IsIn(names)).ListAsync()) - { - _consumer.Consume(user); - } + _consumer.Consume(user); } } @@ -100,12 +96,10 @@ public async Task QueryIndexByFullName10() var rnd = new Random(); var names = Enumerable.Range(1, 10).Select(x => Names[rnd.Next(Names.Length - 1)]).ToArray(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + foreach (var user in await session.QueryIndex(x => x.Name.IsIn(names)).ListAsync()) { - foreach(var user in await session.QueryIndex(x => x.Name.IsIn(names)).ListAsync()) - { - _consumer.Consume(user); - } + _consumer.Consume(user); } } @@ -115,12 +109,10 @@ public async Task QueryIndexByFullName100() var rnd = new Random(); var names = Enumerable.Range(1, 100).Select(x => Names[rnd.Next(Names.Length - 1)]).ToArray(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + foreach (var user in await session.QueryIndex(x => x.Name.IsIn(names)).ListAsync()) { - foreach(var user in await session.QueryIndex(x => x.Name.IsIn(names)).ListAsync()) - { - _consumer.Consume(user); - } + _consumer.Consume(user); } } @@ -130,12 +122,10 @@ public async Task QueryByFullName1() var rnd = new Random(); var names = Enumerable.Range(1, 1).Select(x => Names[rnd.Next(Names.Length - 1)]).ToArray(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + foreach (var user in await session.Query(x => x.Name.IsIn(names)).ListAsync()) { - foreach (var user in await session.Query(x => x.Name.IsIn(names)).ListAsync()) - { - _consumer.Consume(user); - } + _consumer.Consume(user); } } @@ -145,12 +135,10 @@ public async Task QueryByFullName10() var rnd = new Random(); var names = Enumerable.Range(1, 10).Select(x => Names[rnd.Next(Names.Length - 1)]).ToArray(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + foreach (var user in await session.Query(x => x.Name.IsIn(names)).ListAsync()) { - foreach (var user in await session.Query(x => x.Name.IsIn(names)).ListAsync()) - { - _consumer.Consume(user); - } + _consumer.Consume(user); } } @@ -160,22 +148,18 @@ public async Task QueryByFullName100() var rnd = new Random(); var names = Enumerable.Range(1, 100).Select(x => Names[rnd.Next(Names.Length - 1)]).ToArray(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + foreach (var user in await session.Query(x => x.Name.IsIn(names)).ListAsync()) { - foreach (var user in await session.Query(x => x.Name.IsIn(names)).ListAsync()) - { - _consumer.Consume(user); - } + _consumer.Consume(user); } } [Benchmark] public ISession CreateSession() { - using (var session = _store.CreateSession()) - { - return session; - } + using var session = _store.CreateSession(); + return session; } [Benchmark] @@ -184,12 +168,10 @@ public async Task QuerySql() var rnd = new Random(); var names = Enumerable.Range(1, 1).Select(x => Names[rnd.Next(Names.Length - 1)]).ToArray(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + foreach (var user in await session.QueryIndex().Where("Name = '" + names[0] + "'").ListAsync()) { - foreach (var user in await session.QueryIndex().Where("Name = '" + names[0] + "'").ListAsync()) - { - _consumer.Consume(user); - } + _consumer.Consume(user); } } @@ -199,12 +181,10 @@ public async Task QueryParameterizedSql() var rnd = new Random(); var names = Enumerable.Range(1, 1).Select(x => Names[rnd.Next(Names.Length - 1)]).ToArray(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + foreach (var user in await session.QueryIndex().Where("Name = @Name").WithParameter("Name", names[0]).ListAsync()) { - foreach (var user in await session.QueryIndex().Where("Name = @Name").WithParameter("Name", names[0]).ListAsync()) - { - _consumer.Consume(user); - } + _consumer.Consume(user); } } @@ -214,24 +194,20 @@ public async Task QueryLinq() var rnd = new Random(); var names = Enumerable.Range(1, 1).Select(x => Names[rnd.Next(Names.Length - 1)]).ToArray(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + foreach (var user in await session.QueryIndex(x => x.Name == names[0]).ListAsync()) { - foreach (var user in await session.QueryIndex(x => x.Name == names[0]).ListAsync()) - { - _consumer.Consume(user); - } + _consumer.Consume(user); } } - + private async Task CleanAsync() { - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var documents = await session.Query().For().ListAsync(); + foreach (var document in documents) { - var documents = await session.Query().For().ListAsync(); - foreach (var document in documents) - { - session.Delete(document); - } + session.Delete(document); } } @@ -242,7 +218,7 @@ public async Task WriteAllWithYesSql() foreach (var name in Names) { batch++; - session.Save(new User + await session.SaveAsync(new User { Email = name + "@" + name + ".name", Name = name @@ -250,14 +226,13 @@ public async Task WriteAllWithYesSql() if (batch % batchSize == 0) { - session.Dispose(); + await session.DisposeAsync(); session = _store.CreateSession(); } } await session.SaveChangesAsync(); - - session.Dispose(); + await session.DisposeAsync(); } public async Task CreateUsersAsync() @@ -279,17 +254,17 @@ public async Task CreateUsersAsync() if (batch % batchSize == 0) { - users.ForEach(u => session.Save(u)); + users.ForEach(async u => await session.SaveAsync(u)); await session.SaveChangesAsync(); - session.Dispose(); + await session.DisposeAsync(); session = _store.CreateSession(); users = new List(); } } - users.ForEach(u => session.Save(u)); + users.ForEach(async u => await session.SaveAsync(u)); await session.SaveChangesAsync(); - session.Dispose(); + await session.DisposeAsync(); session = _store.CreateSession(); } diff --git a/samples/YesSql.Samples.Web/Controllers/HomeController.cs b/samples/YesSql.Samples.Web/Controllers/HomeController.cs index 8d6319f4..2dd2e3ef 100644 --- a/samples/YesSql.Samples.Web/Controllers/HomeController.cs +++ b/samples/YesSql.Samples.Web/Controllers/HomeController.cs @@ -26,49 +26,46 @@ public async Task Index([ModelBinder(BinderType = typeof(QueryFil { IEnumerable posts; - using (var session = _store.CreateSession()) - { - var query = session.Query(); + await using var session = _store.CreateSession(); + var query = session.Query(); - await filterResult.ExecuteAsync(new WebQueryExecutionContext(HttpContext.RequestServices, query)); + await filterResult.ExecuteAsync(new WebQueryExecutionContext(HttpContext.RequestServices, query)); - var currentSearchText = filterResult.ToString(); + var currentSearchText = filterResult.ToString(); - posts = await query.ListAsync(); + posts = await query.ListAsync(); - // Map termList to model. - // i.e. SelectedFilter needs to be filled with - // the selected filter value from the term. - var search = new Filter - { - SearchText = currentSearchText, - OriginalSearchText = currentSearchText - }; - - filterResult.MapTo(search); + // Map termList to model. + // i.e. SelectedFilter needs to be filled with + // the selected filter value from the term. + var search = new Filter + { + SearchText = currentSearchText, + OriginalSearchText = currentSearchText + }; + filterResult.MapTo(search); - search.Statuses = new List() + search.Statuses = new List() { new SelectListItem("Select...", "", search.SelectedStatus == BlogPostStatus.Default), new SelectListItem("Published", BlogPostStatus.Published.ToString(), search.SelectedStatus == BlogPostStatus.Published), new SelectListItem("Draft", BlogPostStatus.Draft.ToString(), search.SelectedStatus == BlogPostStatus.Draft) }; - search.Sorts = new List() + search.Sorts = new List() { new SelectListItem("Newest", BlogPostSort.Newest.ToString(), search.SelectedSort == BlogPostSort.Newest), new SelectListItem("Oldest", BlogPostSort.Oldest.ToString(), search.SelectedSort == BlogPostSort.Oldest) }; - var vm = new BlogPostViewModel - { - BlogPosts = posts, - Search = search - }; + var vm = new BlogPostViewModel + { + BlogPosts = posts, + Search = search + }; - return View(vm); - } + return View(vm); } [HttpPost("/")] diff --git a/samples/YesSql.Samples.Web/Program.cs b/samples/YesSql.Samples.Web/Program.cs index ddcb53a4..1e2d57fe 100644 --- a/samples/YesSql.Samples.Web/Program.cs +++ b/samples/YesSql.Samples.Web/Program.cs @@ -1,17 +1,182 @@ -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.IO; +using YesSql; +using YesSql.Filters.Query; +using YesSql.Provider.Sqlite; +using YesSql.Samples.Web.Indexes; +using YesSql.Samples.Web.Models; +using YesSql.Samples.Web.ViewModels; +using YesSql.Services; +using YesSql.Sql; -namespace YesSql.Samples.Web +var builder = WebApplication.CreateBuilder(args); + +var filename = "yessql.db"; + +if (File.Exists(filename)) { - public class Program - { - public static void Main(string[] args) - { - CreateWebHostBuilder(args).Build().Run(); - } - - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); - } + File.Delete(filename); } + +builder.Services.AddDbProvider(config => + config.UseSqLite($"Data Source={filename};Cache=Shared")); + +builder.Services.AddMvc(options => options.EnableEndpointRouting = false); + +builder.Services.AddSingleton(sp => + new QueryEngineBuilder() + .WithNamedTerm("status", builder => builder + .OneCondition((val, query) => + { + if (Enum.TryParse(val, true, out var e)) + { + switch (e) + { + case BlogPostStatus.Published: + query.With(x => x.Published); + break; + case BlogPostStatus.Draft: + query.With(x => !x.Published); + break; + default: + break; + } + } + + return query; + }) + .MapTo((val, model) => + { + if (Enum.TryParse(val, true, out var e)) + { + model.SelectedStatus = e; + } + }) + .MapFrom((model) => + { + if (model.SelectedStatus != BlogPostStatus.Default) + { + return (true, model.SelectedStatus.ToString()); + } + + return (false, string.Empty); + + }) + ) + .WithNamedTerm("sort", b => b + .OneCondition((val, query) => + { + if (Enum.TryParse(val, true, out var e)) + { + switch (e) + { + case BlogPostSort.Newest: + query.With().OrderByDescending(x => x.PublishedUtc); + break; + case BlogPostSort.Oldest: + query.With().OrderBy(x => x.PublishedUtc); + break; + default: + query.With().OrderByDescending(x => x.PublishedUtc); + break; + } + } + else + { + query.With().OrderByDescending(x => x.PublishedUtc); + } + + return query; + }) + .MapTo((val, model) => + { + if (Enum.TryParse(val, true, out var e)) + { + model.SelectedSort = e; + } + }) + .MapFrom((model) => + { + if (model.SelectedSort != BlogPostSort.Newest) + { + return (true, model.SelectedSort.ToString()); + } + + return (false, string.Empty); + + }) + .AlwaysRun() + ) + .WithDefaultTerm("title", b => b + .ManyCondition( + ((val, query) => query.With(x => x.Title.Contains(val))), + ((val, query) => query.With(x => x.Title.IsNotIn(s => s.Title, w => w.Title.Contains(val)))) + ) + ) + .Build() +); + +var app = builder.Build(); + +app.UseRouting() + .UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + +var store = app.Services.GetRequiredService(); +store.RegisterIndexes(new[] { new BlogPostIndexProvider() }); + +await using var connection = store.Configuration.ConnectionFactory.CreateConnection(); +await connection.OpenAsync(); + +await using var transaction = await connection.BeginTransactionAsync(store.Configuration.IsolationLevel); +var schemaBuilder = new SchemaBuilder(store.Configuration, transaction); + +await schemaBuilder.CreateMapIndexTableAsync(table => table + .Column("Title") + .Column("Author") + .Column("Content") + .Column("PublishedUtc") + .Column("Published") + ); + +await transaction.CommitAsync(); + +await using var session = app.Services.GetRequiredService().CreateSession(); +await session.SaveAsync(new BlogPost +{ + Title = "On the beach in the sand we found lizards", + Author = "Steve Balmer", + Content = "Steve's first post", + PublishedUtc = DateTime.UtcNow, + Published = false, + Tags = Array.Empty() +}); + +await session.SaveAsync(new BlogPost +{ + Title = "On the beach in the sand we built sandcastles", + Author = "Bill Gates", + Content = "Bill first post", + PublishedUtc = DateTime.UtcNow, + Published = true, + Tags = Array.Empty() +}); + +await session.SaveAsync(new BlogPost +{ + Title = "On the mountain it snowed at the lake", + Author = "Paul Allen", + Content = "Paul's first post", + PublishedUtc = DateTime.UtcNow, + Published = true, + Tags = Array.Empty() +}); + +await session.SaveChangesAsync(); +await connection.CloseAsync(); + +await app.RunAsync(); diff --git a/samples/YesSql.Samples.Web/Startup.cs b/samples/YesSql.Samples.Web/Startup.cs deleted file mode 100644 index 092b7844..00000000 --- a/samples/YesSql.Samples.Web/Startup.cs +++ /dev/null @@ -1,193 +0,0 @@ -using System; -using System.IO; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using YesSql.Filters.Query; -using YesSql.Provider.Sqlite; -using YesSql.Samples.Web.Indexes; -using YesSql.Samples.Web.Models; -using YesSql.Samples.Web.ViewModels; -using YesSql.Services; -using YesSql.Sql; - -namespace YesSql.Samples.Web -{ - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - var filename = "yessql.db"; - - if (File.Exists(filename)) - { - File.Delete(filename); - } - - services.AddDbProvider(config => - config.UseSqLite($"Data Source={filename};Cache=Shared")); - - services.AddMvc(options => options.EnableEndpointRouting = false); - - services.AddSingleton>(sp => - new QueryEngineBuilder() - .WithNamedTerm("status", builder => builder - .OneCondition((val, query) => - { - if (Enum.TryParse(val, true, out var e)) - { - switch (e) - { - case BlogPostStatus.Published: - query.With(x => x.Published); - break; - case BlogPostStatus.Draft: - query.With(x => !x.Published); - break; - default: - break; - } - } - - return query; - }) - .MapTo((val, model) => - { - if (Enum.TryParse(val, true, out var e)) - { - model.SelectedStatus = e; - } - }) - .MapFrom((model) => - { - if (model.SelectedStatus != BlogPostStatus.Default) - { - return (true, model.SelectedStatus.ToString()); - } - - return (false, string.Empty); - - }) - ) - .WithNamedTerm("sort", b => b - .OneCondition((val, query) => - { - if (Enum.TryParse(val, true, out var e)) - { - switch (e) - { - case BlogPostSort.Newest: - query.With().OrderByDescending(x => x.PublishedUtc); - break; - case BlogPostSort.Oldest: - query.With().OrderBy(x => x.PublishedUtc); - break; - default: - query.With().OrderByDescending(x => x.PublishedUtc); - break; - } - } - else - { - query.With().OrderByDescending(x => x.PublishedUtc); - } - - return query; - }) - .MapTo((val, model) => - { - if (Enum.TryParse(val, true, out var e)) - { - model.SelectedSort = e; - } - }) - .MapFrom((model) => - { - if (model.SelectedSort != BlogPostSort.Newest) - { - return (true, model.SelectedSort.ToString()); - } - - return (false, string.Empty); - - }) - .AlwaysRun() - ) - .WithDefaultTerm("title", b => b - .ManyCondition( - ((val, query) => query.With(x => x.Title.Contains(val))), - ((val, query) => query.With(x => x.Title.IsNotIn(s => s.Title, w => w.Title.Contains(val)))) - ) - ) - .Build() - ); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.UseRouting(); - - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - - var store = app.ApplicationServices.GetRequiredService(); - store.RegisterIndexes(new[] { new BlogPostIndexProvider() }); - - using (var connection = store.Configuration.ConnectionFactory.CreateConnection()) - { - connection.Open(); - - using (var transaction = connection.BeginTransaction(store.Configuration.IsolationLevel)) - { - new SchemaBuilder(store.Configuration, transaction) - .CreateMapIndexTable(table => table - .Column("Title") - .Column("Author") - .Column("Content") - .Column("PublishedUtc") - .Column("Published") - ); - - transaction.Commit(); - } - } - - using (var session = app.ApplicationServices.GetRequiredService().CreateSession()) - { - session.Save(new BlogPost - { - Title = "On the beach in the sand we found lizards", - Author = "Steve Balmer", - Content = "Steves first post", - PublishedUtc = DateTime.UtcNow, - Published = false, - Tags = Array.Empty() - }); - - session.Save(new BlogPost - { - Title = "On the beach in the sand we built sandcastles", - Author = "Bill Gates", - Content = "Bill first post", - PublishedUtc = DateTime.UtcNow, - Published = true, - Tags = Array.Empty() - }); - - session.Save(new BlogPost - { - Title = "On the mountain it snowed at the lake", - Author = "Paul Allen", - Content = "Pauls first post", - PublishedUtc = DateTime.UtcNow, - Published = true, - Tags = Array.Empty() - }); - - session.SaveChangesAsync().GetAwaiter().GetResult(); - } - } - } -} diff --git a/src/YesSql.Abstractions/IIdGenerator.cs b/src/YesSql.Abstractions/IIdGenerator.cs index 56388056..33358a72 100644 --- a/src/YesSql.Abstractions/IIdGenerator.cs +++ b/src/YesSql.Abstractions/IIdGenerator.cs @@ -1,3 +1,4 @@ +using System; using System.Threading.Tasks; namespace YesSql @@ -24,6 +25,14 @@ public interface IIdGenerator /// /// The name of the collection to generate the identifier for. /// A unique identifier + [Obsolete($"Instead, utilize the {nameof(GetNextIdAsync)} method. This current method is slated for removal in upcoming releases.")] long GetNextId(string collection); + + /// + /// Generates a unique identifier for the store. + /// + /// The name of the collection to generate the identifier for. + /// A unique identifier + Task GetNextIdAsync(string collection); } } diff --git a/src/YesSql.Abstractions/ISchemaBuilder.cs b/src/YesSql.Abstractions/ISchemaBuilder.cs index 5a983fb0..06dd0f07 100644 --- a/src/YesSql.Abstractions/ISchemaBuilder.cs +++ b/src/YesSql.Abstractions/ISchemaBuilder.cs @@ -1,5 +1,6 @@ using System; using System.Data.Common; +using System.Threading.Tasks; using YesSql.Sql.Schema; namespace YesSql.Sql @@ -42,56 +43,123 @@ public interface ISchemaBuilder /// /// Alters an existing table. /// + [Obsolete($"Instead, utilize the {nameof(AlterTableAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder AlterTable(string name, Action table); /// /// Alters an index table. /// + [Obsolete($"Instead, utilize the {nameof(AlterIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder AlterIndexTable(Type indexType, Action table, string collection); - + /// /// Creates a foreign key. /// + [Obsolete($"Instead, utilize the {nameof(CreateForeignKeyAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder CreateForeignKey(string name, string srcTable, string[] srcColumns, string destTable, string[] destColumns); - + /// /// Creates a Map Index table. /// + [Obsolete($"Instead, utilize the {nameof(CreateMapIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder CreateMapIndexTable(Type indexType, Action table, string collection); - + /// /// Creates a Reduce Index table. /// + [Obsolete($"Instead, utilize the {nameof(CreateReduceIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder CreateReduceIndexTable(Type indexType, Action table, string collection); - + /// /// Creates a table. /// + [Obsolete($"Instead, utilize the {nameof(CreateTableAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder CreateTable(string name, Action table); - + /// /// Removes a foreign key. /// + [Obsolete($"Instead, utilize the {nameof(DropForeignKeyAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder DropForeignKey(string srcTable, string name); - + /// /// Removes a Map Index table. /// + [Obsolete($"Instead, utilize the {nameof(DropMapIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder DropMapIndexTable(Type indexType, string collection = null); /// /// Removes a Reduce Index table. /// + [Obsolete($"Instead, utilize the {nameof(DropReduceIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder DropReduceIndexTable(Type indexType, string collection = null); /// /// Removes a table. /// + [Obsolete($"Instead, utilize the {nameof(DropTableAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder DropTable(string name); /// /// Creates a database schema. /// + [Obsolete($"Instead, utilize the {nameof(CreateSchemaAsync)} method. This current method is slated for removal in upcoming releases.")] ISchemaBuilder CreateSchema(string schema); + + + /// + /// Alters an existing table. + /// + Task AlterTableAsync(string name, Action table); + + /// + /// Alters an index table. + /// + Task AlterIndexTableAsync(Type indexType, Action table, string collection); + + /// + /// Creates a foreign key. + /// + Task CreateForeignKeyAsync(string name, string srcTable, string[] srcColumns, string destTable, string[] destColumns); + + /// + /// Creates a Map Index table. + /// + Task CreateMapIndexTableAsync(Type indexType, Action table, string collection); + + /// + /// Creates a Reduce Index table. + /// + Task CreateReduceIndexTableAsync(Type indexType, Action table, string collection); + + /// + /// Creates a table. + /// + Task CreateTableAsync(string name, Action table); + + /// + /// Removes a foreign key. + /// + Task DropForeignKeyAsync(string srcTable, string name); + + /// + /// Removes a Map Index table. + /// + Task DropMapIndexTableAsync(Type indexType, string collection = null); + + /// + /// Removes a Reduce Index table. + /// + Task DropReduceIndexTableAsync(Type indexType, string collection = null); + + /// + /// Removes a table. + /// + Task DropTableAsync(string name); + + /// + /// Creates a database schema. + /// + Task CreateSchemaAsync(string schema); } } diff --git a/src/YesSql.Abstractions/ISession.cs b/src/YesSql.Abstractions/ISession.cs index 5b603f69..3ce0369d 100644 --- a/src/YesSql.Abstractions/ISession.cs +++ b/src/YesSql.Abstractions/ISession.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Data; using System.Data.Common; -using System.Linq; using System.Threading.Tasks; using YesSql.Indexes; @@ -20,8 +19,19 @@ public interface ISession : IDisposable, IAsyncDisposable /// The entity to save. /// If true, a is thrown if the entity has been updated concurrently by another session. /// The name of the collection to store the object in. + [Obsolete($"Instead, utilize the {nameof(SaveAsync)} method. This current method is slated for removal in upcoming releases.")] void Save(object obj, bool checkConcurrency = false, string collection = null); + + /// + /// Saves a new or existing object to the store, and updates + /// the corresponding indexes. + /// + /// The entity to save. + /// If true, a is thrown if the entity has been updated concurrently by another session. + /// The name of the collection to store the object in. + Task SaveAsync(object obj, bool checkConcurrency = false, string collection = null); + /// /// Deletes an object and its indexes from the store. /// @@ -128,74 +138,4 @@ public interface ISession : IDisposable, IAsyncDisposable /// IStore Store { get; } } - - public static class SessionExtensions - { - /// - /// Loads an object by its id. - /// - /// The object or null. - public async static Task GetAsync(this ISession session, long id, string collection = null) where T : class - { - return (await session.GetAsync(new[] { id }, collection)).FirstOrDefault(); - } - - /// - /// Loads objects by id. - /// - /// A collection of objects in the same order they were defined. - public static Task> GetAsync(this ISession session, int[] ids, string collection = null) where T : class => session.GetAsync(ids.Select(x => (long)x).ToArray(), collection); - - /// - /// Imports an object in the local identity map. - /// - /// - /// This method can be used to re-attach an object that exists in the database - /// but was not loaded from this session, or has been duplicated. If not imported - /// in a session a duplicate record would tentatively be created in the database - /// and a duplicate primary key constraint would fail. - /// - /// - /// true if the object was imported, false otherwise. - /// - public static bool Import(this ISession session, object item, string collection = null) - { - return session.Import(item, 0, 0, collection); - } - - /// - /// Registers index providers that are used only during the lifetime of this session. - /// - /// The session. - /// The index providers to register. - /// The instance. - public static ISession RegisterIndexes(this ISession session, params IIndexProvider[] indexProviders) - { - return session.RegisterIndexes(indexProviders, null); - } - - /// - /// Registers index providers that are used only during the lifetime of this session. - /// - /// The session. - /// The index provider to register. - /// The name of the collection. - /// The instance. - public static ISession RegisterIndexes(this ISession session, IIndexProvider indexProvider, string collection = null) - { - return session.RegisterIndexes(new[] { indexProvider }, collection); - } - - /// - /// Saves a new or existing object to the store, and updates - /// the corresponding indexes. - /// - /// The session. - /// The entity to save. - /// The name of the collection. - public static void Save(this ISession session, object obj, string collection = null) - { - session.Save(obj, false, collection); - } - } } diff --git a/src/YesSql.Abstractions/Indexes/DescribeFor.cs b/src/YesSql.Abstractions/Indexes/DescribeFor.cs index 60f556b6..e376c209 100644 --- a/src/YesSql.Abstractions/Indexes/DescribeFor.cs +++ b/src/YesSql.Abstractions/Indexes/DescribeFor.cs @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; @@ -62,13 +63,13 @@ public IGroupFor Map(Func> map) public IMapFor When(Func predicate) { - _filter = x => predicate((T) x); + _filter = x => predicate((T)x); return this; } public IGroupFor Map(Func map) { - _map = x => Task.FromResult((IEnumerable) new[] { map(x) }); + _map = x => Task.FromResult((IEnumerable)new[] { map(x) }); return this; } @@ -84,6 +85,7 @@ public IGroupFor Map(Func> map) return this; } + public IReduceFor Group(Expression> group) { var memberExpression = group.Body as MemberExpression; @@ -102,10 +104,10 @@ public IReduceFor Group(Expression> gr GroupProperty = property; - var reduceDescibeFor = new IndexDescriptor(); - _reduceDescribeFor = reduceDescibeFor; + var reduceDescribeFor = new IndexDescriptor(); + _reduceDescribeFor = reduceDescribeFor; - return reduceDescibeFor; + return reduceDescribeFor; } public IDeleteFor Reduce(Func, TIndex> reduce) @@ -152,7 +154,6 @@ Func, IIndex> IDescribeFor.GetDelete() return (index, obj) => _delete((TIndex)index, obj.Cast()); } - } public class GroupedEnumerable : IGrouping where TIndex : IIndex @@ -176,7 +177,7 @@ public IEnumerator GetEnumerator() return _enumerable.Cast().GetEnumerator(); } - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } diff --git a/src/YesSql.Abstractions/SchemaBuilderExtensions.cs b/src/YesSql.Abstractions/SchemaBuilderExtensions.cs index f0b646b7..aa302c26 100644 --- a/src/YesSql.Abstractions/SchemaBuilderExtensions.cs +++ b/src/YesSql.Abstractions/SchemaBuilderExtensions.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using YesSql.Sql.Schema; namespace YesSql.Sql @@ -7,33 +8,41 @@ namespace YesSql.Sql public static class SchemaBuilderExtensions { public static IEnumerable CreateSql(this ICommandInterpreter builder, ISchemaCommand command) - { - return builder.CreateSql(new[] { command }); - } + => builder.CreateSql(new[] { command }); + [Obsolete($"Instead, utilize the {nameof(CreateReduceIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] public static ISchemaBuilder CreateReduceIndexTable(this ISchemaBuilder builder, Action table, string collection = null) - { - return builder.CreateReduceIndexTable(typeof(T), table, collection); - } + => builder.CreateReduceIndexTable(typeof(T), table, collection); + [Obsolete($"Instead, utilize the {nameof(DropReduceIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] public static ISchemaBuilder DropReduceIndexTable(this ISchemaBuilder builder, string collection = null) - { - return builder.DropReduceIndexTable(typeof(T), collection); - } + => builder.DropReduceIndexTable(typeof(T), collection); + [Obsolete($"Instead, utilize the {nameof(CreateMapIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] public static ISchemaBuilder CreateMapIndexTable(this ISchemaBuilder builder, Action table, string collection = null) - { - return builder.CreateMapIndexTable(typeof(T), table, collection); - } + => builder.CreateMapIndexTable(typeof(T), table, collection); + [Obsolete($"Instead, utilize the {nameof(DropMapIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] public static ISchemaBuilder DropMapIndexTable(this ISchemaBuilder builder, string collection = null) - { - return builder.DropMapIndexTable(typeof(T), collection); - } + => builder.DropMapIndexTable(typeof(T), collection); + [Obsolete($"Instead, utilize the {nameof(AlterIndexTableAsync)} method. This current method is slated for removal in upcoming releases.")] public static ISchemaBuilder AlterIndexTable(this ISchemaBuilder builder, Action table, string collection = null) - { - return builder.AlterIndexTable(typeof(T), table, collection); - } + => builder.AlterIndexTable(typeof(T), table, collection); + + public static Task CreateReduceIndexTableAsync(this ISchemaBuilder builder, Action table, string collection = null) + => builder.CreateReduceIndexTableAsync(typeof(T), table, collection); + + public static Task DropReduceIndexTableAsync(this ISchemaBuilder builder, string collection = null) + => builder.DropReduceIndexTableAsync(typeof(T), collection); + + public static Task CreateMapIndexTableAsync(this ISchemaBuilder builder, Action table, string collection = null) + => builder.CreateMapIndexTableAsync(typeof(T), table, collection); + + public static Task DropMapIndexTableAsync(this ISchemaBuilder builder, string collection = null) + => builder.DropMapIndexTableAsync(typeof(T), collection); + + public static Task AlterIndexTableAsync(this ISchemaBuilder builder, Action table, string collection = null) + => builder.AlterIndexTableAsync(typeof(T), table, collection); } } diff --git a/src/YesSql.Abstractions/SessionExtensions.cs b/src/YesSql.Abstractions/SessionExtensions.cs new file mode 100644 index 00000000..02053329 --- /dev/null +++ b/src/YesSql.Abstractions/SessionExtensions.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using YesSql.Indexes; + +namespace YesSql +{ + public static class SessionExtensions + { + /// + /// Loads an object by its id. + /// + /// The object or null. + public async static Task GetAsync(this ISession session, long id, string collection = null) where T : class + { + return (await session.GetAsync(new[] { id }, collection)).FirstOrDefault(); + } + + /// + /// Loads objects by id. + /// + /// A collection of objects in the same order they were defined. + public static Task> GetAsync(this ISession session, int[] ids, string collection = null) where T : class => session.GetAsync(ids.Select(x => (long)x).ToArray(), collection); + + /// + /// Imports an object in the local identity map. + /// + /// + /// This method can be used to re-attach an object that exists in the database + /// but was not loaded from this session, or has been duplicated. If not imported + /// in a session a duplicate record would tentatively be created in the database + /// and a duplicate primary key constraint would fail. + /// + /// + /// true if the object was imported, false otherwise. + /// + public static bool Import(this ISession session, object item, string collection = null) + { + return session.Import(item, 0, 0, collection); + } + + /// + /// Registers index providers that are used only during the lifetime of this session. + /// + /// The session. + /// The index providers to register. + /// The instance. + public static ISession RegisterIndexes(this ISession session, params IIndexProvider[] indexProviders) + { + return session.RegisterIndexes(indexProviders, null); + } + + /// + /// Registers index providers that are used only during the lifetime of this session. + /// + /// The session. + /// The index provider to register. + /// The name of the collection. + /// The instance. + public static ISession RegisterIndexes(this ISession session, IIndexProvider indexProvider, string collection = null) + { + return session.RegisterIndexes(new[] { indexProvider }, collection); + } + + /// + /// Saves a new or existing object to the store, and updates + /// the corresponding indexes. + /// + /// The session. + /// The entity to save. + /// The name of the collection. + [Obsolete($"Instead, utilize the {nameof(SaveAsync)} method. This current method is slated for removal in upcoming releases.")] + public static void Save(this ISession session, object obj, string collection = null) + => session.SaveAsync(obj, collection).ConfigureAwait(false).GetAwaiter().GetResult(); + + public static Task SaveAsync(this ISession session, object obj, string collection = null) + => session.SaveAsync(obj, false, collection); + } +} diff --git a/src/YesSql.Core/Services/DbBlockIdGenerator.cs b/src/YesSql.Core/Services/DbBlockIdGenerator.cs index 25d3ba2a..afa4e159 100644 --- a/src/YesSql.Core/Services/DbBlockIdGenerator.cs +++ b/src/YesSql.Core/Services/DbBlockIdGenerator.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; using YesSql.Sql; @@ -13,7 +14,7 @@ namespace YesSql.Services public class DbBlockIdGenerator : IIdGenerator { internal long _initialValue = 1; - private readonly object _synLock = new(); + private readonly SemaphoreSlim _semaphoreSlim = new(1, 1); public static string TableName => "Identifiers"; public readonly int MaxRetries = 20; @@ -50,36 +51,38 @@ public async Task InitializeAsync(IStore store) UpdateCommand = "UPDATE " + _dialect.QuoteForTableName(_tablePrefix + TableName, _schema) + " SET " + _dialect.QuoteForColumnName("nextval") + "=@new WHERE " + _dialect.QuoteForColumnName("nextval") + " = @previous AND " + _dialect.QuoteForColumnName("dimension") + " = @dimension;"; InsertCommand = "INSERT INTO " + _dialect.QuoteForTableName(_tablePrefix + TableName, _schema) + " (" + _dialect.QuoteForColumnName("dimension") + ", " + _dialect.QuoteForColumnName("nextval") + ") VALUES(@dimension, @nextval);"; - await using (var connection = store.Configuration.ConnectionFactory.CreateConnection()) + await using var connection = store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); + + await using var transaction = await connection.BeginTransactionAsync(store.Configuration.IsolationLevel); + + try { - await connection.OpenAsync(); + var localBuilder = new SchemaBuilder(store.Configuration, transaction, true); - try - { - await using (var transaction = connection.BeginTransaction(store.Configuration.IsolationLevel)) - { - var localBuilder = new SchemaBuilder(store.Configuration, transaction, false); - - localBuilder.CreateTable(TableName, table => table - .Column("dimension", column => column.PrimaryKey().NotNull()) - .Column("nextval") - ); - - await transaction.CommitAsync(); - } - } - catch - { + await localBuilder.CreateTableAsync(TableName, table => table + .Column("dimension", column => column.PrimaryKey().NotNull()) + .Column("nextval") + ); - } + await transaction.CommitAsync(); + } + catch + { + await transaction.RollbackAsync(); } } public long GetNextId(string collection) + => GetNextIdAsync(collection).ConfigureAwait(false).GetAwaiter().GetResult(); + + public async Task GetNextIdAsync(string collection) { - collection ??= ""; + collection ??= string.Empty; + + await _semaphoreSlim.WaitAsync(); - lock (_synLock) + try { if (!_ranges.TryGetValue(collection, out var range)) { @@ -90,29 +93,33 @@ public long GetNextId(string collection) if (nextId > range.End) { - LeaseRange(range); + await LeaseRangeAsync(range); nextId = range.Next(); } return nextId; } + finally + { + _semaphoreSlim.Release(); + } } - private void LeaseRange(Range range) + private async Task LeaseRangeAsync(Range range) { var affectedRows = 0; - long nextval = 0; + long nextValue = 0; var retries = 0; - using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); - connection.Open(); + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); do { // Ensure we overwrite the value that has been read by this // instance in case another client is trying to lease a range // at the same time - using (var transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted)) + await using (var transaction = await connection.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted)) { try { @@ -131,7 +138,7 @@ private void LeaseRange(Range range) _store.Configuration.Logger.LogTrace(SelectCommand); } - nextval = Convert.ToInt64(selectCommand.ExecuteScalar()); + nextValue = Convert.ToInt64(await selectCommand.ExecuteScalarAsync()); var updateCommand = connection.CreateCommand(); updateCommand.CommandText = UpdateCommand; @@ -142,12 +149,12 @@ private void LeaseRange(Range range) updateCommand.Parameters.Add(updateDimension); var newValue = updateCommand.CreateParameter(); - newValue.Value = nextval + _blockSize; + newValue.Value = nextValue + _blockSize; newValue.ParameterName = "@new"; updateCommand.Parameters.Add(newValue); var previousValue = updateCommand.CreateParameter(); - previousValue.Value = nextval; + previousValue.Value = nextValue; previousValue.ParameterName = "@previous"; updateCommand.Parameters.Add(previousValue); @@ -157,14 +164,14 @@ private void LeaseRange(Range range) { _store.Configuration.Logger.LogTrace(UpdateCommand); } - affectedRows = updateCommand.ExecuteNonQuery(); + affectedRows = await updateCommand.ExecuteNonQueryAsync(); - transaction.Commit(); + await transaction.CommitAsync(); } catch { affectedRows = 0; - transaction.Rollback(); + await transaction.RollbackAsync(); } } @@ -175,7 +182,7 @@ private void LeaseRange(Range range) } while (affectedRows == 0); - range.SetBlock(nextval, _blockSize); + range.SetBlock(nextValue, _blockSize); } public async Task InitializeCollectionAsync(IConfiguration configuration, string collection) @@ -187,75 +194,70 @@ public async Task InitializeCollectionAsync(IConfiguration configuration, string object nextval; - await using (var connection = configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); - - await using (var transaction = connection.BeginTransaction(configuration.IsolationLevel)) - { - // Does the record already exist? - var selectCommand = transaction.Connection.CreateCommand(); - selectCommand.CommandText = SelectCommand; + await using var connection = configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - var selectDimension = selectCommand.CreateParameter(); - selectDimension.Value = collection; - selectDimension.ParameterName = "@dimension"; - selectCommand.Parameters.Add(selectDimension); - - selectCommand.Transaction = transaction; + await using (var transaction = await connection.BeginTransactionAsync(configuration.IsolationLevel)) + { + // Does the record already exist? + var selectCommand = transaction.Connection.CreateCommand(); + selectCommand.CommandText = SelectCommand; - if (_store.Configuration.Logger.IsEnabled(LogLevel.Trace)) - { - _store.Configuration.Logger.LogTrace(SelectCommand); - } + var selectDimension = selectCommand.CreateParameter(); + selectDimension.Value = collection; + selectDimension.ParameterName = "@dimension"; + selectCommand.Parameters.Add(selectDimension); - nextval = await selectCommand.ExecuteScalarAsync(); + selectCommand.Transaction = transaction; - await transaction.CommitAsync(); + if (_store.Configuration.Logger.IsEnabled(LogLevel.Trace)) + { + _store.Configuration.Logger.LogTrace(SelectCommand); } - if (nextval == null) - { - // Try to create a new record. If it fails, retry reading the record. - try - { - await using (var transaction = connection.BeginTransaction(configuration.IsolationLevel)) - { - // To prevent concurrency issues when creating this record (it must be unique) - // we generate a random collection name, then update it safely + nextval = await selectCommand.ExecuteScalarAsync(); - var command = transaction.Connection.CreateCommand(); - command.CommandText = InsertCommand; - command.Transaction = transaction; + await transaction.CommitAsync(); + } - var dimensionParameter = command.CreateParameter(); - dimensionParameter.Value = collection; - dimensionParameter.ParameterName = "@dimension"; - command.Parameters.Add(dimensionParameter); + if (nextval == null) + { + // Try to create a new record. If it fails, retry reading the record. + try + { + await using var transaction = await connection.BeginTransactionAsync(configuration.IsolationLevel); + // To prevent concurrency issues when creating this record (it must be unique) + // we generate a random collection name, then update it safely - var nextValParameter = command.CreateParameter(); - nextValParameter.Value = _initialValue; - nextValParameter.ParameterName = "@nextval"; - command.Parameters.Add(nextValParameter); + var command = transaction.Connection.CreateCommand(); + command.CommandText = InsertCommand; + command.Transaction = transaction; - if (_store.Configuration.Logger.IsEnabled(LogLevel.Trace)) - { - _store.Configuration.Logger.LogTrace(InsertCommand); - } + var dimensionParameter = command.CreateParameter(); + dimensionParameter.Value = collection; + dimensionParameter.ParameterName = "@dimension"; + command.Parameters.Add(dimensionParameter); - await command.ExecuteNonQueryAsync(); + var nextValParameter = command.CreateParameter(); + nextValParameter.Value = _initialValue; + nextValParameter.ParameterName = "@nextval"; + command.Parameters.Add(nextValParameter); - await transaction.CommitAsync(); - } - } - catch + if (_store.Configuration.Logger.IsEnabled(LogLevel.Trace)) { - await InitializeCollectionAsync(configuration, collection); + _store.Configuration.Logger.LogTrace(InsertCommand); } + + await command.ExecuteNonQueryAsync(); + await transaction.CommitAsync(); } + catch + { + await InitializeCollectionAsync(configuration, collection); + } + } - _ranges[collection] = new Range(collection); - } + _ranges[collection] = new Range(collection); } private class Range diff --git a/src/YesSql.Core/Services/DefaultIdGenerator.cs b/src/YesSql.Core/Services/DefaultIdGenerator.cs index 9c96703f..ead0539a 100644 --- a/src/YesSql.Core/Services/DefaultIdGenerator.cs +++ b/src/YesSql.Core/Services/DefaultIdGenerator.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; namespace YesSql.Services @@ -10,17 +11,21 @@ namespace YesSql.Services /// public class DefaultIdGenerator : IIdGenerator { - private object _synLock = new object(); + private readonly SemaphoreSlim _semaphoreSlim = new(1, 1); - private Dictionary _seeds = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _seeds = new(StringComparer.OrdinalIgnoreCase); private ISqlDialect _dialect; public long GetNextId(string collection) + => GetNextIdAsync(collection).ConfigureAwait(false).GetAwaiter().GetResult(); + + public async Task GetNextIdAsync(string collection) { - lock (_synLock) + await _semaphoreSlim.WaitAsync(); + try { - collection = collection ?? ""; + collection ??= string.Empty; if (!_seeds.TryGetValue(collection, out var seed)) { @@ -29,6 +34,10 @@ public long GetNextId(string collection) return _seeds[collection] = seed + 1; } + finally + { + _semaphoreSlim.Release(); + } } public Task InitializeAsync(IStore store) @@ -41,31 +50,27 @@ public async Task InitializeCollectionAsync(IConfiguration configuration, string { // Extract the current max value from the database - await using (var connection = configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); + await using var connection = configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - await using (var transaction = connection.BeginTransaction(configuration.IsolationLevel)) - { - var tableName = configuration.TableNameConvention.GetDocumentTable(collection); + await using var transaction = await connection.BeginTransactionAsync(configuration.IsolationLevel); + var tableName = configuration.TableNameConvention.GetDocumentTable(collection); - var sql = "SELECT MAX(" + _dialect.QuoteForColumnName("Id") + ") FROM " + _dialect.QuoteForTableName(configuration.TablePrefix + tableName, configuration.Schema); + var sql = "SELECT MAX(" + _dialect.QuoteForColumnName("Id") + ") FROM " + _dialect.QuoteForTableName(configuration.TablePrefix + tableName, configuration.Schema); - var selectCommand = transaction.Connection.CreateCommand(); - selectCommand.CommandText = sql; - selectCommand.Transaction = transaction; + var selectCommand = transaction.Connection.CreateCommand(); + selectCommand.CommandText = sql; + selectCommand.Transaction = transaction; - if (configuration.Logger.IsEnabled(LogLevel.Trace)) - { - configuration.Logger.LogTrace(sql); - } - var result = await selectCommand.ExecuteScalarAsync(); + if (configuration.Logger.IsEnabled(LogLevel.Trace)) + { + configuration.Logger.LogTrace(sql); + } + var result = await selectCommand.ExecuteScalarAsync(); - await transaction.CommitAsync(); + await transaction.CommitAsync(); - _seeds[collection] = result == DBNull.Value ? 0 : Convert.ToInt64(result); - } - } + _seeds[collection] = result == DBNull.Value ? 0 : Convert.ToInt64(result); } } } diff --git a/src/YesSql.Core/Session.cs b/src/YesSql.Core/Session.cs index 7a7dc424..6ec17585 100644 --- a/src/YesSql.Core/Session.cs +++ b/src/YesSql.Core/Session.cs @@ -54,7 +54,7 @@ public ISession RegisterIndexes(IIndexProvider[] indexProviders, string collecti { if (indexProvider.CollectionName == null) { - indexProvider.CollectionName = collection ?? ""; + indexProvider.CollectionName = collection ?? string.Empty; } } @@ -81,7 +81,11 @@ private SessionState GetState(string collection) return state; } + [Obsolete] public void Save(object entity, bool checkConcurrency = false, string collection = null) + => SaveAsync(entity, checkConcurrency, collection).ConfigureAwait(false).GetAwaiter().GetResult(); + + public async Task SaveAsync(object entity, bool checkConcurrency = false, string collection = null) { var state = GetState(collection); @@ -132,7 +136,7 @@ public void Save(object entity, bool checkConcurrency = false, string collection } // It's a new entity - id = _store.GetNextId(collection); + id = await _store.GetNextIdAsync(collection); state.IdentityMap.AddEntity(id, entity); // Then assign a new identifier if it has one @@ -204,15 +208,11 @@ public bool Import(object entity, long id = 0, long version = 0, string collecti return true; } - else - { - throw new InvalidOperationException($"Invalid 'Id' value: {id}"); - } - } - else - { - throw new InvalidOperationException("Objects without an 'Id' property can't be imported if no 'id' argument is provided."); + + throw new InvalidOperationException($"Invalid 'Id' value: {id}"); } + + throw new InvalidOperationException("Objects without an 'Id' property can't be imported if no 'id' argument is provided."); } } @@ -630,7 +630,7 @@ public void Dispose(bool disposing) { try { - CommitOrRollbackTransaction(); + CommitOrRollbackTransactionAsync().ConfigureAwait(false).GetAwaiter().GetResult(); } catch { @@ -861,26 +861,6 @@ public async Task SaveChangesAsync() } } - private void CommitOrRollbackTransaction() - { - // This method is still used in Dispose() when SUPPORTS_ASYNC_TRANSACTIONS is defined - try - { - if (_cancel || !_save) - { - _transaction?.Rollback(); - } - else - { - _transaction?.Commit(); - } - } - finally - { - ReleaseConnection(); - } - } - public async ValueTask DisposeAsync() { // Do nothing if Dispose() was already called @@ -908,19 +888,16 @@ private async Task CommitOrRollbackTransactionAsync() { try { - if (!_cancel) + if (_transaction != null) { - if (_transaction != null) - { - await _transaction.CommitAsync(); - } - } - else - { - if (_transaction != null) + if (_cancel || !_save) { await _transaction.RollbackAsync(); + + return; } + + await _transaction.CommitAsync(); } } finally @@ -936,7 +913,7 @@ private async Task ReleaseTransactionAsync() { foreach (var state in _collectionStates.Values) { - // IndentityMap is cleared in ReleaseSession() + // IdentityMap is cleared in ReleaseSession() state._concurrent?.Clear(); state._saved?.Clear(); state._updated?.Clear(); @@ -1350,9 +1327,7 @@ public async Task CreateConnectionAsync() public DbTransaction CurrentTransaction => _transaction; public Task BeginTransactionAsync() - { - return BeginTransactionAsync(Store.Configuration.IsolationLevel); - } + => BeginTransactionAsync(Store.Configuration.IsolationLevel); /// /// Begins a new transaction if none has been yet. Use this method when writes need to be done. diff --git a/src/YesSql.Core/Sql/SchemaBuilder.cs b/src/YesSql.Core/Sql/SchemaBuilder.cs index 86441139..48a3631c 100644 --- a/src/YesSql.Core/Sql/SchemaBuilder.cs +++ b/src/YesSql.Core/Sql/SchemaBuilder.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Data.Common; +using System.Threading.Tasks; using YesSql.Sql.Schema; namespace YesSql.Sql @@ -33,31 +34,12 @@ public SchemaBuilder(IConfiguration configuration, DbTransaction transaction, bo IdentityColumnSize = configuration.IdentityColumnSize; } - private void Execute(IEnumerable statements) - { - foreach (var statement in statements) - { - if (string.IsNullOrEmpty(statement)) - { - continue; - } - - _logger.LogTrace(statement); - Connection.Execute(statement, null, Transaction); - } - } - - private string Prefix(string table) - { - return TablePrefix + table; - } - - public ISchemaBuilder CreateMapIndexTable(Type indexType, Action table, string collection) + public async Task CreateMapIndexTableAsync(Type indexType, Action table, string collection) { try { var indexName = indexType.Name; - var indexTable = TableNameConvention.GetIndexTable(indexType, collection); + var indexTable = TableNameConvention.GetIndexTable(indexType, collection); var createTable = new CreateTableCommand(Prefix(indexTable)); var documentTable = TableNameConvention.GetDocumentTable(collection); @@ -69,11 +51,11 @@ public ISchemaBuilder CreateMapIndexTable(Type indexType, Action + await AlterTableAsync(indexTable, table => table.CreateIndex($"IDX_FK_{indexTable}", "DocumentId") ); } @@ -84,11 +66,9 @@ public ISchemaBuilder CreateMapIndexTable(Type indexType, Action table, string collection = null) + public async Task CreateReduceIndexTableAsync(Type indexType, Action table, string collection = null) { try { @@ -103,19 +83,19 @@ public ISchemaBuilder CreateReduceIndexTable(Type indexType, Action bridge + await CreateTableAsync(bridgeTableName, bridge => bridge .Column(IdentityColumnSize, indexName + "Id", column => column.NotNull()) .Column(IdentityColumnSize, "DocumentId", column => column.NotNull()) ); - CreateForeignKey("FK_" + bridgeTableName + "_Id", bridgeTableName, new[] { indexName + "Id" }, indexTable, new[] { "Id" }); - CreateForeignKey("FK_" + bridgeTableName + "_DocumentId", bridgeTableName, new[] { "DocumentId" }, documentTable, new[] { "Id" }); + await CreateForeignKeyAsync("FK_" + bridgeTableName + "_Id", bridgeTableName, new[] { indexName + "Id" }, indexTable, new[] { "Id" }); + await CreateForeignKeyAsync("FK_" + bridgeTableName + "_DocumentId", bridgeTableName, new[] { "DocumentId" }, documentTable, new[] { "Id" }); - AlterTable(bridgeTableName, table => + await AlterTableAsync(bridgeTableName, table => table.CreateIndex($"IDX_FK_{bridgeTableName}", indexName + "Id", "DocumentId") ); } @@ -126,11 +106,9 @@ public ISchemaBuilder CreateReduceIndexTable(Type indexType, Action table) + public async Task CreateTableAsync(string name, Action table) { try { var createTable = new CreateTableCommand(Prefix(name)); table(createTable); - Execute(_commandInterpreter.CreateSql(createTable)); + await ExecuteAsync(_commandInterpreter.CreateSql(createTable)); } catch { @@ -199,17 +173,15 @@ public ISchemaBuilder CreateTable(string name, Action table throw; } } - - return this; } - public ISchemaBuilder AlterTable(string name, Action table) + public async Task AlterTableAsync(string name, Action table) { try { var alterTable = new AlterTableCommand(Prefix(name), Dialect, TablePrefix); table(alterTable); - Execute(_commandInterpreter.CreateSql(alterTable)); + await ExecuteAsync(_commandInterpreter.CreateSql(alterTable)); } catch { @@ -218,24 +190,20 @@ public ISchemaBuilder AlterTable(string name, Action table) throw; } } - - return this; } - public ISchemaBuilder AlterIndexTable(Type indexType, Action table, string collection) + public async Task AlterIndexTableAsync(Type indexType, Action table, string collection) { var indexTable = TableNameConvention.GetIndexTable(indexType, collection); - AlterTable(indexTable, table); - - return this; + await AlterTableAsync(indexTable, table); } - public ISchemaBuilder DropTable(string name) + public async Task DropTableAsync(string name) { try { var deleteTable = new DropTableCommand(Prefix(name)); - Execute(_commandInterpreter.CreateSql(deleteTable)); + await ExecuteAsync(_commandInterpreter.CreateSql(deleteTable)); } catch { @@ -244,17 +212,15 @@ public ISchemaBuilder DropTable(string name) throw; } } - - return this; } - public ISchemaBuilder CreateForeignKey(string name, string srcTable, string[] srcColumns, string destTable, string[] destColumns) + public async Task CreateForeignKeyAsync(string name, string srcTable, string[] srcColumns, string destTable, string[] destColumns) { try { var command = new CreateForeignKeyCommand(Dialect.FormatKeyName(Prefix(name)), Prefix(srcTable), srcColumns, Prefix(destTable), destColumns); var sql = _commandInterpreter.CreateSql(command); - Execute(sql); + await ExecuteAsync(sql); } catch { @@ -263,16 +229,14 @@ public ISchemaBuilder CreateForeignKey(string name, string srcTable, string[] sr throw; } } - - return this; } - public ISchemaBuilder DropForeignKey(string srcTable, string name) + public async Task DropForeignKeyAsync(string srcTable, string name) { try { var command = new DropForeignKeyCommand(Dialect.FormatKeyName(Prefix(srcTable)), Prefix(name)); - Execute(_commandInterpreter.CreateSql(command)); + await ExecuteAsync(_commandInterpreter.CreateSql(command)); } catch { @@ -281,16 +245,14 @@ public ISchemaBuilder DropForeignKey(string srcTable, string name) throw; } } - - return this; } - public ISchemaBuilder CreateSchema(string schema) + public async Task CreateSchemaAsync(string schema) { try { var createSchema = new CreateSchemaCommand(schema); - Execute(_commandInterpreter.CreateSql(createSchema)); + await ExecuteAsync(_commandInterpreter.CreateSql(createSchema)); } catch { @@ -299,8 +261,88 @@ public ISchemaBuilder CreateSchema(string schema) throw; } } + } + + public ISchemaBuilder AlterTable(string name, Action table) + { + AlterTableAsync(name, table).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + public ISchemaBuilder AlterIndexTable(Type indexType, Action table, string collection) + { + AlterIndexTableAsync(indexType, table, collection).ConfigureAwait(false).GetAwaiter().GetResult(); return this; } + + public ISchemaBuilder CreateForeignKey(string name, string srcTable, string[] srcColumns, string destTable, string[] destColumns) + { + CreateForeignKeyAsync(name, srcTable, srcColumns, destTable, destColumns).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + + public ISchemaBuilder CreateMapIndexTable(Type indexType, Action table, string collection) + { + CreateMapIndexTableAsync(indexType, table, collection).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + + public ISchemaBuilder CreateReduceIndexTable(Type indexType, Action table, string collection) + { + CreateReduceIndexTableAsync(indexType, table, collection).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + + public ISchemaBuilder CreateTable(string name, Action table) + { + CreateTableAsync(name, table).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + + public ISchemaBuilder DropForeignKey(string srcTable, string name) + { + DropForeignKeyAsync(srcTable, name).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + + public ISchemaBuilder DropMapIndexTable(Type indexType, string collection = null) + { + DropMapIndexTableAsync(indexType, collection).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + + public ISchemaBuilder DropReduceIndexTable(Type indexType, string collection = null) + { + DropReduceIndexTableAsync(indexType, collection).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + + public ISchemaBuilder DropTable(string name) + { + DropTableAsync(name).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + + public ISchemaBuilder CreateSchema(string schema) + { + CreateSchemaAsync(schema).ConfigureAwait(false).GetAwaiter().GetResult(); + return this; + } + + private async Task ExecuteAsync(IEnumerable statements) + { + foreach (var statement in statements) + { + if (string.IsNullOrEmpty(statement)) + { + continue; + } + + _logger.LogTrace(statement); + await Connection.ExecuteAsync(statement, null, Transaction); + } + } + private string Prefix(string table) + => TablePrefix + table; } } diff --git a/src/YesSql.Core/Store.cs b/src/YesSql.Core/Store.cs index cb13ac0c..0239585a 100644 --- a/src/YesSql.Core/Store.cs +++ b/src/YesSql.Core/Store.cs @@ -95,10 +95,11 @@ public async Task InitializeAsync() { await connection.OpenAsync(); - await using var transaction = connection.BeginTransaction(Configuration.IsolationLevel); + await using var transaction = await connection.BeginTransactionAsync(Configuration.IsolationLevel); + var builder = new SchemaBuilder(Configuration, transaction); - builder.CreateSchema(Configuration.Schema); + await builder.CreateSchemaAsync(Configuration.Schema); await transaction.CommitAsync(); } @@ -108,98 +109,91 @@ public async Task InitializeAsync() await Configuration.IdGenerator.InitializeAsync(this); // Pre-initialize the default collection - await InitializeCollectionAsync(""); + await InitializeCollectionAsync(string.Empty); } public async Task InitializeCollectionAsync(string collection) { var documentTable = Configuration.TableNameConvention.GetDocumentTable(collection); - await using (var connection = Configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); + await using var connection = Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - try - { - var selectCommand = connection.CreateCommand(); + try + { + var selectCommand = connection.CreateCommand(); - var selectBuilder = Dialect.CreateBuilder(Configuration.TablePrefix); - selectBuilder.Select(); - selectBuilder.AddSelector("*"); - selectBuilder.Table(documentTable, null, Configuration.Schema); - selectBuilder.Take("1"); + var selectBuilder = Dialect.CreateBuilder(Configuration.TablePrefix); + selectBuilder.Select(); + selectBuilder.AddSelector("*"); + selectBuilder.Table(documentTable, null, Configuration.Schema); + selectBuilder.Take("1"); - selectCommand.CommandText = selectBuilder.ToSqlString(); + selectCommand.CommandText = selectBuilder.ToSqlString(); - Configuration.Logger.LogTrace(selectCommand.CommandText); + Configuration.Logger.LogTrace(selectCommand.CommandText); - using (var result = await selectCommand.ExecuteReaderAsync()) + using var result = await selectCommand.ExecuteReaderAsync(); + if (result != null) + { + try { - if (result != null) - { - try - { - // Check if the Version column exists - result.GetOrdinal(nameof(Document.Version)); - } - catch - { - await result.CloseAsync(); - using var migrationTransaction = connection.BeginTransaction(); - var migrationBuilder = new SchemaBuilder(Configuration, migrationTransaction); - - try - { - migrationBuilder - .AlterTable(documentTable, table => table - .AddColumn(nameof(Document.Version), column => column.WithDefault(0)) - ); - - await migrationTransaction.CommitAsync(); - } - catch - { - - // Another thread must have altered it - } - } - return; - } + // Check if the Version column exists + result.GetOrdinal(nameof(Document.Version)); } - } - catch - { - await using (var transaction = connection.BeginTransaction()) + catch { - var builder = new SchemaBuilder(Configuration, transaction); + await result.CloseAsync(); + await using var migrationTransaction = await connection.BeginTransactionAsync(); + var migrationBuilder = new SchemaBuilder(Configuration, migrationTransaction); try { - // The table doesn't exist, create it - builder - .CreateTable(documentTable, table => table - .Column(Configuration.IdentityColumnSize, nameof(Document.Id), column => column.PrimaryKey().NotNull()) - .Column(nameof(Document.Type), column => column.NotNull()) - .Column(nameof(Document.Content), column => column.Unlimited()) - .Column(nameof(Document.Version), column => column.NotNull().WithDefault(0)) - ) - .AlterTable(documentTable, table => table - .CreateIndex("IX_" + documentTable + "_Type", "Type") - ); - - await transaction.CommitAsync(); + await migrationBuilder.AlterTableAsync(documentTable, table => table + .AddColumn(nameof(Document.Version), column => column.WithDefault(0)) + ); + + await migrationTransaction.CommitAsync(); } catch { - // Another thread must have created it + // Another thread must have altered it + await migrationTransaction.RollbackAsync(); } } + return; } - finally + } + catch + { + await using var transaction = await connection.BeginTransactionAsync(); + var builder = new SchemaBuilder(Configuration, transaction); + + try { - await Configuration.IdGenerator.InitializeCollectionAsync(Configuration, collection); + // The table doesn't exist, create it + await builder.CreateTableAsync(documentTable, table => table + .Column(Configuration.IdentityColumnSize, nameof(Document.Id), column => column.PrimaryKey().NotNull()) + .Column(nameof(Document.Type), column => column.NotNull()) + .Column(nameof(Document.Content), column => column.Unlimited()) + .Column(nameof(Document.Version), column => column.NotNull().WithDefault(0)) + ); + + await builder.AlterTableAsync(documentTable, table => table + .CreateIndex("IX_" + documentTable + "_Type", "Type") + ); + + await transaction.CommitAsync(); + } + catch + { + // Another thread must have created it } } + finally + { + await Configuration.IdGenerator.InitializeCollectionAsync(Configuration, collection); + } } private void ValidateConfiguration() @@ -211,24 +205,17 @@ private void ValidateConfiguration() } public ISession CreateSession() - { - return new Session(this); - } + => new Session(this); public void Dispose() { } public IAccessor GetIdAccessor(Type tContainer) - { - return IdAccessors.GetOrAdd(tContainer, Configuration.IdentifierAccessorFactory.CreateAccessor); - } + => IdAccessors.GetOrAdd(tContainer, Configuration.IdentifierAccessorFactory.CreateAccessor); public IAccessor GetVersionAccessor(Type tContainer) - { - return VersionAccessors.GetOrAdd(tContainer, Configuration.VersionAccessorFactory.CreateAccessor); - - } + => VersionAccessors.GetOrAdd(tContainer, Configuration.VersionAccessorFactory.CreateAccessor); /// /// Returns the available indexers for a specified type @@ -272,10 +259,12 @@ private static Func MakeDescriptorActivator(Type type) return Expression.Lambda>(Expression.New(contextType)).Compile(); } + [Obsolete($"Instead, utilize the {nameof(GetNextIdAsync)} method. This current method is slated for removal in upcoming releases.")] public long GetNextId(string collection) - { - return Configuration.IdGenerator.GetNextId(collection); - } + => GetNextIdAsync(collection).ConfigureAwait(false).GetAwaiter().GetResult(); + + public Task GetNextIdAsync(string collection) + => Configuration.IdGenerator.GetNextIdAsync(collection); public IStore RegisterIndexes(IEnumerable indexProviders, string collection = null) { diff --git a/test/YesSql.Tests/CoreTests.cs b/test/YesSql.Tests/CoreTests.cs index 1ed1c7df..2e19b55d 100644 --- a/test/YesSql.Tests/CoreTests.cs +++ b/test/YesSql.Tests/CoreTests.cs @@ -46,13 +46,13 @@ public async Task InitializeAsync() { _configuration = CreateConfiguration(); - CleanDatabase(_configuration, false); + await CleanDatabaseAsync(_configuration, false); _store = await StoreFactory.CreateAndInitializeAsync(_configuration); await _store.InitializeCollectionAsync("Col1"); _store.TypeNames[typeof(Person)] = "People"; - CreateTables(_configuration); + await CreateTablesAsync(_configuration); } else { @@ -62,13 +62,11 @@ public async Task InitializeAsync() } // Clear the tables for each new test - ClearTables(_configuration); + await ClearTablesAsync(_configuration); } public virtual Task DisposeAsync() - { - return Task.CompletedTask; - } + => Task.CompletedTask; protected void EnableLogging() { @@ -77,52 +75,52 @@ protected void EnableLogging() } //[DebuggerNonUserCode] - protected virtual void CleanDatabase(IConfiguration configuration, bool throwOnError) + protected virtual async Task CleanDatabaseAsync(IConfiguration configuration, bool throwOnError) { // Remove existing tables - using var connection = configuration.ConnectionFactory.CreateConnection(); - connection.Open(); + await using var connection = configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - using var transaction = connection.BeginTransaction(configuration.IsolationLevel); + await using var transaction = await connection.BeginTransactionAsync(configuration.IsolationLevel); var builder = new SchemaBuilder(configuration, transaction, throwOnError); - builder.DropReduceIndexTable(); - builder.DropReduceIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); + await builder.DropReduceIndexTableAsync(); + await builder.DropReduceIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropMapIndexTable(); - builder.DropReduceIndexTable(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropMapIndexTableAsync(); + await builder.DropReduceIndexTableAsync(); - builder.DropMapIndexTable("Col1"); - builder.DropMapIndexTable("Col1"); - builder.DropMapIndexTable("Col1"); - builder.DropReduceIndexTable("Col1"); - builder.DropReduceIndexTable("LongCollection"); + await builder.DropMapIndexTableAsync("Col1"); + await builder.DropMapIndexTableAsync("Col1"); + await builder.DropMapIndexTableAsync("Col1"); + await builder.DropReduceIndexTableAsync("Col1"); + await builder.DropReduceIndexTableAsync("LongCollection"); - builder.DropTable(configuration.TableNameConvention.GetDocumentTable("Col1")); - builder.DropTable(configuration.TableNameConvention.GetDocumentTable("")); + await builder.DropTableAsync(configuration.TableNameConvention.GetDocumentTable("Col1")); + await builder.DropTableAsync(configuration.TableNameConvention.GetDocumentTable("")); - builder.DropTable(DbBlockIdGenerator.TableName); + await builder.DropTableAsync(DbBlockIdGenerator.TableName); - OnCleanDatabase(builder, transaction); + await OnCleanDatabaseAsync(builder, transaction); - transaction.Commit(); + await transaction.CommitAsync(); } - protected virtual void ClearTables(IConfiguration configuration) + protected virtual async Task ClearTablesAsync(IConfiguration configuration) { - void DeleteReduceIndexTable(DbConnection connection, string collection = "") + async Task DeleteReduceIndexTableAsync(DbConnection connection, string collection = "") { var indexTable = configuration.TableNameConvention.GetIndexTable(typeof(IndexType), collection); var documentTable = configuration.TableNameConvention.GetDocumentTable(collection); @@ -131,238 +129,232 @@ void DeleteReduceIndexTable(DbConnection connection, string collectio try { - connection.Execute($"DELETE FROM {configuration.SqlDialect.QuoteForTableName(TablePrefix + bridgeTableName, configuration.Schema)}"); - connection.Execute($"DELETE FROM {configuration.SqlDialect.QuoteForTableName(TablePrefix + indexTable, configuration.Schema)}"); + await connection.ExecuteAsync($"DELETE FROM {configuration.SqlDialect.QuoteForTableName(TablePrefix + bridgeTableName, configuration.Schema)}"); + await connection.ExecuteAsync($"DELETE FROM {configuration.SqlDialect.QuoteForTableName(TablePrefix + indexTable, configuration.Schema)}"); } catch { } } - void DeleteMapIndexTable(DbConnection connection, string collection = "") + async Task DeleteMapIndexTableAsync(DbConnection connection, string collection = "") { var indexName = typeof(IndexType).Name; var indexTable = configuration.TableNameConvention.GetIndexTable(typeof(IndexType), collection); try { - connection.Execute($"DELETE FROM {configuration.SqlDialect.QuoteForTableName(TablePrefix + indexTable, configuration.Schema)}"); + await connection.ExecuteAsync($"DELETE FROM {configuration.SqlDialect.QuoteForTableName(TablePrefix + indexTable, configuration.Schema)}"); } catch { } } - void DeleteDocumentTable(DbConnection connection, string collection = "") + async Task DeleteDocumentTableAsync(DbConnection connection, string collection = "") { var tableName = configuration.TableNameConvention.GetDocumentTable(collection); try { - connection.Execute($"DELETE FROM {configuration.SqlDialect.QuoteForTableName(TablePrefix + tableName, configuration.Schema)}"); + await connection.ExecuteAsync($"DELETE FROM {configuration.SqlDialect.QuoteForTableName(TablePrefix + tableName, configuration.Schema)}"); } catch { } } // Remove existing tables - using (var connection = configuration.ConnectionFactory.CreateConnection()) - { - connection.Open(); - - DeleteReduceIndexTable(connection); - DeleteReduceIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteMapIndexTable(connection); - DeleteReduceIndexTable(connection); - - DeleteMapIndexTable(connection, "Col1"); - DeleteMapIndexTable(connection, "Col1"); - DeleteMapIndexTable(connection, "Col1"); - DeleteReduceIndexTable(connection, "Col1"); - - DeleteDocumentTable(connection, "Col1"); - DeleteDocumentTable(connection, ""); + await using (var connection = configuration.ConnectionFactory.CreateConnection()) + { + await connection.OpenAsync(); - //connection.Execute($"DELETE FROM {TablePrefix}{DbBlockIdGenerator.TableName}"); + await DeleteReduceIndexTableAsync(connection); + await DeleteReduceIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteMapIndexTableAsync(connection); + await DeleteReduceIndexTableAsync(connection); + + await DeleteMapIndexTableAsync(connection, "Col1"); + await DeleteMapIndexTableAsync(connection, "Col1"); + await DeleteMapIndexTableAsync(connection, "Col1"); + await DeleteReduceIndexTableAsync(connection, "Col1"); + + await DeleteDocumentTableAsync(connection, "Col1"); + await DeleteDocumentTableAsync(connection, ""); - OnClearTables(connection); + //connection.Execute($"DELETE FROM {TablePrefix}{DbBlockIdGenerator.TableName}"); + await OnClearTablesAsync(connection); } } - protected virtual void OnCleanDatabase(SchemaBuilder builder, DbTransaction transaction) - { + protected virtual Task OnCleanDatabaseAsync(SchemaBuilder builder, DbTransaction transaction) + => Task.CompletedTask; - } + protected virtual Task OnClearTablesAsync(DbConnection connection) + => Task.CompletedTask; - protected virtual void OnClearTables(DbConnection connection) + public async Task CreateTablesAsync(IConfiguration configuration) { + await using var connection = configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - } - - public void CreateTables(IConfiguration configuration) - { - using var connection = configuration.ConnectionFactory.CreateConnection(); - connection.Open(); - - using var transaction = connection.BeginTransaction(configuration.IsolationLevel); + await using var transaction = await connection.BeginTransactionAsync(configuration.IsolationLevel); var builder = new SchemaBuilder(configuration, transaction); - builder.CreateReduceIndexTable(column => column - .Column(nameof(ArticlesByDay.Count)) - .Column(nameof(ArticlesByDay.DayOfYear)) - ); - builder.CreateReduceIndexTable(column => column - .Column(nameof(AttachmentByDay.Count)) - .Column(nameof(AttachmentByDay.Date)) - ); + await builder.CreateReduceIndexTableAsync(column => column + .Column(nameof(ArticlesByDay.Count)) + .Column(nameof(ArticlesByDay.DayOfYear)) + ); - builder.CreateReduceIndexTable(column => column - .Column(nameof(UserByRoleNameIndex.Count)) - .Column(nameof(UserByRoleNameIndex.RoleName)) - ); + await builder.CreateReduceIndexTableAsync(column => column + .Column(nameof(AttachmentByDay.Count)) + .Column(nameof(AttachmentByDay.Date)) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(ArticleByPublishedDate.PublishedDateTime)) - .Column(nameof(ArticleByPublishedDate.Title)) - ); + await builder.CreateReduceIndexTableAsync(column => column + .Column(nameof(UserByRoleNameIndex.Count)) + .Column(nameof(UserByRoleNameIndex.RoleName)) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(PersonByName.SomeName)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(ArticleByPublishedDate.PublishedDateTime)) + .Column(nameof(ArticleByPublishedDate.Title)) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(CarIndex.Name)) - .Column(nameof(CarIndex.Category)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PersonByName.SomeName)) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(PersonByNameCol.Name)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(CarIndex.Name)) + .Column(nameof(CarIndex.Category)) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(PersonIdentity.Identity)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PersonByNameCol.Name)) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(PersonByAge.Age)) - .Column(nameof(PersonByAge.Adult)) - .Column(nameof(PersonByAge.Name)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PersonIdentity.Identity)) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(ShapeIndex.Name)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PersonByAge.Age)) + .Column(nameof(PersonByAge.Adult)) + .Column(nameof(PersonByAge.Name)) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(PersonByAge.Age), c => c.Nullable()) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(ShapeIndex.Name)) + ); + + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PersonByAge.Age), c => c.Nullable()) + ); - builder.CreateMapIndexTable(column => { }); + await builder.CreateMapIndexTableAsync(column => { }); - builder.CreateMapIndexTable(column => column - .Column(nameof(EmailByAttachment.Date)) - .Column(nameof(EmailByAttachment.AttachmentName)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(EmailByAttachment.Date)) + .Column(nameof(EmailByAttachment.AttachmentName)) + ); - builder.CreateMapIndexTable(column => column + await builder.CreateMapIndexTableAsync(column => column .Column(nameof(PropertyIndex.Name), col => col.WithLength(767)) .Column(nameof(PropertyIndex.ForRent)) .Column(nameof(PropertyIndex.IsOccupied)) .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) ); - builder.CreateMapIndexTable(column => column - .Column(nameof(Binary.Content1), c => c.WithLength(255)) - .Column(nameof(Binary.Content2), c => c.WithLength(8000)) - .Column(nameof(Binary.Content3), c => c.WithLength(65535)) - .Column(nameof(Binary.Content4), c => c.WithLength(1)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(Binary.Content1), c => c.WithLength(255)) + .Column(nameof(Binary.Content2), c => c.WithLength(8000)) + .Column(nameof(Binary.Content3), c => c.WithLength(65535)) + .Column(nameof(Binary.Content4), c => c.WithLength(1)) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(TypesIndex.ValueBool)) - //.Column(nameof(TypesIndex.ValueChar)) - .Column(nameof(TypesIndex.ValueDateTime)) - .Column(nameof(TypesIndex.ValueDateTimeOffset)) - .Column(nameof(TypesIndex.ValueDecimal)) - .Column(nameof(TypesIndex.ValueDouble)) - .Column(nameof(TypesIndex.ValueFloat)) - .Column(nameof(TypesIndex.ValueGuid)) - .Column(nameof(TypesIndex.ValueInt)) - .Column(nameof(TypesIndex.ValueLong)) - //.Column(nameof(TypesIndex.ValueSByte)) - .Column(nameof(TypesIndex.ValueShort)) - .Column(nameof(TypesIndex.ValueTimeSpan)) - //.Column(nameof(TypesIndex.ValueUInt)) - //.Column(nameof(TypesIndex.ValueULong)) - //.Column(nameof(TypesIndex.ValueUShort)) - .Column(nameof(TypesIndex.NullableBool), c => c.Nullable()) - //.Column(nameof(TypesIndex.NullableChar), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableDateTime), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableDateTimeOffset), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableDecimal), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableDouble), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableFloat), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableGuid), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableInt), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableLong), c => c.Nullable()) - //.Column(nameof(TypesIndex.NullableSByte), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableShort), c => c.Nullable()) - .Column(nameof(TypesIndex.NullableTimeSpan), c => c.Nullable()) - //.Column(nameof(TypesIndex.NullableUInt), c => c.Nullable()) - //.Column(nameof(TypesIndex.NullableULong), c => c.Nullable()) - //.Column(nameof(TypesIndex.NullableUShort), c => c.Nullable()) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(TypesIndex.ValueBool)) + //.Column(nameof(TypesIndex.ValueChar)) + .Column(nameof(TypesIndex.ValueDateTime)) + .Column(nameof(TypesIndex.ValueDateTimeOffset)) + .Column(nameof(TypesIndex.ValueDecimal)) + .Column(nameof(TypesIndex.ValueDouble)) + .Column(nameof(TypesIndex.ValueFloat)) + .Column(nameof(TypesIndex.ValueGuid)) + .Column(nameof(TypesIndex.ValueInt)) + .Column(nameof(TypesIndex.ValueLong)) + //.Column(nameof(TypesIndex.ValueSByte)) + .Column(nameof(TypesIndex.ValueShort)) + .Column(nameof(TypesIndex.ValueTimeSpan)) + //.Column(nameof(TypesIndex.ValueUInt)) + //.Column(nameof(TypesIndex.ValueULong)) + //.Column(nameof(TypesIndex.ValueUShort)) + .Column(nameof(TypesIndex.NullableBool), c => c.Nullable()) + //.Column(nameof(TypesIndex.NullableChar), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableDateTime), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableDateTimeOffset), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableDecimal), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableDouble), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableFloat), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableGuid), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableInt), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableLong), c => c.Nullable()) + //.Column(nameof(TypesIndex.NullableSByte), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableShort), c => c.Nullable()) + .Column(nameof(TypesIndex.NullableTimeSpan), c => c.Nullable()) + //.Column(nameof(TypesIndex.NullableUInt), c => c.Nullable()) + //.Column(nameof(TypesIndex.NullableULong), c => c.Nullable()) + //.Column(nameof(TypesIndex.NullableUShort), c => c.Nullable()) + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(PersonByName.SomeName)), - "Col1" - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PersonByName.SomeName)), + "Col1" + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(PersonByNameCol.Name)), - "Col1" - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PersonByNameCol.Name)), + "Col1" + ); - builder.CreateMapIndexTable(column => column - .Column(nameof(PersonByBothNamesCol.Firstname)) - .Column(nameof(PersonByBothNamesCol.Lastname)), - "Col1" - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PersonByBothNamesCol.Firstname)) + .Column(nameof(PersonByBothNamesCol.Lastname)), + "Col1" + ); - builder.CreateReduceIndexTable(column => column - .Column(nameof(PersonsByNameCol.Name)) - .Column(nameof(PersonsByNameCol.Count)), - "Col1" - ); + await builder.CreateReduceIndexTableAsync(column => column + .Column(nameof(PersonsByNameCol.Name)) + .Column(nameof(PersonsByNameCol.Count)), + "Col1" + ); - transaction.Commit(); + await transaction.CommitAsync(); } [Fact] - public void ShouldCreateDatabase() + public async Task ShouldCreateDatabase() { - using (var session = _store.CreateSession()) - { - var doc = new Product(); - session.Save(doc); - } + await using var session = _store.CreateSession(); + var doc = new Product(); + await session.SaveAsync(doc); } [Fact] public async Task ShouldSaveCustomObject() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -370,12 +362,12 @@ public async Task ShouldSaveCustomObject() Lastname = "Gates" }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.Query().CountAsync()); } @@ -384,7 +376,7 @@ public async Task ShouldSaveCustomObject() [Fact] public async Task NotCallingCommitShouldCancelTransaction() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -392,10 +384,10 @@ public async Task NotCallingCommitShouldCancelTransaction() Lastname = "Gates" }; - session.Save(bill); + await session.SaveAsync(bill); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(0, await session.Query().CountAsync()); } @@ -404,7 +396,7 @@ public async Task NotCallingCommitShouldCancelTransaction() [Fact] public async Task ShouldCancelTransactionAfterFlush() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -412,7 +404,7 @@ public async Task ShouldCancelTransactionAfterFlush() Lastname = "Gates" }; - session.Save(bill); + await session.SaveAsync(bill); await session.FlushAsync(); @@ -422,19 +414,21 @@ public async Task ShouldCancelTransactionAfterFlush() Lastname = "Balmer" }; - session.Save(steve); + await session.SaveAsync(steve); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - Assert.Equal(0, await session.Query().CountAsync()); + var total = await session.Query().CountAsync(); + + Assert.Equal(0, total); } } [Fact] public async Task ShouldSaveSeveralObjects() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -448,13 +442,13 @@ public async Task ShouldSaveSeveralObjects() Lastname = "Balmer" }; - session.Save(bill); - session.Save(steve); + await session.SaveAsync(bill); + await session.SaveAsync(steve); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query().CountAsync()); } @@ -463,31 +457,29 @@ public async Task ShouldSaveSeveralObjects() [Fact] public async Task ShouldSaveAnonymousObject() { - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var bill = new { - var bill = new - { - Firstname = "Bill", - Lastname = "Gates" - }; + Firstname = "Bill", + Lastname = "Gates" + }; - var steve = new - { - Firstname = "Steve", - Lastname = "Balmer" - }; + var steve = new + { + Firstname = "Steve", + Lastname = "Balmer" + }; - session.Save(bill); - session.Save(steve); + await session.SaveAsync(bill); + await session.SaveAsync(steve); - await session.SaveChangesAsync(); - } + await session.SaveChangesAsync(); } [Fact] public async Task ShouldLoadAnonymousDocument() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new { @@ -500,11 +492,11 @@ public async Task ShouldLoadAnonymousDocument() } }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { dynamic person = await session.Query().Any().FirstOrDefaultAsync(); @@ -522,29 +514,27 @@ public async Task ShouldLoadAnonymousDocument() [Fact] public async Task ShouldQueryNonExistentResult() { - using (var session = _store.CreateSession()) - { - var person = await session.Query().FirstOrDefaultAsync(); - Assert.Null(person); - } + await using var session = _store.CreateSession(); + var person = await session.Query().FirstOrDefaultAsync(); + Assert.Null(person); } [Fact] public async Task ShouldUpdateNewDocument() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { Firstname = "Bill" }; - session.Save(bill); + await session.SaveAsync(bill); bill.Lastname = "Gates"; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.Query().CountAsync()); @@ -559,14 +549,14 @@ public async Task ShouldQueryIndexWithParameter() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { Firstname = "Bill" }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.QueryIndex().Where(d => d.QuoteForColumnName(nameof(PersonByName.SomeName)) + " = @Name").WithParameter("Name", "Bill").FirstOrDefaultAsync(); @@ -580,15 +570,15 @@ public async Task ShouldMapEnums() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Car { Name = "Truck", Category = Categories.Truck }); - session.Save(new Car { Name = "Van", Category = Categories.Van }); + await session.SaveAsync(new Car { Name = "Truck", Category = Categories.Truck }); + await session.SaveAsync(new Car { Name = "Van", Category = Categories.Van }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal("Van", (await session.QueryIndex(x => x.Category == Categories.Van).FirstOrDefaultAsync()).Name); Assert.Equal("Truck", (await session.QueryIndex(x => x.Category == Categories.Truck).FirstOrDefaultAsync()).Name); @@ -603,16 +593,16 @@ public async Task ShouldApplyIndexFilter() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Person { Firstname = "Alex" }); - session.Save(new Person { Firstname = "Bill" }); - session.Save(new Person { Firstname = "assan" }); + await session.SaveAsync(new Person { Firstname = "Alex" }); + await session.SaveAsync(new Person { Firstname = "Bill" }); + await session.SaveAsync(new Person { Firstname = "assan" }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.QueryIndex().CountAsync()); } @@ -623,15 +613,15 @@ public async Task ShouldMapAsyncIndex() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { Firstname = "Bill" }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.QueryIndex().FirstOrDefaultAsync(); @@ -643,27 +633,26 @@ public async Task ShouldMapAsyncIndex() [Fact] public async Task ShouldResolveScopedIndexProviders() { - - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { session.RegisterIndexes(new ScopedPersonAsyncIndexProvider(1)); - session.Save(new Person { Firstname = "Bill" }); + await session.SaveAsync(new Person { Firstname = "Bill" }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { session.RegisterIndexes(new ScopedPersonAsyncIndexProvider(2)); - session.Save(new Person { Firstname = "Bill" }); - session.Save(new Person { Firstname = "Steve" }); + await session.SaveAsync(new Person { Firstname = "Bill" }); + await session.SaveAsync(new Person { Firstname = "Steve" }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var count = await session.QueryIndex().CountAsync(); var bill1 = await session.QueryIndex(x => x.SomeName == "Bill1").FirstOrDefaultAsync(); @@ -682,16 +671,16 @@ public async Task ShouldQueryNullValues() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Person { Firstname = null }); - session.Save(new Person { Firstname = "a" }); - session.Save(new Person { Firstname = "b" }); + await session.SaveAsync(new Person { Firstname = null }); + await session.SaveAsync(new Person { Firstname = "a" }); + await session.SaveAsync(new Person { Firstname = "b" }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex(x => x.SomeName == null).CountAsync()); Assert.Equal(2, await session.QueryIndex(x => x.SomeName != null).CountAsync()); @@ -699,7 +688,6 @@ public async Task ShouldQueryNullValues() Assert.Equal(2, await session.QueryIndex(x => null != x.SomeName).CountAsync()); Assert.Equal(3, await session.QueryIndex(x => null == null).CountAsync()); Assert.Equal(0, await session.QueryIndex(x => null != null).CountAsync()); - } } @@ -708,18 +696,18 @@ public async Task ShouldQueryNullVariables() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Person { Firstname = null }); - session.Save(new Person { Firstname = "a" }); - session.Save(new Person { Firstname = "b" }); + await session.SaveAsync(new Person { Firstname = null }); + await session.SaveAsync(new Person { Firstname = "a" }); + await session.SaveAsync(new Person { Firstname = "b" }); await session.SaveChangesAsync(); } string nullVariable = null; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex(x => x.SomeName == nullVariable).CountAsync()); Assert.Equal(2, await session.QueryIndex(x => x.SomeName != nullVariable).CountAsync()); @@ -733,17 +721,17 @@ public async Task ShouldCompareWithConstants() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Article { Title = TestConstants.Strings.SomeString, PublishedUtc = new DateTime(2011, 11, 1) }); - session.Save(new Article { Title = TestConstants.Strings.SomeOtherString, PublishedUtc = new DateTime(2011, 11, 1) }); - session.Save(new Article { Title = TestConstants.Strings.SomeString, PublishedUtc = new DateTime(2011, 11, 2) }); - session.Save(new Article { Title = TestConstants.Strings.SomeOtherString, PublishedUtc = new DateTime(2011, 11, 2) }); + await session.SaveAsync(new Article { Title = TestConstants.Strings.SomeString, PublishedUtc = new DateTime(2011, 11, 1) }); + await session.SaveAsync(new Article { Title = TestConstants.Strings.SomeOtherString, PublishedUtc = new DateTime(2011, 11, 1) }); + await session.SaveAsync(new Article { Title = TestConstants.Strings.SomeString, PublishedUtc = new DateTime(2011, 11, 2) }); + await session.SaveAsync(new Article { Title = TestConstants.Strings.SomeOtherString, PublishedUtc = new DateTime(2011, 11, 2) }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query(x => x.Title == TestConstants.Strings.SomeString).CountAsync()); Assert.Equal(2, await session.Query(x => x.Title != TestConstants.Strings.SomeString).CountAsync()); @@ -757,20 +745,20 @@ public async Task ShouldQueryDocumentWithParameter() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { Firstname = "Bill" }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().Where(d => d.QuoteForColumnName(nameof(PersonByName.SomeName)) + " = @Name").WithParameter("Name", "Bill").FirstOrDefaultAsync(); Assert.NotNull(person); - Assert.Equal("Bill", (string)person.Firstname); + Assert.Equal("Bill", person.Firstname); } } @@ -779,17 +767,17 @@ public async Task ShouldQuoteString() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { Firstname = "Bill" }; var steve = new Person { Firstname = "Steve" }; - session.Save(bill); - session.Save(steve); + await session.SaveAsync(bill); + await session.SaveAsync(steve); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var connection = await session.CreateConnectionAsync(); var dialect = _store.Configuration.SqlDialect; @@ -807,7 +795,7 @@ public async Task ShouldSerializeComplexObject() { long productId; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var product = new Product { @@ -815,11 +803,11 @@ public async Task ShouldSerializeComplexObject() Name = "Milk", }; - session.Save(product); + await session.SaveAsync(product); await session.FlushAsync(); productId = product.Id; - session.Save(new Order + await session.SaveAsync(new Order { Customer = "customers/microsoft", OrderLines = @@ -835,7 +823,7 @@ public async Task ShouldSerializeComplexObject() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var prod = await session.GetAsync(productId); Assert.NotNull(prod); @@ -846,7 +834,7 @@ public async Task ShouldSerializeComplexObject() [Fact] public async Task ShouldAssignIdWhenSaved() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -855,7 +843,7 @@ public async Task ShouldAssignIdWhenSaved() }; Assert.Equal(0, bill.Id); - session.Save(bill); + await session.SaveAsync(bill); Assert.NotEqual(0, bill.Id); await session.SaveChangesAsync(); @@ -865,7 +853,7 @@ public async Task ShouldAssignIdWhenSaved() [Fact] public async Task ShouldAutoFlushOnGet() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -873,7 +861,7 @@ public async Task ShouldAutoFlushOnGet() Lastname = "Gates" }; - session.Save(bill); + await session.SaveAsync(bill); var newBill = await session.GetAsync(bill.Id); Assert.Same(newBill, bill); @@ -885,7 +873,7 @@ public async Task ShouldAutoFlushOnGet() [Fact] public async Task ShouldKeepTrackedOnAutoFlush() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -893,7 +881,7 @@ public async Task ShouldKeepTrackedOnAutoFlush() Lastname = "Gates" }; - session.Save(bill); + await session.SaveAsync(bill); var newBill = await session.GetAsync(bill.Id); Assert.Same(newBill, bill); @@ -905,7 +893,7 @@ public async Task ShouldKeepTrackedOnAutoFlush() [Fact] public async Task NoSavingChangesShouldRollbackAutoFlush() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -913,13 +901,13 @@ public async Task NoSavingChangesShouldRollbackAutoFlush() Lastname = "Gates" }; - session.Save(bill); + await session.SaveAsync(bill); var newBill = await session.GetAsync(bill.Id); Assert.Same(newBill, bill); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(0, await session.Query().CountAsync()); } @@ -928,36 +916,34 @@ public async Task NoSavingChangesShouldRollbackAutoFlush() [Fact] public async Task ShouldKeepIdentityMapOnCommitAsync() { - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var bill = new Person { - var bill = new Person - { - Firstname = "Bill", - Lastname = "Gates" - }; + Firstname = "Bill", + Lastname = "Gates" + }; - session.Save(bill); - var newBill = await session.GetAsync(bill.Id); + await session.SaveAsync(bill); + var newBill = await session.GetAsync(bill.Id); - Assert.Equal(bill, newBill); + Assert.Equal(bill, newBill); - await session.SaveChangesAsync(); + await session.SaveChangesAsync(); - newBill = await session.GetAsync(bill.Id); + newBill = await session.GetAsync(bill.Id); - Assert.Equal(bill, newBill); - } + Assert.Equal(bill, newBill); } [Fact] - public async Task ShouldUpdateAutoflushedIndex() + public async Task ShouldUpdateAutoFlushedIndex() { // When auto-flush is called on an entity // its indexes should be updated on the actual commit _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -965,26 +951,26 @@ public async Task ShouldUpdateAutoflushedIndex() Lastname = "Gates" }; - session.Save(bill); + await session.SaveAsync(bill); // This query triggers an auto-flush Assert.Equal(1, await session.Query().CountAsync()); bill.Firstname = "Bill2"; - session.Save(bill); + await session.SaveAsync(bill); Assert.Equal(1, await session.Query().Where(x => x.SomeName == "Bill2").CountAsync()); bill.Firstname = "Bill3"; - session.Save(bill); + await session.SaveAsync(bill); Assert.Equal(1, await session.QueryIndex().CountAsync()); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.QueryIndex().Where(x => x.SomeName == "Bill3").CountAsync()); @@ -996,7 +982,7 @@ public async Task ShouldQueryBoolean() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1012,13 +998,13 @@ public async Task ShouldQueryBoolean() Age = 12 }; - session.Save(bill); - session.Save(elon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex(x => x.Adult && x.Adult).CountAsync()); Assert.Equal(1, await session.QueryIndex(x => x.Adult).CountAsync()); @@ -1049,7 +1035,7 @@ public async Task ShouldQueryWithCompiledQueries() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1072,14 +1058,14 @@ public async Task ShouldQueryWithCompiledQueries() Age = 12 }; - session.Save(bill); - session.Save(elon); - session.Save(eilon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); + await session.SaveAsync(eilon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.ExecuteQuery(new PersonByNameOrAgeQuery(50, null)).CountAsync()); Assert.Equal(2, await session.ExecuteQuery(new PersonByNameOrAgeQuery(12, null)).CountAsync()); @@ -1103,7 +1089,7 @@ public async Task ShouldOrderCompiledQueries() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1119,13 +1105,13 @@ public async Task ShouldOrderCompiledQueries() Age = 12 }; - session.Save(bill); - session.Save(elon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = await session.ExecuteQuery(new PersonOrderedAscQuery()).ListAsync(); @@ -1133,7 +1119,7 @@ public async Task ShouldOrderCompiledQueries() Assert.Equal("Bill", results.ElementAt(1).Firstname); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = await session.ExecuteQuery(new PersonOrderedDescQuery()).ListAsync(); @@ -1147,11 +1133,11 @@ public async Task ShouldPageCompiledQueries() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < 10; i++) { - session.Save(new Person + await session.SaveAsync(new Person { Firstname = "Bill", Lastname = "Gates", @@ -1162,7 +1148,7 @@ public async Task ShouldPageCompiledQueries() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = await session.ExecuteQuery(new PersonPagedQuery()).ListAsync(); @@ -1175,7 +1161,7 @@ public virtual async Task ShouldRunCompiledQueriesConcurrently() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1189,8 +1175,8 @@ public virtual async Task ShouldRunCompiledQueriesConcurrently() Lastname = "Balmer" }; - session.Save(bill); - session.Save(steve); + await session.SaveAsync(bill); + await session.SaveAsync(steve); await session.SaveChangesAsync(); } @@ -1205,7 +1191,7 @@ public virtual async Task ShouldRunCompiledQueriesConcurrently() { while (!stopping && Interlocked.Add(ref counter, 1) < MaxTransactions) { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.ExecuteQuery(new PersonByNameOrAgeQuery(0, "Bill")).CountAsync()); } @@ -1226,7 +1212,7 @@ public async Task ShouldNotLeakPagingBetweenQueries() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1249,14 +1235,14 @@ public async Task ShouldNotLeakPagingBetweenQueries() Age = 12 }; - session.Save(bill); - session.Save(elon); - session.Save(eilon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); + await session.SaveAsync(eilon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(12, (await session.ExecuteQuery(new PersonByNameOrAgeQuery(12, null)).FirstOrDefaultAsync()).Age); Assert.Equal(2, (await session.ExecuteQuery(new PersonByNameOrAgeQuery(12, null)).ListAsync()).Count()); @@ -1268,7 +1254,7 @@ public async Task ShouldSupportAsyncEnumerable() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1291,14 +1277,14 @@ public async Task ShouldSupportAsyncEnumerable() Age = 12 }; - session.Save(bill); - session.Save(elon); - session.Save(eilon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); + await session.SaveAsync(eilon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = new List(); @@ -1317,7 +1303,7 @@ public async Task ShouldQueryInnerSelect() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1333,13 +1319,13 @@ public async Task ShouldQueryInnerSelect() Age = 12 }; - session.Save(bill); - session.Save(elon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.Query().Where(x => x.Name.IsIn(y => y.SomeName, y => y.SomeName.StartsWith("B") || y.SomeName.StartsWith("C"))).CountAsync()); Assert.Equal(2, await session.Query().Where(x => x.Name.IsIn(y => y.SomeName, y => y.SomeName.StartsWith("B") || y.SomeName.Contains("lo"))).CountAsync()); @@ -1355,7 +1341,7 @@ public async Task ShouldQueryInnerSelectWithNoPredicates() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1371,13 +1357,13 @@ public async Task ShouldQueryInnerSelectWithNoPredicates() Age = 12 }; - session.Save(bill); - session.Save(elon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query().Where(x => x.Name.IsInAny(y => y.SomeName)).CountAsync()); Assert.Equal(0, await session.Query().Where(x => x.Name.IsNotInAny(y => y.SomeName)).CountAsync()); @@ -1390,7 +1376,7 @@ public async Task ShouldQueryInnerSelectWithUnaryPredicate() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1406,13 +1392,13 @@ public async Task ShouldQueryInnerSelectWithUnaryPredicate() Age = 12 }; - session.Save(bill); - session.Save(elon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query().Where(x => x.Name.IsIn(y => y.SomeName, y => true)).CountAsync()); Assert.Equal(0, await session.Query().Where(x => x.Name.IsNotIn(y => y.SomeName, y => true)).CountAsync()); @@ -1425,7 +1411,7 @@ public async Task ShouldConcatenateMembers() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1441,13 +1427,13 @@ public async Task ShouldConcatenateMembers() Age = 12 }; - session.Save(bill); - session.Save(elon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.Query().Where(x => x.Name + x.Name == "BillBill").CountAsync()); Assert.Equal(1, await session.Query().Where(x => x.Name + " " + x.Name == "Bill Bill").CountAsync()); @@ -1466,7 +1452,7 @@ public async Task ShouldQueryWithLike() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1482,13 +1468,13 @@ public async Task ShouldQueryWithLike() Age = 12 }; - session.Save(bill); - session.Save(elon); + await session.SaveAsync(bill); + await session.SaveAsync(elon); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query().Where(x => x.Name.IsLike("%l%")).CountAsync()); Assert.Equal(1, await session.Query().Where(x => x.Name.IsNotLike("%B%")).CountAsync()); @@ -1506,7 +1492,7 @@ public virtual async Task ShouldAppendIndexOnUpdate() _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1514,21 +1500,21 @@ public virtual async Task ShouldAppendIndexOnUpdate() Lastname = "Gates" }; - session.Save(bill); + await session.SaveAsync(bill); var p1 = await session.QueryIndex().FirstOrDefaultAsync(); var firstId = p1.Id; bill.Firstname = "Bill2"; - session.Save(bill); + await session.SaveAsync(bill); var p2 = await session.QueryIndex().FirstOrDefaultAsync(); Assert.Equal(firstId + 1, p2.Id); bill.Firstname = "Bill3"; - session.Save(bill); + await session.SaveAsync(bill); var p3 = await session.QueryIndex().FirstOrDefaultAsync(); @@ -1537,7 +1523,7 @@ public virtual async Task ShouldAppendIndexOnUpdate() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.QueryIndex().Where(x => x.SomeName == "Bill3").CountAsync()); @@ -1568,8 +1554,8 @@ public async Task ShouldCreateSeveralMapIndexPerDocument() Lastname = "Guthrie" }; - session.Save(hanselman); - session.Save(guthrie); + await session.SaveAsync(hanselman); + await session.SaveAsync(guthrie); await session.SaveChangesAsync(); } @@ -1591,7 +1577,7 @@ public async Task ShouldQueryMultipleIndexes() _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var hanselman = new Person { @@ -1605,13 +1591,13 @@ public async Task ShouldQueryMultipleIndexes() Lastname = "Guthrie" }; - session.Save(hanselman); - session.Save(guthrie); + await session.SaveAsync(hanselman); + await session.SaveAsync(guthrie); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query() .Any( @@ -1629,7 +1615,7 @@ public async Task ShouldScopeMultipleIndexQueries() _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var hanselman = new Person { @@ -1649,14 +1635,14 @@ public async Task ShouldScopeMultipleIndexQueries() Lastname = "Kristensen" }; - session.Save(hanselman); - session.Save(guthrie); - session.Save(mads); + await session.SaveAsync(hanselman); + await session.SaveAsync(guthrie); + await session.SaveAsync(mads); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query() .Any( @@ -1678,7 +1664,7 @@ public async Task ShouldScopeNestedMultipleIndexQueries() _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var hanselman = new Person { @@ -1698,14 +1684,14 @@ public async Task ShouldScopeNestedMultipleIndexQueries() Lastname = "Kristensen" }; - session.Save(hanselman); - session.Save(guthrie); - session.Save(mads); + await session.SaveAsync(hanselman); + await session.SaveAsync(guthrie); + await session.SaveAsync(mads); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query() .All( @@ -1729,7 +1715,7 @@ public async Task ShouldDeletePreviousIndexes() _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var guthrie = new Person { @@ -1737,39 +1723,39 @@ public async Task ShouldDeletePreviousIndexes() Lastname = "Guthrie" }; - session.Save(guthrie); + await session.SaveAsync(guthrie); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.QueryIndex().CountAsync()); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var guthrie = await session.Query(x => x.Identity == "Scott").FirstOrDefaultAsync(); guthrie.Lastname = "Gu"; - session.Save(guthrie); + await session.SaveAsync(guthrie); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.QueryIndex().Where(x => x.Identity == "Scott").CountAsync()); Assert.Equal(1, await session.QueryIndex().Where(x => x.Identity == "Gu").CountAsync()); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var guthrie = await session.Query(x => x.Identity == "Scott").FirstOrDefaultAsync(); guthrie.Anonymous = true; - session.Save(guthrie); + await session.SaveAsync(guthrie); Assert.Equal(0, await session.QueryIndex().CountAsync()); @@ -1801,8 +1787,8 @@ public async Task ShouldDeduplicateDocuments() Age = 10000 + i }; - session.Save(scott); - session.Save(scotty); + await session.SaveAsync(scott); + await session.SaveAsync(scotty); } await session.SaveChangesAsync(); @@ -1820,7 +1806,7 @@ public async Task ShouldCreateIndexAndLinkToDocument() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1834,13 +1820,13 @@ public async Task ShouldCreateIndexAndLinkToDocument() Lastname = "Balmer" }; - session.Save(bill); - session.Save(steve); + await session.SaveAsync(bill); + await session.SaveAsync(steve); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.QueryIndex(x => x.SomeName == "Bill").CountAsync()); @@ -1863,7 +1849,7 @@ public async Task ShouldJoinMapIndexes() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1883,14 +1869,14 @@ public async Task ShouldJoinMapIndexes() Age = 2 }; - session.Save(bill); - session.Save(steve); - session.Save(paul); + await session.SaveAsync(bill); + await session.SaveAsync(steve); + await session.SaveAsync(paul); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(3, await session.QueryIndex().CountAsync()); Assert.Equal(2, await session.QueryIndex(x => x.Age == 2).CountAsync()); @@ -1906,17 +1892,17 @@ public async Task ShouldReturnImplicitlyFilteredType() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Article()); - session.Save(new Person { Firstname = "Bill" }); - session.Save(new Person { Firstname = "Steve" }); - session.Save(new Person { Firstname = "Paul" }); + await session.SaveAsync(new Article()); + await session.SaveAsync(new Person { Firstname = "Bill" }); + await session.SaveAsync(new Person { Firstname = "Steve" }); + await session.SaveAsync(new Person { Firstname = "Paul" }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(3, await session.QueryIndex().CountAsync()); Assert.Equal(3, await session.Query().For().CountAsync()); @@ -1931,7 +1917,7 @@ public async Task ShouldOrderJoinedMapIndexes() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -1951,14 +1937,14 @@ public async Task ShouldOrderJoinedMapIndexes() Age = 2 }; - session.Save(bill); - session.Save(steve); - session.Save(paul); + await session.SaveAsync(bill); + await session.SaveAsync(steve); + await session.SaveAsync(paul); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query().For() .With(x => x.SomeName.StartsWith("S")) @@ -1986,7 +1972,7 @@ public async Task ShouldClearOrders() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -2000,13 +1986,13 @@ public async Task ShouldClearOrders() Lastname = "Balmer" }; - session.Save(bill); - session.Save(steve); + await session.SaveAsync(bill); + await session.SaveAsync(steve); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var query = session.Query().OrderByDescending(x => x.SomeName); query.OrderByDescending(x => x.SomeName); @@ -2021,7 +2007,7 @@ public async Task ShouldJoinReduceIndex() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dates = new[] { @@ -2045,13 +2031,13 @@ public async Task ShouldJoinReduceIndex() foreach (var article in articles) { - session.Save(article); + await session.SaveAsync(article); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(4, await session.QueryIndex().CountAsync()); @@ -2073,7 +2059,7 @@ public async Task JoinOrderShouldNotMatter() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -2093,14 +2079,14 @@ public async Task JoinOrderShouldNotMatter() Age = 2 }; - session.Save(bill); - session.Save(steve); - session.Save(paul); + await session.SaveAsync(bill); + await session.SaveAsync(steve); + await session.SaveAsync(paul); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal("Steve", (await session.Query().For() .With(x => x.SomeName.StartsWith("S")) @@ -2115,7 +2101,7 @@ public async Task LoadingDocumentShouldNotDuplicateIndex() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -2123,12 +2109,12 @@ public async Task LoadingDocumentShouldNotDuplicateIndex() Lastname = "Gates", }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.QueryIndex(x => x.SomeName == "Bill").CountAsync()); @@ -2142,7 +2128,7 @@ public async Task LoadingDocumentShouldNotDuplicateIndex() Assert.Equal("Bill", person.Firstname); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.QueryIndex(x => x.SomeName == "Bill").CountAsync()); @@ -2161,15 +2147,15 @@ public async Task ShouldIncrementAttachmentIndex() { _store.RegisterIndexes(); //Create one Email with 3 attachments - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = new Email() { Date = new DateTime(2018, 06, 11), Attachments = new System.Collections.Generic.List() { new Attachment("A1"), new Attachment("A2"), new Attachment("A3") } }; - session.Save(email); + await session.SaveAsync(email); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex().CountAsync()); Assert.Equal(3, (await session.QueryIndex(x => x.Date == new DateTime(2018, 06, 11).DayOfYear).FirstOrDefaultAsync()).Count); @@ -2183,7 +2169,7 @@ public async Task ShouldUpdateAttachmentIndex() var date = new DateTime(2018, 06, 11); // Create one Email with 3 attachments - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = new Email() { @@ -2196,19 +2182,19 @@ public async Task ShouldUpdateAttachmentIndex() } }; - session.Save(email); + await session.SaveAsync(email); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex().CountAsync()); Assert.Equal(3, (await session.QueryIndex(x => x.Date == date.DayOfYear).FirstOrDefaultAsync()).Count); } // Updating existing email, adding 2 attachments - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = await session.Query() .Where(m => m.Date == date.DayOfYear) @@ -2217,13 +2203,13 @@ public async Task ShouldUpdateAttachmentIndex() email.Attachments.Add(new Attachment("A4")); email.Attachments.Add(new Attachment("A5")); - session.Save(email); + await session.SaveAsync(email); await session.SaveChangesAsync(); } // Actual email should be updated, and there should still be a single AttachmentByDay - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = await session.Query() .Where(m => m.Date == date.DayOfYear) @@ -2234,7 +2220,7 @@ public async Task ShouldUpdateAttachmentIndex() } // AttachmentByDay Count should have been incremented - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var abd = await session.QueryIndex(x => x.Date == date.DayOfYear).FirstOrDefaultAsync(); Assert.Equal(5, abd.Count); @@ -2246,7 +2232,7 @@ public async Task ShouldReduce() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dates = new[] { @@ -2269,13 +2255,13 @@ public async Task ShouldReduce() foreach (var article in articles) { - session.Save(article); + await session.SaveAsync(article); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(4, await session.QueryIndex().CountAsync()); @@ -2296,7 +2282,7 @@ public async Task ShouldReduceAndMergeWithDatabase() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dates = new[] { @@ -2319,20 +2305,20 @@ public async Task ShouldReduceAndMergeWithDatabase() foreach (var article in articles) { - session.Save(article); + await session.SaveAsync(article); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Article { PublishedUtc = new DateTime(2011, 11, 1) }); + await session.SaveAsync(new Article { PublishedUtc = new DateTime(2011, 11, 1) }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(4, await session.QueryIndex().CountAsync()); @@ -2354,9 +2340,9 @@ public async Task MultipleIndexesShouldNotConflict() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Article + await session.SaveAsync(new Article { PublishedUtc = new DateTime(2011, 11, 1) }); @@ -2364,9 +2350,9 @@ public async Task MultipleIndexesShouldNotConflict() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Article + await session.SaveAsync(new Article { PublishedUtc = new DateTime(2011, 11, 1) }); @@ -2374,7 +2360,7 @@ public async Task MultipleIndexesShouldNotConflict() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex().CountAsync()); } @@ -2391,14 +2377,14 @@ public async Task ShouldDeleteCustomObject() Lastname = "Gates" }; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().For().FirstOrDefaultAsync(); Assert.NotNull(person); @@ -2408,7 +2394,7 @@ public async Task ShouldDeleteCustomObject() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().For().FirstOrDefaultAsync(); Assert.Null(person); @@ -2420,11 +2406,11 @@ public async Task ShouldDeleteCustomObjectBatch() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < _configuration.CommandsPageSize + 50; i++) { - session.Save(new Person + await session.SaveAsync(new Person { Firstname = "Bill", Lastname = "Gates" @@ -2434,7 +2420,7 @@ public async Task ShouldDeleteCustomObjectBatch() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var persons = await session.Query().For().ListAsync(); @@ -2446,7 +2432,7 @@ public async Task ShouldDeleteCustomObjectBatch() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().For().FirstOrDefaultAsync(); Assert.Null(person); @@ -2464,14 +2450,14 @@ public async Task RemovingDocumentShouldDeleteMappedIndex() Lastname = "Gates" }; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var personByName = await session.QueryIndex().FirstOrDefaultAsync(); Assert.NotNull(personByName); @@ -2484,7 +2470,7 @@ public async Task RemovingDocumentShouldDeleteMappedIndex() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var personByName = await session.QueryIndex().FirstOrDefaultAsync(); Assert.Null(personByName); @@ -2496,7 +2482,7 @@ public async Task RemovingDocumentShouldDeleteReducedIndex() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dates = new[] { @@ -2519,20 +2505,20 @@ public async Task RemovingDocumentShouldDeleteReducedIndex() foreach (var article in articles) { - session.Save(article); + await session.SaveAsync(article); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(10, await session.Query().For
().CountAsync()); Assert.Equal(4, await session.QueryIndex().CountAsync()); } // delete a document - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var article = await session.Query().Where(b => b.DayOfYear == new DateTime(2011, 11, 4).DayOfYear).FirstOrDefaultAsync(); Assert.NotNull(article); @@ -2542,7 +2528,7 @@ public async Task RemovingDocumentShouldDeleteReducedIndex() } // there should be only 3 indexes left - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // document was deleted Assert.Equal(9, await session.Query().For
().CountAsync()); @@ -2556,7 +2542,7 @@ public async Task UpdatingDocumentShouldUpdateReducedIndex() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dates = new[] { @@ -2577,13 +2563,13 @@ public async Task UpdatingDocumentShouldUpdateReducedIndex() foreach (var date in dates) { - session.Save(new Article { PublishedUtc = date }); + await session.SaveAsync(new Article { PublishedUtc = date }); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // 10 articles Assert.Equal(10, await session.Query().For
().CountAsync()); @@ -2593,7 +2579,7 @@ public async Task UpdatingDocumentShouldUpdateReducedIndex() } // change the published date of an article - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var article = await session .Query() @@ -2604,13 +2590,13 @@ public async Task UpdatingDocumentShouldUpdateReducedIndex() article.PublishedUtc = new DateTime(2011, 11, 3); - session.Save(article); + await session.SaveAsync(article); await session.SaveChangesAsync(); } // there should be the same number of indexes - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(10, await session.Query().For
().CountAsync()); Assert.Equal(4, await session.QueryIndex().CountAsync()); @@ -2627,7 +2613,7 @@ public virtual async Task AlteringDocumentShouldUpdateReducedIndex() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dates = new[] { @@ -2643,13 +2629,13 @@ public virtual async Task AlteringDocumentShouldUpdateReducedIndex() foreach (var article in articles) { - session.Save(article); + await session.SaveAsync(article); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // There should be 3 articles Assert.Equal(3, await session.Query().For
().CountAsync()); @@ -2659,7 +2645,7 @@ public virtual async Task AlteringDocumentShouldUpdateReducedIndex() } // Deleting a document which was the only one in the reduced group - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var article = await session.Query() .Where(b => b.DayOfYear == new DateTime(2011, 11, 1).DayOfYear) @@ -2672,7 +2658,7 @@ public virtual async Task AlteringDocumentShouldUpdateReducedIndex() } // Ensure the document and its index have been deleted - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // There should be 1 article Assert.Equal(2, await session.Query
().CountAsync()); @@ -2687,18 +2673,18 @@ public async Task IndexHasLinkToDocuments() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var d1 = new Article { PublishedUtc = new DateTime(2011, 11, 1) }; var d2 = new Article { PublishedUtc = new DateTime(2011, 11, 1) }; - session.Save(d1); - session.Save(d2); + await session.SaveAsync(d1); + await session.SaveAsync(d2); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var articles = session.Query().For
(); Assert.Equal(2, await articles.CountAsync()); @@ -2710,13 +2696,13 @@ public async Task ChangesAreAutoFlushed() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var d1 = new Article { PublishedUtc = new DateTime(2011, 11, 1) }; var d2 = new Article { PublishedUtc = new DateTime(2011, 11, 1) }; - session.Save(d1); - session.Save(d2); + await session.SaveAsync(d1); + await session.SaveAsync(d2); var articles = session.Query(x => x.DayOfYear == 305); Assert.Equal(2, await articles.CountAsync()); @@ -2728,13 +2714,13 @@ public async Task AutoflushCanHappenMultipleTimes() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var d1 = new Article { PublishedUtc = new DateTime(2011, 11, 1) }; var d2 = new Article { PublishedUtc = new DateTime(2011, 11, 1) }; - session.Save(d1); - session.Save(d2); + await session.SaveAsync(d1); + await session.SaveAsync(d2); var articles = await session.Query(x => x.DayOfYear == 305).ListAsync(); @@ -2751,13 +2737,13 @@ public async Task ChangesAfterAutoflushAreSaved() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var d1 = new Article { PublishedUtc = new DateTime(2011, 11, 1) }; var d2 = new Article { PublishedUtc = new DateTime(2011, 11, 1) }; - session.Save(d1); - session.Save(d2); + await session.SaveAsync(d1); + await session.SaveAsync(d2); var articles = await session.Query(x => x.DayOfYear == 305).ListAsync(); @@ -2766,7 +2752,7 @@ public async Task ChangesAfterAutoflushAreSaved() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var articles = await session.Query(x => x.DayOfYear == 306).ListAsync(); Assert.Single(articles); @@ -2778,7 +2764,7 @@ public async Task ShouldOrderOnValueType() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < 100; i++) { @@ -2789,13 +2775,13 @@ public async Task ShouldOrderOnValueType() Age = i }; - session.Save(person); + await session.SaveAsync(person); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(100, await session.QueryIndex().CountAsync()); Assert.Equal(0, (await session.QueryIndex().OrderBy(x => x.Age).FirstOrDefaultAsync()).Age); @@ -2808,7 +2794,7 @@ public async Task CanCountThenListOrdered() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < 100; i++) { @@ -2819,13 +2805,13 @@ public async Task CanCountThenListOrdered() Age = i }; - session.Save(person); + await session.SaveAsync(person); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var query = session.QueryIndex().OrderBy(x => x.Age); @@ -2839,7 +2825,7 @@ public async Task ShouldPageResults() { _store.RegisterIndexes(); var random = new Random(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var indices = Enumerable.Range(0, 100).Select(x => x).ToList(); @@ -2862,13 +2848,13 @@ public async Task ShouldPageResults() Lastname = "Gates" + indices[i].ToString("D2"), }; - session.Save(person); + await session.SaveAsync(person); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(100, await session.QueryIndex().CountAsync()); Assert.Equal(10, (await session.QueryIndex().OrderBy(x => x.SomeName).Skip(0).Take(10).ListAsync()).Count()); @@ -2884,7 +2870,7 @@ public async Task ShouldPageResults() } } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(100, await session.QueryIndex().CountAsync()); Assert.Equal(10, (await session.QueryIndex().OrderByDescending(x => x.SomeName).Skip(0).Take(10).ListAsync()).Count()); @@ -2900,7 +2886,7 @@ public async Task ShouldPageResults() } } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var query = session.QueryIndex().OrderBy(x => x.SomeName).Skip(95).Take(10); @@ -2922,7 +2908,7 @@ public async Task ShouldPageWithoutOrder() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < 100; i++) { @@ -2932,13 +2918,13 @@ public async Task ShouldPageWithoutOrder() Lastname = "Gates" + i, }; - session.Save(person); + await session.SaveAsync(person); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // Count() should remove paging and order as it's not supported by some databases Assert.Equal(100, await session.Query().CountAsync()); @@ -2965,7 +2951,7 @@ public async Task PagingShouldNotReturnMoreItemsThanResults() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < 10; i++) { @@ -2975,13 +2961,13 @@ public async Task PagingShouldNotReturnMoreItemsThanResults() Lastname = "Gates" + i, }; - session.Save(person); + await session.SaveAsync(person); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var persons = await session.Query().Take(100).ListAsync(); Assert.Equal(10, persons.Count()); @@ -2993,7 +2979,7 @@ public virtual async Task ShouldReturnCachedResults() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < 10; i++) { @@ -3003,13 +2989,13 @@ public virtual async Task ShouldReturnCachedResults() Lastname = "Gates" + i, }; - session.Save(person); + await session.SaveAsync(person); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var persons = await session.Query().ListAsync(); Assert.Equal(10, persons.Count()); @@ -3025,7 +3011,7 @@ public async Task ShouldQueryByMappedIndex() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -3039,13 +3025,13 @@ public async Task ShouldQueryByMappedIndex() Lastname = "Balmer" }; - session.Save(bill); - session.Save(steve); + await session.SaveAsync(bill); + await session.SaveAsync(steve); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query().For().With().CountAsync()); Assert.Equal(1, await session.Query().For().With(x => x.SomeName == "Steve").CountAsync()); @@ -3058,7 +3044,7 @@ public async Task ShouldQueryByReducedIndex() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dates = new[] { @@ -3081,13 +3067,13 @@ public async Task ShouldQueryByReducedIndex() foreach (var article in articles) { - session.Save(article); + await session.SaveAsync(article); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(10, await session.Query().For
().With().CountAsync()); @@ -3106,7 +3092,7 @@ public async Task ShouldQueryMultipleByReducedIndex() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dates = new[] { @@ -3122,13 +3108,13 @@ public async Task ShouldQueryMultipleByReducedIndex() foreach (var article in articles) { - session.Save(article); + await session.SaveAsync(article); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var query = session.Query
() .Any( @@ -3143,15 +3129,15 @@ public async Task ShouldQueryMultipleByReducedIndex() [Fact] public async Task ShouldSaveBigDocuments() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { - Firstname = new String('x', 10000), + Firstname = new string('x', 10000), }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } @@ -3160,19 +3146,19 @@ public async Task ShouldSaveBigDocuments() [Fact] public async Task ShouldResolveTypes() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { Firstname = "Bill" }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = await session.Query().Any().FirstOrDefaultAsync(); @@ -3185,7 +3171,7 @@ public async Task ShouldResolveTypes() [Fact] public async Task ShouldSavePolymorphicProperties() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var drawing = new Drawing { @@ -3197,12 +3183,12 @@ public async Task ShouldSavePolymorphicProperties() } }; - session.Save(drawing); + await session.SaveAsync(drawing); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var drawing = await session.Query().For().FirstOrDefaultAsync(); @@ -3223,16 +3209,16 @@ public async Task ShouldQuerySubClasses() _store.RegisterIndexes>(); _store.RegisterIndexes>(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Square { Size = 10 }); - session.Save(new Square { Size = 20 }); - session.Save(new Circle { Radius = 5 }); + await session.SaveAsync(new Square { Size = 10 }); + await session.SaveAsync(new Square { Size = 20 }); + await session.SaveAsync(new Circle { Radius = 5 }); await session.SaveChangesAsync(); }; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(3, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.Query(filterType: true).CountAsync()); @@ -3251,7 +3237,7 @@ public async Task ShouldQuerySubClasses() [Fact] public async Task ShouldIgnoreNonSerializedAttribute() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dog = new Animal @@ -3260,12 +3246,12 @@ public async Task ShouldIgnoreNonSerializedAttribute() Color = "Pink" }; - session.Save(dog); + await session.SaveAsync(dog); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dog = await session.Query().For().FirstOrDefaultAsync(); @@ -3280,14 +3266,14 @@ public async Task ShouldGetTypeById() { long circleId; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.FlushAsync(); circleId = circle.Id; @@ -3295,7 +3281,7 @@ public async Task ShouldGetTypeById() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = await session.GetAsync(circleId); @@ -3309,14 +3295,14 @@ public async Task ShouldReturnNullWithWrongTypeById() { long circleId; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.FlushAsync(); circleId = circle.Id; @@ -3324,7 +3310,7 @@ public async Task ShouldReturnNullWithWrongTypeById() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var square = await session.GetAsync(circleId); @@ -3337,14 +3323,14 @@ public virtual async Task ShouldGetDocumentById() { long circleId; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.FlushAsync(); circleId = circle.Id; @@ -3352,7 +3338,7 @@ public virtual async Task ShouldGetDocumentById() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = await session.GetAsync(circleId); @@ -3365,14 +3351,14 @@ public async Task ShouldGetObjectById() { long circleId; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.FlushAsync(); circleId = circle.Id; @@ -3380,7 +3366,7 @@ public async Task ShouldGetObjectById() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = await session.GetAsync(circleId); @@ -3394,14 +3380,14 @@ public async Task ShouldGetDynamicById() { long circleId; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.FlushAsync(); circleId = circle.Id; @@ -3409,7 +3395,7 @@ public async Task ShouldGetDynamicById() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = await session.GetAsync(circleId); @@ -3426,7 +3412,7 @@ public async Task ShouldReturnObjectsByIdsInCorrectOrder(int numberOfItems) { var circleIds = new List(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < numberOfItems; i++) { @@ -3434,7 +3420,7 @@ public async Task ShouldReturnObjectsByIdsInCorrectOrder(int numberOfItems) { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); circleIds.Add(circle.Id); } @@ -3443,7 +3429,7 @@ public async Task ShouldReturnObjectsByIdsInCorrectOrder(int numberOfItems) await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { circleIds.Reverse(); @@ -3456,21 +3442,21 @@ public async Task ShouldReturnObjectsByIdsInCorrectOrder(int numberOfItems) [Fact] public async Task ShouldAllowMultipleCallToSave() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); - session.Save(circle); - session.Save(circle); + await session.SaveAsync(circle); + await session.SaveAsync(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circles = await session.Query().For().ListAsync(); @@ -3482,27 +3468,27 @@ public async Task ShouldAllowMultipleCallToSave() public async Task ShouldUpdateDisconnectedObject() { Circle circle; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { circle.Radius = 20; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circles = await session.Query().For().ListAsync(); Assert.Single(circles); @@ -3513,36 +3499,36 @@ public async Task ShouldUpdateDisconnectedObject() [Fact] public virtual async Task ShouldNotCommitTransaction() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.CancelAsync(); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(0, await session.Query().For().CountAsync()); } } [Fact] - public virtual async Task ShouldNotCreatDocumentInCanceledSessions() + public virtual async Task ShouldNotCreateDocumentInCanceledSessions() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.CancelAsync(); @@ -3553,7 +3539,7 @@ public virtual async Task ShouldNotCreatDocumentInCanceledSessions() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(0, await session.Query().For().CountAsync()); } @@ -3562,19 +3548,19 @@ public virtual async Task ShouldNotCreatDocumentInCanceledSessions() [Fact] public virtual async Task ShouldNotUpdateDocumentInCanceledSessions() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { await session.CancelAsync(); @@ -3582,12 +3568,12 @@ public virtual async Task ShouldNotUpdateDocumentInCanceledSessions() circle.Radius = 20; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = await session.Query().For().FirstOrDefaultAsync(); @@ -3599,30 +3585,30 @@ public virtual async Task ShouldNotUpdateDocumentInCanceledSessions() [Fact] public async Task ShouldSaveChangesExplicitly() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = await session.Query().For().FirstOrDefaultAsync(); Assert.NotNull(circle); circle.Radius = 20; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(20, (await session.Query().For().FirstOrDefaultAsync()).Radius); } @@ -3638,7 +3624,7 @@ public async Task ShouldSaveChangesWithIDisposableAsync() Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } @@ -3648,7 +3634,7 @@ public async Task ShouldSaveChangesWithIDisposableAsync() var circle = await session.Query().For().FirstOrDefaultAsync(); Assert.NotNull(circle); circle.Radius = 20; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } @@ -3662,19 +3648,19 @@ public async Task ShouldSaveChangesWithIDisposableAsync() [Fact] public async Task ShouldNotSaveChangesAutomatically() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = new Circle { Radius = 10 }; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = await session.Query().For().FirstOrDefaultAsync(); Assert.NotNull(circle); @@ -3682,23 +3668,23 @@ public async Task ShouldNotSaveChangesAutomatically() circle.Radius = 20; } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(10, (await session.Query().For().FirstOrDefaultAsync()).Radius); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var circle = await session.Query().For().FirstOrDefaultAsync(); Assert.NotNull(circle); circle.Radius = 20; - session.Save(circle); + await session.SaveAsync(circle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(20, (await session.Query().For().FirstOrDefaultAsync()).Radius); } @@ -3709,19 +3695,19 @@ public async Task ShouldMapWithPredicate() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Article { IsPublished = true }); - session.Save(new Article { IsPublished = true }); - session.Save(new Article { IsPublished = true }); - session.Save(new Article { IsPublished = true }); - session.Save(new Article { IsPublished = false }); - session.Save(new Article { IsPublished = false }); + await session.SaveAsync(new Article { IsPublished = true }); + await session.SaveAsync(new Article { IsPublished = true }); + await session.SaveAsync(new Article { IsPublished = true }); + await session.SaveAsync(new Article { IsPublished = true }); + await session.SaveAsync(new Article { IsPublished = false }); + await session.SaveAsync(new Article { IsPublished = false }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(6, await session.Query().For
().CountAsync()); Assert.Equal(4, await session.Query().For
().With().CountAsync()); @@ -3735,7 +3721,7 @@ public async Task ShouldAcceptEmptyIsIn() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -3752,14 +3738,14 @@ public async Task ShouldAcceptEmptyIsIn() Firstname = "Scott" }; - session.Save(bill); - session.Save(steve); - session.Save(paul); + await session.SaveAsync(bill); + await session.SaveAsync(steve); + await session.SaveAsync(paul); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query().For() .With(x => x.SomeName.IsIn(new[] { "Bill", "Steve" })) @@ -3776,7 +3762,7 @@ public async Task ShouldCreateNotInQuery() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -3793,14 +3779,14 @@ public async Task ShouldCreateNotInQuery() Firstname = "Scott" }; - session.Save(bill); - session.Save(steve); - session.Save(paul); + await session.SaveAsync(bill); + await session.SaveAsync(steve); + await session.SaveAsync(paul); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.Query().For() .With(x => x.SomeName.IsNotIn(new[] { "Bill", "Steve" })) @@ -3838,7 +3824,7 @@ public virtual async Task ShouldReadCommittedRecords() var task1 = Task.Run(async () => { // IsolationLevel.ReadCommitted is the default - using (var session1 = _store.CreateSession()) + await using (var session1 = _store.CreateSession()) { Assert.Equal(0, await session1.QueryIndex().CountAsync()); @@ -3848,7 +3834,7 @@ public virtual async Task ShouldReadCommittedRecords() Lastname = "Gates", }; - session1.Save(bill); + await session1.SaveAsync(bill); await session1.FlushAsync(); Assert.Equal(1, await session1.QueryIndex().CountAsync()); @@ -3864,7 +3850,7 @@ public virtual async Task ShouldReadCommittedRecords() } // IsolationLevel.ReadCommitted is the default - using (var session1 = _store.CreateSession()) + await using (var session1 = _store.CreateSession()) { Assert.Equal(2, await session1.QueryIndex().CountAsync()); } @@ -3878,7 +3864,7 @@ public virtual async Task ShouldReadCommittedRecords() } // IsolationLevel.ReadCommitted is the default - using (var session2 = _store.CreateSession()) + await using (var session2 = _store.CreateSession()) { Assert.Equal(1, await session2.QueryIndex().CountAsync()); @@ -3888,7 +3874,7 @@ public virtual async Task ShouldReadCommittedRecords() Lastname = "Ballmer", }; - session2.Save(steve); + await session2.SaveAsync(steve); await session2.FlushAsync(); @@ -3898,7 +3884,7 @@ public virtual async Task ShouldReadCommittedRecords() } // IsolationLevel.ReadCommitted is the default - using (var session2 = _store.CreateSession()) + await using (var session2 = _store.CreateSession()) { Assert.Equal(2, await session2.QueryIndex().CountAsync()); } @@ -3937,7 +3923,7 @@ public virtual async Task ShouldReadUncommittedRecords() var task1 = Task.Run(async () => { - using (var session1 = _store.CreateSession()) + await using (var session1 = _store.CreateSession()) { await session1.BeginTransactionAsync(IsolationLevel.ReadUncommitted); @@ -3949,7 +3935,7 @@ public virtual async Task ShouldReadUncommittedRecords() Lastname = "Gates", }; - session1.Save(bill); + await session1.SaveAsync(bill); await session1.FlushAsync(); Assert.Equal(1, await session1.QueryIndex().CountAsync()); @@ -3963,7 +3949,7 @@ public virtual async Task ShouldReadUncommittedRecords() await session1.SaveChangesAsync(); } - using (var session1 = _store.CreateSession()) + await using (var session1 = _store.CreateSession()) { await session1.BeginTransactionAsync(IsolationLevel.ReadUncommitted); @@ -3980,7 +3966,7 @@ public virtual async Task ShouldReadUncommittedRecords() Assert.Fail("session1IsFlushed timeout"); } - using (var session2 = _store.CreateSession()) + await using (var session2 = _store.CreateSession()) { await session2.BeginTransactionAsync(IsolationLevel.ReadUncommitted); @@ -3992,7 +3978,7 @@ public virtual async Task ShouldReadUncommittedRecords() Lastname = "Ballmer", }; - session2.Save(steve); + await session2.SaveAsync(steve); await session2.FlushAsync(); @@ -4001,7 +3987,7 @@ public virtual async Task ShouldReadUncommittedRecords() await session2.SaveChangesAsync(); } - using (var session2 = _store.CreateSession()) + await using (var session2 = _store.CreateSession()) { await session2.BeginTransactionAsync(IsolationLevel.ReadUncommitted); @@ -4020,7 +4006,7 @@ public virtual async Task ShouldReadUncommittedRecords() [Fact] public async Task ShouldSaveInCollections() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new { @@ -4028,17 +4014,17 @@ public async Task ShouldSaveInCollections() Lastname = "Gates" }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.Query().Any().CountAsync()); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var steve = new @@ -4047,12 +4033,12 @@ public async Task ShouldSaveInCollections() Lastname = "Balmer" }; - session.Save(steve, "Col1"); + await session.SaveAsync(steve, "Col1"); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.Query("Col1").Any().CountAsync()); } @@ -4063,7 +4049,7 @@ public async Task ShouldFilterMapIndexPerCollection() { _store.RegisterIndexes("Col1"); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -4077,13 +4063,13 @@ public async Task ShouldFilterMapIndexPerCollection() Lastname = "Balmer" }; - session.Save(bill, "Col1"); - session.Save(steve, "Col1"); + await session.SaveAsync(bill, "Col1"); + await session.SaveAsync(steve, "Col1"); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.Query("Col1").CountAsync()); Assert.Equal(1, await session.Query(x => x.Name == "Steve", "Col1").CountAsync()); @@ -4091,7 +4077,7 @@ public async Task ShouldFilterMapIndexPerCollection() } // Store a Person in the default collection - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var satya = new Person { @@ -4099,13 +4085,13 @@ public async Task ShouldFilterMapIndexPerCollection() Lastname = "Nadella", }; - session.Save(satya); + await session.SaveAsync(satya); await session.SaveChangesAsync(); } // Ensure the index hasn't been altered - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.Query().CountAsync()); Assert.Equal(0, await session.QueryIndex().CountAsync()); @@ -4118,7 +4104,7 @@ public async Task ShouldSaveReduceIndexInCollection() { _store.RegisterIndexes("Col1"); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -4130,13 +4116,13 @@ public async Task ShouldSaveReduceIndexInCollection() Firstname = "Bill" }; - session.Save(bill, "Col1"); - session.Save(bill2, "Col1"); + await session.SaveAsync(bill, "Col1"); + await session.SaveAsync(bill2, "Col1"); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, (await session.QueryIndex(x => x.Name == "Bill", "Col1").FirstOrDefaultAsync()).Count); } @@ -4148,7 +4134,7 @@ public async Task ShouldQueryInnerSelectWithCollection() _store.RegisterIndexes("Col1"); _store.RegisterIndexes("Col1"); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -4164,13 +4150,13 @@ public async Task ShouldQueryInnerSelectWithCollection() Age = 12 }; - session.Save(bill, "Col1"); - session.Save(elon, "Col1"); + await session.SaveAsync(bill, "Col1"); + await session.SaveAsync(elon, "Col1"); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.Query(x => x.Name == "Bill", "Col1").CountAsync()); Assert.Equal(1, await session.Query(x => x.Lastname == "Gates", "Col1").CountAsync()); @@ -4190,7 +4176,7 @@ public async Task ShouldQueryInnerSelectWithCollection() [Fact] public async Task ShouldGetAndDeletePerCollection() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -4198,12 +4184,12 @@ public async Task ShouldGetAndDeletePerCollection() Lastname = "Gates", }; - session.Save(bill, "Col1"); + await session.SaveAsync(bill, "Col1"); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query("Col1").FirstOrDefaultAsync(); Assert.NotNull(person); @@ -4216,7 +4202,7 @@ public async Task ShouldGetAndDeletePerCollection() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query("Col1").FirstOrDefaultAsync(); Assert.Null(person); @@ -4228,7 +4214,7 @@ public virtual async Task ShouldIndexWithDateTime() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var dates = new[] { @@ -4252,13 +4238,13 @@ public virtual async Task ShouldIndexWithDateTime() foreach (var article in articles) { - session.Save(article); + await session.SaveAsync(article); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(10, await session.QueryIndex().CountAsync()); Assert.Equal(10, (await session.QueryIndex().ListAsync()).Count()); @@ -4280,19 +4266,19 @@ public virtual async Task ShouldUpdateEntitiesFromSeparateSessions() Lastname = "Gates" }; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(bill); + await session.SaveAsync(bill); Assert.Equal(1, await session.Query().CountAsync()); Assert.Equal(1, await session.QueryIndex().Where(x => x.SomeName == "Bill").CountAsync()); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { bill.Firstname = "Bill2"; - session.Save(bill); + await session.SaveAsync(bill); await session.FlushAsync(); Assert.Equal(1, await session.Query().CountAsync()); @@ -4308,10 +4294,10 @@ public async Task TrackDocumentQuery() { Person person1, person2; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { person1 = new Person { Firstname = "Bill" }; - session.Save(person1); + await session.SaveAsync(person1); person2 = await session.Query().FirstOrDefaultAsync(); await session.SaveChangesAsync(); @@ -4331,21 +4317,21 @@ public async Task SqlDateFunctions(string method, int expected) { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var article = new Article { PublishedUtc = new DateTime(2011, 11, 1, 2, 5, 4, DateTimeKind.Utc) }; - session.Save(article); + await session.SaveAsync(article); await session.SaveChangesAsync(); } int result; - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); @@ -4364,15 +4350,15 @@ public async Task SqlNowFunction() var now = DateTime.UtcNow; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 1; i < 11; i++) { - session.Save(new Article + await session.SaveAsync(new Article { PublishedUtc = now.AddDays(i) }); - session.Save(new Article + await session.SaveAsync(new Article { PublishedUtc = now.AddDays(-i) }); @@ -4383,7 +4369,7 @@ public async Task SqlNowFunction() int publishedInTheFutureResult, publishedInThePastResult; - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); @@ -4411,14 +4397,14 @@ public virtual async Task CanUseStaticMethodsInLinqQueries() Lastname = "GATES" }; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex().Where(x => x.SomeName == PersonByName.Normalize(bill.Firstname)).CountAsync()); } @@ -4429,7 +4415,7 @@ public virtual async Task ShouldRemoveGroupKey() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var user = new User { @@ -4438,21 +4424,21 @@ public virtual async Task ShouldRemoveGroupKey() RoleNames = { "administrator", "editor" } }; - session.Save(user); + await session.SaveAsync(user); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var user = await session.Query().FirstOrDefaultAsync(); user.RoleNames.Remove("editor"); - session.Save(user); + await session.SaveAsync(user); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(1, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.Query(x => x.RoleName == "administrator").CountAsync()); @@ -4465,7 +4451,7 @@ public virtual async Task ShouldAddGroupKey() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var user = new User { @@ -4474,21 +4460,21 @@ public virtual async Task ShouldAddGroupKey() RoleNames = { "administrator" } }; - session.Save(user); + await session.SaveAsync(user); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var user = await session.Query().FirstOrDefaultAsync(); user.RoleNames.Add("editor"); - session.Save(user); + await session.SaveAsync(user); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(2, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.Query(x => x.RoleName == "administrator").CountAsync()); @@ -4501,7 +4487,7 @@ public virtual async Task ShouldGateQuery() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -4515,12 +4501,12 @@ public virtual async Task ShouldGateQuery() Lastname = "Balmer" }; - session.Save(bill); - session.Save(steve); + await session.SaveAsync(bill); + await session.SaveAsync(steve); for (var i = 0; i < 20; i++) { - session.Save(new Person { Firstname = $"Foo {i}" }); + await session.SaveAsync(new Person { Firstname = $"Foo {i}" }); } await session.SaveChangesAsync(); @@ -4543,12 +4529,10 @@ public virtual async Task ShouldGateQuery() { while (!stopping && Interlocked.Add(ref counter, 1) < MaxTransactions) { - using (var session = _store.CreateSession()) - { - await session.Query().For().With().ListAsync(); - await session.Query().For().With(x => x.SomeName == "Steve").ListAsync(); - await session.Query().For().With().Where(x => x.SomeName == "Steve").ListAsync(); - } + await using var session = _store.CreateSession(); + await session.Query().For().With().ListAsync(); + await session.Query().For().With(x => x.SomeName == "Steve").ListAsync(); + await session.Query().For().With().Where(x => x.SomeName == "Steve").ListAsync(); } })).ToList(); @@ -4570,12 +4554,10 @@ public virtual async Task ShouldGateQuery() { while (!stopping && Interlocked.Add(ref counter, 1) < MaxTransactions) { - using (var session = _store.CreateSession()) - { - await session.Query().For().With().ListAsync(); - await session.Query().For().With(x => x.SomeName == "Steve").ListAsync(); - await session.Query().For().With().Where(x => x.SomeName == "Steve").ListAsync(); - } + await using var session = _store.CreateSession(); + await session.Query().For().With().ListAsync(); + await session.Query().For().With(x => x.SomeName == "Steve").ListAsync(); + await session.Query().For().With().Where(x => x.SomeName == "Steve").ListAsync(); } gatedCounter = counter; @@ -4602,12 +4584,10 @@ public virtual async Task ShouldGateQuery() { while (!stopping && Interlocked.Add(ref counter, 1) < MaxTransactions) { - using (var session = _store.CreateSession()) - { - await session.Query().For().With().ListAsync(); - await session.Query().For().With(x => x.SomeName == "Steve").ListAsync(); - await session.Query().For().With().Where(x => x.SomeName == "Steve").ListAsync(); - } + await using var session = _store.CreateSession(); + await session.Query().For().With().ListAsync(); + await session.Query().For().With(x => x.SomeName == "Steve").ListAsync(); + await session.Query().For().With().Where(x => x.SomeName == "Steve").ListAsync(); } nonGatedCounter = counter; @@ -4634,7 +4614,7 @@ public virtual async Task ShouldPopulateIdFieldWithPrivateSetter() { Tree oak; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { oak = new Tree { @@ -4642,12 +4622,12 @@ public virtual async Task ShouldPopulateIdFieldWithPrivateSetter() HeightInInches = 375 }; - session.Save(oak); + await session.SaveAsync(oak); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(oak.Id, (await session.Query().FirstOrDefaultAsync()).Id); } @@ -4656,14 +4636,14 @@ public virtual async Task ShouldPopulateIdFieldWithPrivateSetter() [Fact] public virtual async Task ShouldConvertDateTimeToUtc() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Article { PublishedUtc = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Local) }); + await session.SaveAsync(new Article { PublishedUtc = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Local) }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var article = await session.Query
().FirstOrDefaultAsync(); @@ -4678,20 +4658,20 @@ public async Task ShouldOrderCaseInsensitively() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Person { Firstname = "D" }); - session.Save(new Person { Firstname = "b" }); - session.Save(new Person { Firstname = "G" }); - session.Save(new Person { Firstname = "F" }); - session.Save(new Person { Firstname = "c" }); - session.Save(new Person { Firstname = "e" }); - session.Save(new Person { Firstname = "A" }); + await session.SaveAsync(new Person { Firstname = "D" }); + await session.SaveAsync(new Person { Firstname = "b" }); + await session.SaveAsync(new Person { Firstname = "G" }); + await session.SaveAsync(new Person { Firstname = "F" }); + await session.SaveAsync(new Person { Firstname = "c" }); + await session.SaveAsync(new Person { Firstname = "e" }); + await session.SaveAsync(new Person { Firstname = "A" }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = await session.Query().OrderBy(x => x.SomeName).ListAsync(); @@ -4710,17 +4690,17 @@ public async Task ShouldOrderWithoutDuplicates() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Person { Firstname = "D" }); - session.Save(new Person { Firstname = "G" }); - session.Save(new Person { Firstname = "F" }); - session.Save(new Person { Firstname = "A" }); + await session.SaveAsync(new Person { Firstname = "D" }); + await session.SaveAsync(new Person { Firstname = "G" }); + await session.SaveAsync(new Person { Firstname = "F" }); + await session.SaveAsync(new Person { Firstname = "A" }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = await session.Query().OrderBy(x => x.SomeName).NoDuplicates().ListAsync(); @@ -4736,17 +4716,17 @@ public async Task ShouldQueryOrderByRandom() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < 100; i++) { - session.Save(new Person { Firstname = i < 50 ? "D" : "E" }); + await session.SaveAsync(new Person { Firstname = i < 50 ? "D" : "E" }); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = await session.Query().OrderByRandom().ListAsync(); @@ -4760,17 +4740,17 @@ public async Task ShouldQueryThenByRandom() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var i = 0; i < 100; i++) { - session.Save(new Person { Firstname = i < 50 ? "D" : "E" }); + await session.SaveAsync(new Person { Firstname = i < 50 ? "D" : "E" }); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = await session.Query().OrderBy(x => x.SomeName).ThenByRandom().ListAsync(); @@ -4789,9 +4769,9 @@ public async Task ShouldImportDetachedObject() Firstname = "Bill", }; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(bill); + await session.SaveAsync(bill); Assert.Single(await session.Query().ListAsync()); Assert.True(bill.Id > 0); @@ -4799,7 +4779,7 @@ public async Task ShouldImportDetachedObject() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { bill = new Person { @@ -4813,7 +4793,7 @@ public async Task ShouldImportDetachedObject() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var all = await session.Query().ListAsync(); Assert.Single(all); @@ -4826,7 +4806,7 @@ public async Task ShouldHandleNullableFields() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -4849,14 +4829,14 @@ public async Task ShouldHandleNullableFields() Age = 376 }; - session.Save(bill); - session.Save(elon); - session.Save(isaac); + await session.SaveAsync(bill); + await session.SaveAsync(elon); + await session.SaveAsync(isaac); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(3, await session.Query().CountAsync()); Assert.Equal(1, await session.Query(x => x.Age == null).CountAsync()); @@ -4866,7 +4846,7 @@ public async Task ShouldHandleNullableFields() [Fact] public async Task ShouldHandleBooleanConstants() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var user = new User { @@ -4875,12 +4855,12 @@ public async Task ShouldHandleBooleanConstants() RoleNames = { "administrator", "editor" } }; - session.Save(user); + await session.SaveAsync(user); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { string roleName = null; var result1 = await session @@ -4898,7 +4878,6 @@ public async Task ShouldHandleBooleanConstants() Assert.Null(result1); Assert.Null(result2); Assert.Null(result3); - } } @@ -4909,7 +4888,7 @@ public async Task ShouldLogSql() _store.Configuration.Logger = logger; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -4918,7 +4897,7 @@ public async Task ShouldLogSql() Age = 50 }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } @@ -4927,7 +4906,7 @@ public async Task ShouldLogSql() } [Fact] - public async Task ShouldNotGenerateDeleteSatementsForFilteredIndexProviders() + public async Task ShouldNotGenerateDeleteStatementsForFilteredIndexProviders() { var logger = new TestLogger(); @@ -4936,14 +4915,14 @@ public async Task ShouldNotGenerateDeleteSatementsForFilteredIndexProviders() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Person { Firstname = "A" }); + await session.SaveAsync(new Person { Firstname = "A" }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = await session.Query().ListAsync(); Assert.Equal("A", results.ElementAt(0).Firstname); @@ -4957,7 +4936,7 @@ public async Task ShouldNotGenerateDeleteSatementsForFilteredIndexProviders() } [Fact] - public async Task ShouldGenerateDeleteSatementsForFilteredIndexProviders() + public async Task ShouldGenerateDeleteStatementsForFilteredIndexProviders() { var logger = new TestLogger(); @@ -4966,14 +4945,14 @@ public async Task ShouldGenerateDeleteSatementsForFilteredIndexProviders() _store.RegisterIndexes(); _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(new Person { Firstname = "A" }); + await session.SaveAsync(new Person { Firstname = "A" }); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var results = await session.Query().ListAsync(); Assert.Equal("A", results.ElementAt(0).Firstname); @@ -4992,12 +4971,12 @@ public async Task ShouldCreateMoreObjectThanIdBlock() long lastId = 0; long firstId = 0; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { for (var k = 0; k < 1000; k++) { var person = new Person { Firstname = "Bill" }; - session.Save(person); + await session.SaveAsync(person); lastId = person.Id; if (firstId == 0) @@ -5024,14 +5003,14 @@ public async Task ShouldGenerateIdsConcurrently(string collection) long lastId = 0; var results = new bool[MaxTransactions + concurrency]; - var tasks = Enumerable.Range(1, concurrency).Select(i => Task.Run(() => + var tasks = Enumerable.Range(1, concurrency).Select(i => Task.Run(async () => { long taskId; man.Wait(); while (!cts.IsCancellationRequested) { - lastId = taskId = _store.Configuration.IdGenerator.GetNextId(collection); + lastId = taskId = await _store.Configuration.IdGenerator.GetNextIdAsync(collection); if (taskId > MaxTransactions) { @@ -5041,7 +5020,7 @@ public async Task ShouldGenerateIdsConcurrently(string collection) Assert.False(results[taskId], $"Found duplicate identifier: '{taskId}'"); results[taskId] = true; - System.Diagnostics.Debug.WriteLine($"{i}:{taskId}"); + Debug.WriteLine($"{i}:{taskId}"); } })).ToList(); @@ -5055,32 +5034,31 @@ public async Task ShouldGenerateIdsConcurrently(string collection) [Fact] public async Task ShouldNotDuplicateCommandsWhenCommitFails() { - - using (var session = (Session)_store.CreateSession()) + await using var session = (Session)_store.CreateSession(); + var bill = new Person { - var bill = new Person - { - Firstname = "Bill", - Lastname = "Gates" - }; + Firstname = "Bill", + Lastname = "Gates" + }; - session.Save(bill); + await session.SaveAsync(bill); - // Create a command that will throw an exception - // Use an order of 4 so it will be at the end of the list - session._commands = new List(); - session._commands.Add(new FailingCommand(new Document())); + // Create a command that will throw an exception + // Use an order of 4 so it will be at the end of the list + session._commands = new List + { + new FailingCommand(new Document()) + }; - await Assert.ThrowsAnyAsync(async () => await session.SaveChangesAsync()); + await Assert.ThrowsAnyAsync(session.SaveChangesAsync); - Assert.Null(session._commands); - } + Assert.Null(session._commands); } [Fact] public async Task ShouldResolveManyTypes() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -5093,13 +5071,13 @@ public async Task ShouldResolveManyTypes() Name = "Lion" }; - session.Save(bill); - session.Save(lion); + await session.SaveAsync(bill); + await session.SaveAsync(lion); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var all = await session.Query().Any().ListAsync(); @@ -5118,7 +5096,7 @@ public async Task ShouldReturnDistinctDocuments() _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = new Email() { @@ -5131,12 +5109,12 @@ public async Task ShouldReturnDistinctDocuments() } }; - session.Save(email); + await session.SaveAsync(email); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var result = await session.Query().Where(e => e.AttachmentName.EndsWith(".doc")).ListAsync(); @@ -5150,11 +5128,11 @@ public async Task ShouldReturnNonUniqueResultsWithDistinctOption() // Query a page of documents, but collisions in the results should trigger database round-trips to fill the page _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // Creates 30 emails with 3 attachments each - for (int i = 0; i < 30; i++) + for (var i = 0; i < 30; i++) { var email = new Email() { @@ -5167,13 +5145,13 @@ public async Task ShouldReturnNonUniqueResultsWithDistinctOption() } }; - session.Save(email); + await session.SaveAsync(email); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var result1 = await session.Query().Where(e => e.AttachmentName.EndsWith(".doc")).Take(10).ListAsync(); var count1 = await session.Query().Where(e => e.AttachmentName.EndsWith(".doc")).CountAsync(); @@ -5192,7 +5170,7 @@ public async Task ShouldCountSingleDocument() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = new Email() { @@ -5205,12 +5183,12 @@ public async Task ShouldCountSingleDocument() } }; - session.Save(email); + await session.SaveAsync(email); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // Get all emails that have '.doc' attachments var count = await session.Query().Where(e => e.AttachmentName.EndsWith(".doc")).CountAsync(); @@ -5220,7 +5198,7 @@ public async Task ShouldCountSingleDocument() } [Fact] - public virtual void ShouldRenameColumn() + public virtual async Task ShouldRenameColumn() { var table = "Table1"; var prefixedTable = TablePrefix + table; @@ -5228,97 +5206,91 @@ public virtual void ShouldRenameColumn() var column2 = "Column2"; var value = "Value"; - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) - { - connection.Open(); - - try - { - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - builder.DropTable(table); + try + { + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); - transaction.Commit(); - } - } - catch - { - // Do nothing if the table can't be dropped - } + var builder = new SchemaBuilder(_store.Configuration, transaction); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { + await builder.DropTableAsync(table); - var builder = new SchemaBuilder(_store.Configuration, transaction); + await transaction.CommitAsync(); + } + catch + { + // Do nothing if the table can't be dropped + } - builder.CreateTable(table, column => column - .Column(column1) - ); + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) + { + var builder = new SchemaBuilder(_store.Configuration, transaction); - var sqlInsert = string.Format("INSERT INTO {0} ({1}) VALUES({2})", - _store.Configuration.SqlDialect.QuoteForTableName(prefixedTable, _store.Configuration.Schema), - _store.Configuration.SqlDialect.QuoteForColumnName(column1), - _store.Configuration.SqlDialect.GetSqlValue(value) - ); + await builder.CreateTableAsync(table, column => column + .Column(column1) + ); - connection.Execute(sqlInsert, transaction: transaction); + var sqlInsert = string.Format("INSERT INTO {0} ({1}) VALUES({2})", + _store.Configuration.SqlDialect.QuoteForTableName(prefixedTable, _store.Configuration.Schema), + _store.Configuration.SqlDialect.QuoteForColumnName(column1), + _store.Configuration.SqlDialect.GetSqlValue(value) + ); - transaction.Commit(); - } + await connection.ExecuteAsync(sqlInsert, transaction: transaction); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var sqlSelect = string.Format("SELECT {0} FROM {1}", - _store.Configuration.SqlDialect.QuoteForColumnName(column1), - _store.Configuration.SqlDialect.QuoteForTableName(prefixedTable, _store.Configuration.Schema) - ); + await transaction.CommitAsync(); + } - var result = connection.Query(sqlSelect, transaction: transaction).FirstOrDefault(); + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) + { + var sqlSelect = string.Format("SELECT {0} FROM {1}", + _store.Configuration.SqlDialect.QuoteForColumnName(column1), + _store.Configuration.SqlDialect.QuoteForTableName(prefixedTable, _store.Configuration.Schema) + ); - Assert.Equal(value, result.Column1); + var result = (await connection.QueryAsync(sqlSelect, transaction: transaction)).FirstOrDefault(); - transaction.Commit(); - } + Assert.Equal(value, result.Column1); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await transaction.CommitAsync(); + } - builder.AlterTable(table, column => column - .RenameColumn(column1, column2) - ); + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) + { + var builder = new SchemaBuilder(_store.Configuration, transaction); - transaction.Commit(); - } + await builder.AlterTableAsync(table, column => column + .RenameColumn(column1, column2) + ); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var sqlSelect = string.Format("SELECT {0} FROM {1}", - _store.Configuration.SqlDialect.QuoteForColumnName(column2), - _store.Configuration.SqlDialect.QuoteForTableName(prefixedTable, _store.Configuration.Schema) - ); + await transaction.CommitAsync(); + } - var result = connection.Query(sqlSelect, transaction: transaction).FirstOrDefault(); + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) + { + var sqlSelect = string.Format("SELECT {0} FROM {1}", + _store.Configuration.SqlDialect.QuoteForColumnName(column2), + _store.Configuration.SqlDialect.QuoteForTableName(prefixedTable, _store.Configuration.Schema) + ); - Assert.Equal(value, result.Column2); + var result = (await connection.QueryAsync(sqlSelect, transaction: transaction)).FirstOrDefault(); - transaction.Commit(); - } + Assert.Equal(value, result.Column2); + await transaction.CommitAsync(); } } [Fact] public virtual async Task ShouldHandleConcurrency() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = new Person { Firstname = "Bill" }; - session.Save(email); + await session.SaveAsync(email); await session.SaveChangesAsync(); } @@ -5329,7 +5301,7 @@ public virtual async Task ShouldHandleConcurrency() var task1 = Task.Run(async () => { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); @@ -5345,13 +5317,13 @@ public virtual async Task ShouldHandleConcurrency() person.Lastname = "Gates"; - session.Save(person, true); + await session.SaveAsync(person, true); Assert.NotNull(person); await session.SaveChangesAsync(); } - // Noify the other thread to save + // Notify the other thread to save task1Saved.Set(); }); @@ -5361,32 +5333,30 @@ public virtual async Task ShouldHandleConcurrency() await Assert.ThrowsAsync(async () => { - using (var session = _store.CreateSession()) - { - var person = await session.Query().FirstOrDefaultAsync(); - Assert.NotNull(person); + await using var session = _store.CreateSession(); + var person = await session.Query().FirstOrDefaultAsync(); + Assert.NotNull(person); - task2Loaded.Set(); + task2Loaded.Set(); - // Wait for the other thread to save the person before updating it - if (!task1Saved.WaitOne(5000)) - { - Assert.Fail("task1Saved timeout"); - await session.CancelAsync(); - } + // Wait for the other thread to save the person before updating it + if (!task1Saved.WaitOne(5000)) + { + Assert.Fail("task1Saved timeout"); + await session.CancelAsync(); + } - person.Lastname = "Doors"; - session.Save(person, true); - Assert.NotNull(person); + person.Lastname = "Doors"; + await session.SaveAsync(person, true); + Assert.NotNull(person); - await session.SaveChangesAsync(); - } + await session.SaveChangesAsync(); }); }); await Task.WhenAll(task1, task2); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); @@ -5399,41 +5369,41 @@ public virtual async Task ShouldNotThrowConcurrencyException() { _store.Configuration.CheckConcurrentUpdates(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = new Person { Firstname = "Bill" }; - session.Save(email); + await session.SaveAsync(email); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); person.Lastname = "Gates"; - session.Save(person); + await session.SaveAsync(person); Assert.NotNull(person); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); person.Lastname = "Doors"; - session.Save(person); + await session.SaveAsync(person); Assert.NotNull(person); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); @@ -5449,10 +5419,9 @@ public async Task ShouldReloadDetachedObject() Firstname = "Bill", }; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - - session.Save(bill); + await session.SaveAsync(bill); Assert.Single(await session.Query().ListAsync()); Assert.True(bill.Id > 0); @@ -5460,7 +5429,7 @@ public async Task ShouldReloadDetachedObject() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { bill = new Person { @@ -5469,12 +5438,12 @@ public async Task ShouldReloadDetachedObject() Lastname = "Gates", }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var all = await session.Query().ListAsync(); Assert.Single(all); @@ -5485,28 +5454,26 @@ public async Task ShouldReloadDetachedObject() [Fact] public async Task ShouldDetachEntity() { - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var bill = new Person { - var bill = new Person - { - Firstname = "Bill", - Lastname = "Gates" - }; + Firstname = "Bill", + Lastname = "Gates" + }; - session.Save(bill); + await session.SaveAsync(bill); - var newBill = await session.GetAsync(bill.Id); + var newBill = await session.GetAsync(bill.Id); - Assert.Equal(bill, newBill); + Assert.Equal(bill, newBill); - session.Detach(bill); + session.Detach(bill); - newBill = await session.GetAsync(bill.Id); + newBill = await session.GetAsync(bill.Id); - Assert.NotEqual(bill, newBill); + Assert.NotEqual(bill, newBill); - await session.SaveChangesAsync(); - } + await session.SaveChangesAsync(); } [Fact] @@ -5514,15 +5481,15 @@ public async Task ShouldStoreBinaryInIndex() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { Firstname = "Bill" }; - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var binary = await session.QueryIndex().FirstOrDefaultAsync(); @@ -5537,52 +5504,46 @@ public async Task ShouldStoreBinaryInIndex() [Fact] public async Task ShouldCreateAndIndexPropertyWithMaximumKeyLengths() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder.DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(767)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(767)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location)) + ); - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied")); + await builder.AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied") + ); - transaction.Commit(); - } + await transaction.CommitAsync(); } _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var property = new Property { - var property = new Property - { - Name = new string('*', 767), - IsOccupied = true, - ForRent = true - }; + Name = new string('*', 767), + IsOccupied = true, + ForRent = true + }; - session.Save(property); - } + await session.SaveAsync(property); } [Fact] public async Task ShouldCommitInMultipleCollections() { - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var steve = new { @@ -5590,7 +5551,7 @@ public async Task ShouldCommitInMultipleCollections() Lastname = "Balmer" }; - session.Save(steve); + await session.SaveAsync(steve); var bill = new { @@ -5599,12 +5560,12 @@ public async Task ShouldCommitInMultipleCollections() }; - session.Save(bill, "Col1"); + await session.SaveAsync(bill, "Col1"); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var count = await session.Query("Col1").Any().CountAsync(); Assert.Equal(1, count); @@ -5619,7 +5580,7 @@ public async Task ShouldStoreCollectionIndexesInDistinctTables() { _store.RegisterIndexes("Col1"); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var steve = new Person { @@ -5627,7 +5588,7 @@ public async Task ShouldStoreCollectionIndexesInDistinctTables() Lastname = "Balmer" }; - session.Save(steve); + await session.SaveAsync(steve); var bill = new Person { @@ -5635,12 +5596,12 @@ public async Task ShouldStoreCollectionIndexesInDistinctTables() Lastname = "Gates" }; - session.Save(bill, "Col1"); + await session.SaveAsync(bill, "Col1"); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { Assert.Equal(0, await session.QueryIndex().CountAsync()); Assert.Equal(1, await session.QueryIndex("Col1").CountAsync()); @@ -5652,16 +5613,16 @@ public virtual async Task ShouldSetVersionProperty() { _store.Configuration.CheckConcurrentUpdates(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var doc1 = new Person { Firstname = "Bill", Version = 11 }; - session.Save(doc1); + await session.SaveAsync(doc1); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var doc1 = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(doc1); @@ -5675,16 +5636,16 @@ public virtual async Task ShouldIncrementVersionProperty() { _store.Configuration.CheckConcurrentUpdates(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var doc1 = new Person { Firstname = "Bill" }; - session.Save(doc1); + await session.SaveAsync(doc1); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var doc1 = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(doc1); @@ -5694,7 +5655,7 @@ public virtual async Task ShouldIncrementVersionProperty() } [Fact] - public virtual async Task ShouldCheckVersionHaschanged() + public virtual async Task ShouldCheckVersionHasChanged() { // Simulates a long running workflow where a web page // wants to update a document, and check that the state it @@ -5710,11 +5671,11 @@ public virtual async Task ShouldCheckVersionHaschanged() _store.Configuration.CheckConcurrentUpdates(); // Create initial document - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = new Person { Firstname = "Bill" }; - session.Save(email); + await session.SaveAsync(email); await session.SaveChangesAsync(); } @@ -5726,7 +5687,7 @@ public virtual async Task ShouldCheckVersionHaschanged() }; // User A loads the document, stores in a view model - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); @@ -5741,14 +5702,14 @@ public virtual async Task ShouldCheckVersionHaschanged() } // User B loads the document, updates it - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); person.Firstname = "William"; - session.Save(person); + await session.SaveAsync(person); // The object is new, its version should be 1 Assert.Equal(1, person.Version); @@ -5757,7 +5718,7 @@ public virtual async Task ShouldCheckVersionHaschanged() } // User A submits the changes, and should detect the version has changed - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); @@ -5767,7 +5728,7 @@ public virtual async Task ShouldCheckVersionHaschanged() } [Fact] - public virtual async Task ShouldDetectVersionHaschanged() + public virtual async Task ShouldDetectVersionHasChanged() { // Simulates a long running workflow where a web page // wants to update a document, and check that the state it @@ -5783,11 +5744,11 @@ public virtual async Task ShouldDetectVersionHaschanged() _store.Configuration.CheckConcurrentUpdates(); // Create initial document - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var email = new Person { Firstname = "Bill" }; - session.Save(email); + await session.SaveAsync(email); await session.SaveChangesAsync(); } @@ -5799,7 +5760,7 @@ public virtual async Task ShouldDetectVersionHaschanged() }; // User A loads the document, stores in a view model - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); @@ -5814,14 +5775,14 @@ public virtual async Task ShouldDetectVersionHaschanged() } // User B loads the document, updates it - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); person.Firstname = "William"; - session.Save(person); + await session.SaveAsync(person); // The object is new, its version should be 1 Assert.Equal(1, person.Version); @@ -5832,22 +5793,20 @@ public virtual async Task ShouldDetectVersionHaschanged() // User A submits the changes await Assert.ThrowsAsync(async () => { - using (var session = _store.CreateSession()) - { - var person = await session.Query().FirstOrDefaultAsync(); - Assert.NotNull(person); + await using var session = _store.CreateSession(); + var person = await session.Query().FirstOrDefaultAsync(); + Assert.NotNull(person); - person.Version = viewModel.Version; - person.Firstname = viewModel.Firstname; + person.Version = viewModel.Version; + person.Firstname = viewModel.Firstname; - session.Save(person); + await session.SaveAsync(person); - await session.SaveChangesAsync(); - } + await session.SaveChangesAsync(); }); // Changes should not have been persisted - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().FirstOrDefaultAsync(); Assert.NotNull(person); @@ -5860,9 +5819,9 @@ await Assert.ThrowsAsync(async () => [ClassData(typeof(DecimalPrecisionAndScaleDataGenerator))] public void SqlDecimalPrecisionAndScale(byte? precision, byte? scale) { - string expected = string.Format(DecimalColumnDefinitionFormatString, precision ?? _store.Configuration.SqlDialect.DefaultDecimalPrecision, scale ?? _store.Configuration.SqlDialect.DefaultDecimalScale); + var expected = string.Format(DecimalColumnDefinitionFormatString, precision ?? _store.Configuration.SqlDialect.DefaultDecimalPrecision, scale ?? _store.Configuration.SqlDialect.DefaultDecimalScale); - string result = _store.Configuration.SqlDialect.GetTypeName(DbType.Decimal, null, precision, scale); + var result = _store.Configuration.SqlDialect.GetTypeName(DbType.Decimal, null, precision, scale); Assert.Equal(expected, result); } @@ -5874,22 +5833,22 @@ public async Task ShouldUpdateVersions() _store.Configuration.CheckConcurrentUpdates(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var c = new Car { Name = "Clio" }; - session.Save(c); + await session.SaveAsync(c); await session.SaveChangesAsync(); } // Create initial document - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // Load the existing car var c = await session.Query().FirstOrDefaultAsync(); - session.Save(c); + await session.SaveAsync(c); await session.Query().FirstOrDefaultAsync(); @@ -5911,22 +5870,23 @@ public async Task AllDataTypesShouldBeStored() var valueDateTimeOffset = new DateTimeOffset(valueDateTime, new TimeSpan(1, 2, 0)); // Create fake document to associate to index - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(dummy); + await session.SaveAsync(dummy); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - var index = new TypesIndex(); - - index.ValueDateTime = valueDateTime; - index.ValueGuid = valueGuid; - index.ValueBool = valueBool; - index.ValueDateTimeOffset = valueDateTimeOffset; - index.ValueTimeSpan = valueTimeSpan; + var index = new TypesIndex + { + ValueDateTime = valueDateTime, + ValueGuid = valueGuid, + ValueBool = valueBool, + ValueDateTimeOffset = valueDateTimeOffset, + ValueTimeSpan = valueTimeSpan + }; ((IIndex)index).AddDocument(new Document { Id = dummy.Id }); @@ -5938,7 +5898,7 @@ public async Task AllDataTypesShouldBeStored() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var index = await session.QueryIndex().FirstOrDefaultAsync(); @@ -5969,14 +5929,14 @@ public async Task AllDataTypesShouldBeQueryableWithProperties() var valueDateTimeOffset = new DateTimeOffset(valueDateTime, new TimeSpan(1, 2, 0)); // Create fake document to associate to index - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(dummy); + await session.SaveAsync(dummy); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var index = new TypesIndex(); @@ -5996,9 +5956,9 @@ public async Task AllDataTypesShouldBeQueryableWithProperties() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - // Ensure that query builing is also converting the values + // Ensure that query building is also converting the values var index = await session.QueryIndex(x => x.ValueBool == valueBool && x.ValueDateTime == valueDateTime @@ -6033,14 +5993,14 @@ public async Task AllDataTypesShouldBeQueryableWithConstants() var valueDateTimeOffset = new DateTimeOffset(valueDateTime, new TimeSpan(1, 2, 0)); // Create fake document to associate to index - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(dummy); + await session.SaveAsync(dummy); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var index = new TypesIndex(); @@ -6060,9 +6020,9 @@ public async Task AllDataTypesShouldBeQueryableWithConstants() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - // Ensure that query builing is also converting constants + // Ensure that query building is also converting constants var index = await session.QueryIndex(x => x.ValueBool == false && x.ValueDateTime == new DateTime(2021, 1, 20) @@ -6092,14 +6052,14 @@ public async Task NullValuesShouldBeStoredInNullableFields() var dummy = new Person(); // Create fake document to associate to index - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(dummy); + await session.SaveAsync(dummy); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var index = new TypesIndex { @@ -6119,7 +6079,7 @@ public async Task NullValuesShouldBeStoredInNullableFields() await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var index = await session.QueryIndex().FirstOrDefaultAsync(); @@ -6143,18 +6103,18 @@ public async Task ShouldSplitBatchCommandsByMaxParameters() _store.RegisterIndexes(); _store.Configuration.CommandsPageSize = int.MaxValue; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // This will produce 2000 queries (1 doc + 1 index) and 8000 parameters (4/doc and 4/index) for (var i = 0; i < 1000; i++) { - session.Save(new Person { Age = i, Firstname = i.ToString(), Lastname = i.ToString() }); + await session.SaveAsync(new Person { Age = i, Firstname = i.ToString(), Lastname = i.ToString() }); } await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var persons = (await session.Query().ListAsync()); Assert.Equal(1000, persons.Count()); @@ -6162,7 +6122,7 @@ public async Task ShouldSplitBatchCommandsByMaxParameters() // When reduced to a maximum to 2098, i.e. stopping the batch before 2099, it will pass. foreach (var person in persons) { - session.Save(person); + await session.SaveAsync(person); } } } @@ -6175,7 +6135,7 @@ public async Task SameQueryShouldBeReusable() _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var bill = new Person { @@ -6189,13 +6149,13 @@ public async Task SameQueryShouldBeReusable() Lastname = "Balmer" }; - session.Save(bill); - session.Save(steve); + await session.SaveAsync(bill); + await session.SaveAsync(steve); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var queryIndex = session.QueryIndex(x => x.SomeName == "Bill"); @@ -6214,7 +6174,7 @@ public async Task ShouldParseNamedTermQuery() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var billsArticle = new Article { @@ -6228,13 +6188,13 @@ public async Task ShouldParseNamedTermQuery() PublishedUtc = DateTime.UtcNow }; - session.Save(billsArticle); - session.Save(stevesArticle); + await session.SaveAsync(billsArticle); + await session.SaveAsync(stevesArticle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var filter = "title:steve"; @@ -6267,7 +6227,7 @@ public async Task ShouldParseDefaultTermQuery(string search) { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var billsArticle = new Article { @@ -6281,13 +6241,13 @@ public async Task ShouldParseDefaultTermQuery(string search) PublishedUtc = DateTime.UtcNow }; - session.Save(billsArticle); - session.Save(stevesArticle); + await session.SaveAsync(billsArticle); + await session.SaveAsync(stevesArticle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var filterQuery = session.Query
(); @@ -6321,7 +6281,7 @@ public async Task ShouldParseOrQuery() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var billsArticle = new Article { @@ -6335,13 +6295,13 @@ public async Task ShouldParseOrQuery() PublishedUtc = DateTime.UtcNow }; - session.Save(billsArticle); - session.Save(stevesArticle); + await session.SaveAsync(billsArticle); + await session.SaveAsync(stevesArticle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // boolean OR "title:(bill OR post)" var filter = "title:bill post"; @@ -6378,7 +6338,7 @@ public async Task ShouldParseAndQuery() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var billsArticle = new Article { @@ -6392,13 +6352,13 @@ public async Task ShouldParseAndQuery() PublishedUtc = DateTime.UtcNow }; - session.Save(billsArticle); - session.Save(stevesArticle); + await session.SaveAsync(billsArticle); + await session.SaveAsync(stevesArticle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // boolean AND "title:(bill AND rabbits)" var filter = "title:bill AND rabbits"; @@ -6436,7 +6396,7 @@ public async Task ShouldParseTwoNamedTermQuerys() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var billsArticle = new Article { @@ -6450,13 +6410,13 @@ public async Task ShouldParseTwoNamedTermQuerys() PublishedUtc = DateTime.UtcNow }; - session.Save(billsArticle); - session.Save(stevesArticle); + await session.SaveAsync(billsArticle); + await session.SaveAsync(stevesArticle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var filter = "title:article title:article"; var filterQuery = session.Query
(); @@ -6493,7 +6453,7 @@ public async Task ShouldParseComplexQuery() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var beachLizardsArticle = new Article { @@ -6507,13 +6467,13 @@ public async Task ShouldParseComplexQuery() PublishedUtc = DateTime.UtcNow }; - session.Save(beachLizardsArticle); - session.Save(mountainArticle); + await session.SaveAsync(beachLizardsArticle); + await session.SaveAsync(mountainArticle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var filter = "title:(beach AND sand) OR (mountain AND lake)"; var filterQuery = session.Query
(); @@ -6556,7 +6516,7 @@ public async Task ShouldParseNotComplexQuery() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var beachLizardsArticle = new Article { @@ -6576,14 +6536,14 @@ public async Task ShouldParseNotComplexQuery() PublishedUtc = DateTime.UtcNow }; - session.Save(beachLizardsArticle); - session.Save(sandcastlesArticle); - session.Save(mountainArticle); + await session.SaveAsync(beachLizardsArticle); + await session.SaveAsync(sandcastlesArticle); + await session.SaveAsync(mountainArticle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { // boolean : ((beach AND sand) OR (mountain AND lake)) NOT lizards var filter = "title:((beach AND sand) OR (mountain AND lake)) NOT lizards"; @@ -6630,7 +6590,7 @@ public async Task ShouldParseNotBooleanQuery() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var billsArticle = new Article { @@ -6650,14 +6610,14 @@ public async Task ShouldParseNotBooleanQuery() PublishedUtc = DateTime.UtcNow }; - session.Save(billsArticle); - session.Save(stevesArticle); - session.Save(paulsArticle); + await session.SaveAsync(billsArticle); + await session.SaveAsync(stevesArticle); + await session.SaveAsync(paulsArticle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var filter = "title:NOT steve"; var filterQuery = session.Query
(); @@ -6694,7 +6654,7 @@ public async Task ShouldParseNotQueryWithOrder() { _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var billsArticle = new Article { @@ -6714,14 +6674,14 @@ public async Task ShouldParseNotQueryWithOrder() PublishedUtc = DateTime.UtcNow }; - session.Save(billsArticle); - session.Save(stevesArticle); - session.Save(paulsArticle); + await session.SaveAsync(billsArticle); + await session.SaveAsync(stevesArticle); + await session.SaveAsync(paulsArticle); await session.SaveChangesAsync(); } - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var filter = "title:about NOT steve"; var filterQuery = session.Query
(); @@ -6741,7 +6701,7 @@ public async Task ShouldParseNotQueryWithOrder() await parsed.ExecuteAsync(filterQuery); - // Order queries can be placed anywhere inside the booleans and they still get processed fine. + // Order queries can be placed anywhere inside the boolean and they still get processed fine. var yesSqlQuery = session.Query().For
() .All( x => x.With(x => x.Title.IsNotIn(s => s.Title, w => w.Title.Contains("steve"))).OrderByDescending(x => x.Title) diff --git a/test/YesSql.Tests/MySqlTests.cs b/test/YesSql.Tests/MySqlTests.cs index c733c1bb..d1a4b62b 100644 --- a/test/YesSql.Tests/MySqlTests.cs +++ b/test/YesSql.Tests/MySqlTests.cs @@ -49,16 +49,16 @@ public async Task ForeignKeyOfIndexesMustBe_DeleteCascated() Lastname = "Gates" }; - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { - session.Save(bill); + await session.SaveAsync(bill); await session.SaveChangesAsync(); } // second store, don't register the index _store = await StoreFactory.CreateAndInitializeAsync(configuration); - using (var session = _store.CreateSession()) + await using (var session = _store.CreateSession()) { var person = await session.Query().For().FirstOrDefaultAsync(); Assert.NotNull(person); @@ -70,214 +70,178 @@ public async Task ForeignKeyOfIndexesMustBe_DeleteCascated() [Fact] public async Task ThrowsWhenIndexKeyLengthExceeded() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); - - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - builder - .DropMapIndexTable(); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(769)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(768)) - ); + await builder.DropMapIndexTableAsync(); - Assert.Throws(() => builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name"))); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(769)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(768)) + ); - } - } + await Assert.ThrowsAsync(async () => + { + await builder.AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name") + ); + }); } [Fact] public async Task ShouldCreatePropertyIndexWithSpecifiedLength() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); - - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); - - builder - .DropMapIndexTable(); - - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(769)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(768)) - ); - - // 300 + 468 = 768 which is the max allowed by MySQL. - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name(300)", "Location (468)")); - - transaction.Commit(); - } - } + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); + + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); + + await builder.DropMapIndexTableAsync(); + + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(769)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(768)) + ); + + // 300 + 468 = 768 which is the max allowed by MySQL. + await builder.AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name(300)", "Location (468)") + ); + + await transaction.CommitAsync(); } [Fact] public async Task ThrowsWhenIndexKeysWithBitsLengthExceeded() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); + + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); + + await builder.DropMapIndexTableAsync(); + + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(384)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(384)) + ); + + await Assert.ThrowsAsync(async () => { - await connection.OpenAsync(); - - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); - - builder - .DropMapIndexTable(); - - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(384)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(384)) - ); - - Assert.Throws(() => builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied", "Location"))); - } - } + await builder.AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied", "Location")); + }); } [Fact] public async Task ThrowsWhenIndexKeysLengthExceeded() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); - - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); - - builder - .DropMapIndexTable(); - - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(385)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(384)) - ); - - Assert.Throws(() => builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "Location"))); - } - } + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); + + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); + + await builder.DropMapIndexTableAsync(); + + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(385)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(384)) + ); + + await Assert.ThrowsAsync(async () => await builder + .AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "Location"))); } [Fact] public async Task ShouldCreatePropertyIndexWithMaxKey() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder.DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(768)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(768)) - ); + await builder.CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(768)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(768)) + ); - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name")); + await builder.AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name")); - transaction.Commit(); - } - } + await transaction.CommitAsync(); } [Fact] public async Task ShouldCreateIndexPropertyWithMaxKeys() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder.DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(384)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(384)) - ); + await builder + .CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(384)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(384)) + ); - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "Location")); + await builder + .AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "Location")); - transaction.Commit(); - } - } + await transaction.CommitAsync(); } [Fact] public async Task ShouldCreateIndexPropertyWithMaxBitKeys() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder + .DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(767)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(384)) - ); + await builder + .CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(767)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(384)) + ); - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied")); + await builder + .AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied")); - transaction.Commit(); - } - } + await transaction.CommitAsync(); } [Fact] @@ -285,32 +249,30 @@ public async Task ShouldCreateHashedIndexKeyName() { await _store.InitializeCollectionAsync("LongCollection"); - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) + { + var builder = new SchemaBuilder(_store.Configuration, transaction); - // tpFK_LongCollection_PersonsByNameCol_LongCollection_Document_Id : 64 chars. Throws exception if not hashed. + // tpFK_LongCollection_PersonsByNameCol_LongCollection_Document_Id : 64 chars. Throws exception if not hashed. - builder.CreateReduceIndexTable(column => column - .Column(nameof(PersonsByNameCol.Name)) - .Column(nameof(PersonsByNameCol.Count)), - "LongCollection" - ); + await builder.CreateReduceIndexTableAsync(column => column + .Column(nameof(PersonsByNameCol.Name)) + .Column(nameof(PersonsByNameCol.Count)), + "LongCollection" + ); - transaction.Commit(); - } + await transaction.CommitAsync(); + } - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) + { + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder.DropReduceIndexTable("LongCollection"); - transaction.Commit(); - } + await builder.DropReduceIndexTableAsync("LongCollection"); + await transaction.CommitAsync(); } } } diff --git a/test/YesSql.Tests/PostgreSqlTests.cs b/test/YesSql.Tests/PostgreSqlTests.cs index fe4318f5..8f256613 100644 --- a/test/YesSql.Tests/PostgreSqlTests.cs +++ b/test/YesSql.Tests/PostgreSqlTests.cs @@ -41,51 +41,50 @@ public override Task ShouldReadUncommittedRecords() [Fact] public async Task ShouldIndexPropertyKeys() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) { - new SchemaBuilder(_store.Configuration, transaction) - .DropMapIndexTable(); + var builder = new SchemaBuilder(_store.Configuration, transaction); + + await builder.DropMapIndexTableAsync(); - transaction.Commit(); + await transaction.CommitAsync(); } - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) { var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .CreateMapIndexTable(column => column + await builder + .CreateMapIndexTableAsync(column => column .Column(nameof(PropertyIndex.Name), col => col.WithLength(4000)) .Column(nameof(PropertyIndex.ForRent)) .Column(nameof(PropertyIndex.IsOccupied)) .Column(nameof(PropertyIndex.Location), col => col.WithLength(4000)) ); - builder - .AlterTable(nameof(PropertyIndex), table => table + await builder + .AlterTableAsync(nameof(PropertyIndex), table => table .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied", "Location")); - transaction.Commit(); + await transaction.CommitAsync(); } } _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var property = new Property { - var property = new Property - { - Name = new string('*', 4000), - IsOccupied = true, - ForRent = true, - Location = new string('*', 4000) - }; + Name = new string('*', 4000), + IsOccupied = true, + ForRent = true, + Location = new string('*', 4000) + }; - session.Save(property); - } + await session.SaveAsync(property); } [Fact] @@ -95,30 +94,28 @@ public async Task ShouldCreateHashedIndexKeyName() // This will cause exceptions in other tables when the 'short' key is truncated again. await _store.InitializeCollectionAsync("LongCollection"); - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) - { - await connection.OpenAsync(); + await using var connection = _store.Configuration.ConnectionFactory.CreateConnection(); + await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) + { + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder.CreateReduceIndexTable(column => column - .Column(nameof(PersonsByNameCol.Name)) - .Column(nameof(PersonsByNameCol.Count)), - "LongCollection" - ); + await builder.CreateReduceIndexTableAsync(column => column + .Column(nameof(PersonsByNameCol.Name)) + .Column(nameof(PersonsByNameCol.Count)), + "LongCollection" + ); - transaction.Commit(); - } + await transaction.CommitAsync(); + } - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using (var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel)) + { + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder.DropReduceIndexTable("LongCollection"); - transaction.Commit(); - } + await builder.DropReduceIndexTableAsync("LongCollection"); + await transaction.CommitAsync(); } } } diff --git a/test/YesSql.Tests/SqlServerTests.cs b/test/YesSql.Tests/SqlServerTests.cs index 116cf142..face7197 100644 --- a/test/YesSql.Tests/SqlServerTests.cs +++ b/test/YesSql.Tests/SqlServerTests.cs @@ -35,28 +35,26 @@ public async Task ShouldSeedExistingIds() { var configuration = new Configuration().UseSqlServer(ConnectionStringBuilder.ConnectionString, "BobaFett").SetTablePrefix("Store1").UseBlockIdGenerator(); - using (var connection = configuration.ConnectionFactory.CreateConnection()) + await using (var connection = configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction()) - { - var builder = new SchemaBuilder(configuration, transaction, throwOnError: false); + await using var transaction = await connection.BeginTransactionAsync(); + var builder = new SchemaBuilder(configuration, transaction, throwOnError: false); - builder.DropTable(configuration.TableNameConvention.GetDocumentTable("")); - builder.DropTable("Identifiers"); + await builder.DropTableAsync(configuration.TableNameConvention.GetDocumentTable("")); + await builder.DropTableAsync("Identifiers"); - transaction.Commit(); - } + await transaction.CommitAsync(); } var store1 = await StoreFactory.CreateAndInitializeAsync(configuration); - using (var session1 = store1.CreateSession()) + await using (var session1 = store1.CreateSession()) { var p1 = new Person { Firstname = "Bill" }; - session1.Save(p1); + await session1.SaveAsync(p1); Assert.Equal(1, p1.Id); @@ -65,15 +63,12 @@ public async Task ShouldSeedExistingIds() var store2 = await StoreFactory.CreateAndInitializeAsync(new Configuration().UseSqlServer(ConnectionStringBuilder.ConnectionString, "BobaFett").SetTablePrefix("Store1").UseBlockIdGenerator()); - using (var session2 = store2.CreateSession()) - { - var p2 = new Person { Firstname = "Bill" }; + await using var session2 = store2.CreateSession(); + var p2 = new Person { Firstname = "Bill" }; - session2.Save(p2); + await session2.SaveAsync(p2); - Assert.Equal(21, p2.Id); - - } + Assert.Equal(21, p2.Id); } [Theory] @@ -83,19 +78,17 @@ public async Task ShouldGenerateIdsWithConcurrentStores(string collection) { var configuration = new Configuration().UseSqlServer(ConnectionStringBuilder.ConnectionString, "BobaFett").SetTablePrefix("Store1").UseBlockIdGenerator(); - using (var connection = configuration.ConnectionFactory.CreateConnection()) + await using (var connection = configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(configuration, transaction, throwOnError: false); + await using var transaction = await connection.BeginTransactionAsync(configuration.IsolationLevel); + var builder = new SchemaBuilder(configuration, transaction, throwOnError: false); - builder.DropTable(configuration.TableNameConvention.GetDocumentTable("")); - builder.DropTable("Identifiers"); + await builder.DropTableAsync(configuration.TableNameConvention.GetDocumentTable("")); + await builder.DropTableAsync("Identifiers"); - transaction.Commit(); - } + await transaction.CommitAsync(); } var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1)); @@ -114,7 +107,7 @@ public async Task ShouldGenerateIdsWithConcurrentStores(string collection) while (!cts.IsCancellationRequested) { - lastId = taskId = store1.Configuration.IdGenerator.GetNextId(collection); + lastId = taskId = await store1.Configuration.IdGenerator.GetNextIdAsync(collection); if (taskId > MaxTransactions) { @@ -136,31 +129,29 @@ public async Task ShouldGenerateIdsWithConcurrentStores(string collection) [Fact] public async Task ThrowsWhenIndexKeyLengthExceeded() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder + .DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) - ); + await builder + .CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) + ); - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name")); + await builder + .AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name")); - transaction.Commit(); - } + await transaction.CommitAsync(); } _store.RegisterIndexes(); @@ -174,13 +165,14 @@ public async Task ThrowsWhenIndexKeyLengthExceeded() // Maximum length of standard nonclustered index column is 1700 bytes 850 * 2 = 1700 Name = new string('*', 851) }; - session.Save(property); + await session.SaveAsync(property); } finally { if (session != null) { - await Assert.ThrowsAsync(async () => await session.SaveChangesAsync()); + await Assert.ThrowsAsync(session.SaveChangesAsync); + await session.DisposeAsync(); } } } @@ -188,30 +180,28 @@ public async Task ThrowsWhenIndexKeyLengthExceeded() [Fact] public async Task ThrowsWhenIndexKeysWithBitsLengthExceeded() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder + .DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) - ); + await builder + .CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) + ); - builder.AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied")); + await builder.AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied")); - transaction.Commit(); - } + await transaction.CommitAsync(); } _store.RegisterIndexes(); @@ -227,13 +217,14 @@ public async Task ThrowsWhenIndexKeysWithBitsLengthExceeded() ForRent = true, IsOccupied = true }; - session.Save(property); + await session.SaveAsync(property); } finally { if (session != null) { - await Assert.ThrowsAsync(async () => await session.SaveChangesAsync()); + await Assert.ThrowsAsync(session.SaveChangesAsync); + await session.DisposeAsync(); } } } @@ -241,31 +232,29 @@ public async Task ThrowsWhenIndexKeysWithBitsLengthExceeded() [Fact] public async Task ThrowsWhenIndexKeysLengthExceeded() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder + .DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) - ); + await builder + .CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) + ); - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "Location")); + await builder + .AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "Location")); - transaction.Commit(); - } + await transaction.CommitAsync(); } _store.RegisterIndexes(); @@ -280,13 +269,14 @@ public async Task ThrowsWhenIndexKeysLengthExceeded() Name = new string('*', 425), Location = new string('*', 426), // Max length + 2 bytes }; - session.Save(property); + await session.SaveAsync(property); } finally { if (session != null) { - await Assert.ThrowsAsync(async () => await session.SaveChangesAsync()); + await Assert.ThrowsAsync(session.SaveChangesAsync); + await session.DisposeAsync(); } } } @@ -294,138 +284,133 @@ public async Task ThrowsWhenIndexKeysLengthExceeded() [Fact] public async Task ShouldIndexPropertyKey() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + try { var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder + .DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column + await builder + .CreateMapIndexTableAsync(column => column .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) .Column(nameof(PropertyIndex.ForRent)) .Column(nameof(PropertyIndex.IsOccupied)) .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) ); - builder - .AlterTable(nameof(PropertyIndex), table => table + await builder + .AlterTableAsync(nameof(PropertyIndex), table => table .CreateIndex("IDX_Property", "Name")); - transaction.Commit(); + await transaction.CommitAsync(); + } + catch + { + await transaction.RollbackAsync(); } } _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var property = new Property { - var property = new Property - { - // Maximum length of standard nonclustered index is 1700 bytes 850 * 2 = 1700 - Name = new string('*', 850) - }; + // Maximum length of standard nonclustered index is 1700 bytes 850 * 2 = 1700 + Name = new string('*', 850) + }; - session.Save(property); - } + await session.SaveAsync(property); } [Fact] public async Task ShouldIndexPropertyKeys() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder + .DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) - ); + await builder + .CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) + ); - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "Location")); + await builder + .AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "Location")); - transaction.Commit(); - } + await transaction.CommitAsync(); } _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var property = new Property { - var property = new Property - { - // Maximum length of standard nonclustered index is 1700 bytes 850 / 2 = 425 - Name = new string('*', 425), - Location = new string('*', 425) - }; + // Maximum length of standard nonclustered index is 1700 bytes 850 / 2 = 425 + Name = new string('*', 425), + Location = new string('*', 425) + }; - session.Save(property); - } + await session.SaveAsync(property); } [Fact] public async Task ShouldIndexPropertyKeysWithBits() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder + .DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) - ); + await builder + .CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(1000)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(1000)) + ); - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied", "Location")); + await builder + .AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied", "Location")); - transaction.Commit(); - } + await transaction.CommitAsync(); } _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var property = new Property { - var property = new Property - { - // Maximum length of standard nonclustered index is 1700 bytes 850 * 2 = 1700 - Name = new string('*', 425), - IsOccupied = true, - ForRent = true, - Location = new string('*', 424) - }; - - session.Save(property); - } + // Maximum length of standard nonclustered index is 1700 bytes 850 * 2 = 1700 + Name = new string('*', 425), + IsOccupied = true, + ForRent = true, + Location = new string('*', 424) + }; + + await session.SaveAsync(property); } } } diff --git a/test/YesSql.Tests/SqliteTests.cs b/test/YesSql.Tests/SqliteTests.cs index a9309f8a..d6442ee5 100644 --- a/test/YesSql.Tests/SqliteTests.cs +++ b/test/YesSql.Tests/SqliteTests.cs @@ -46,14 +46,14 @@ public override Task ShouldReadCommittedRecords() return base.ShouldReadCommittedRecords(); } -// [Theory(Skip = "Sqlite doesn't use DbBlockIdGenerator")] -// [InlineData(100)] -//#pragma warning disable xUnit1026 // Theory methods should use all of their parameters -// public override Task ShouldGenerateLongIds(long id) -//#pragma warning restore xUnit1026 // Theory methods should use all of their parameters -// { -// return Task.CompletedTask; -// } + // [Theory(Skip = "Sqlite doesn't use DbBlockIdGenerator")] + // [InlineData(100)] + //#pragma warning disable xUnit1026 // Theory methods should use all of their parameters + // public override Task ShouldGenerateLongIds(long id) + //#pragma warning restore xUnit1026 // Theory methods should use all of their parameters + // { + // return Task.CompletedTask; + // } [Fact(Skip = "Sqlite doesn't support concurrent writers")] public override Task ShouldReadUncommittedRecords() @@ -70,11 +70,11 @@ public async Task ShouldSeedExistingIds() var store1 = await StoreFactory.CreateAndInitializeAsync(new Configuration().UseSqLite(connectionString).SetTablePrefix(TablePrefix).UseDefaultIdGenerator()); - using (var session1 = store1.CreateSession()) + await using (var session1 = store1.CreateSession()) { var p1 = new Person { Firstname = "Bill" }; - session1.Save(p1); + await session1.SaveAsync(p1); Assert.Equal(1, p1.Id); @@ -83,14 +83,12 @@ public async Task ShouldSeedExistingIds() var store2 = await StoreFactory.CreateAndInitializeAsync(new Configuration().UseSqLite(connectionString).SetTablePrefix(TablePrefix).UseDefaultIdGenerator()); - using (var session2 = store2.CreateSession()) - { - var p2 = new Person { Firstname = "Bill" }; + await using var session2 = store2.CreateSession(); + var p2 = new Person { Firstname = "Bill" }; - session2.Save(p2); + await session2.SaveAsync(p2); - Assert.Equal(2, p2.Id); - } + Assert.Equal(2, p2.Id); } } @@ -103,47 +101,43 @@ public override Task ShouldHandleConcurrency() [Fact] public async Task ShouldIndexPropertyKeys() { - using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) + await using (var connection = _store.Configuration.ConnectionFactory.CreateConnection()) { await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel)) - { - var builder = new SchemaBuilder(_store.Configuration, transaction); + await using var transaction = await connection.BeginTransactionAsync(_store.Configuration.IsolationLevel); + var builder = new SchemaBuilder(_store.Configuration, transaction); - builder - .DropMapIndexTable(); + await builder + .DropMapIndexTableAsync(); - builder - .CreateMapIndexTable(column => column - .Column(nameof(PropertyIndex.Name), col => col.WithLength(4000)) - .Column(nameof(PropertyIndex.ForRent)) - .Column(nameof(PropertyIndex.IsOccupied)) - .Column(nameof(PropertyIndex.Location), col => col.WithLength(4000)) - ); + await builder + .CreateMapIndexTableAsync(column => column + .Column(nameof(PropertyIndex.Name), col => col.WithLength(4000)) + .Column(nameof(PropertyIndex.ForRent)) + .Column(nameof(PropertyIndex.IsOccupied)) + .Column(nameof(PropertyIndex.Location), col => col.WithLength(4000)) + ); - builder - .AlterTable(nameof(PropertyIndex), table => table - .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied", "Location")); + await builder + .AlterTableAsync(nameof(PropertyIndex), table => table + .CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied", "Location")); - transaction.Commit(); - } + await transaction.CommitAsync(); } _store.RegisterIndexes(); - using (var session = _store.CreateSession()) + await using var session = _store.CreateSession(); + var property = new Property { - var property = new Property - { - Name = new string('*', 4000), - IsOccupied = true, - ForRent = true, - Location = new string('*', 4000) - }; + Name = new string('*', 4000), + IsOccupied = true, + ForRent = true, + Location = new string('*', 4000) + }; - session.Save(property); - } + await session.SaveAsync(property); } } }