diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 669f038..0104706 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,10 @@ jobs: run: dotnet build --configuration Release /p:Version=${VERSION_NUMBER} - name: Test - run: dotnet test --configuration Release /p:Version=${VERSION_NUMBER} --no-build + run: | + dotnet test --configuration Release /p:Version=${VERSION_NUMBER} --no-build + # replace VERSION_NUMBER in docs/docs.config.json with ${VERSION_NUMBER} + sed -i "s/VERSION_NUMBER/${VERSION_NUMBER}/g" docs/docs.config.json - name: Pack run: dotnet pack --configuration Release /p:Version=${VERSION_NUMBER} --no-build --output nupkgs @@ -34,4 +37,24 @@ jobs: - name: Push run: dotnet nuget push nupkgs/${PACKAGE_ID}.${VERSION_NUMBER}.nupkg env: - PACKAGE_ID: "DapperMatic" + PACKAGE_ID: "MJCZone.DapperMatic" + + - name: Upload Pages Artifact + uses: actions/upload-pages-artifact@v3 + with: + path: docs/ + + # Deploy to GitHub Pages + deploy: + needs: build + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index 2d443d3..90f4712 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ *.userosscache *.sln.docstates __delete/ +nuget.config # DocFx generated files docs/**/toc.yml diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..595b706 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "files.associations": { + "*.vue": "html" + }, + "vetur.validation.template": false, + "vetur.validation.script": false, + "vetur.validation.style": false +} diff --git a/DapperMatic.sln b/MJCZone.DapperMatic.sln similarity index 83% rename from DapperMatic.sln rename to MJCZone.DapperMatic.sln index ef2938d..431e75d 100644 --- a/DapperMatic.sln +++ b/MJCZone.DapperMatic.sln @@ -5,11 +5,11 @@ VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{80E77F84-7DB0-4CBF-9E43-4A6E9F1758B2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DapperMatic", "src\DapperMatic\DapperMatic.csproj", "{48C04108-798F-4CED-8874-D146500778EB}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MJCZone.DapperMatic", "src\MJCZone.DapperMatic\MJCZone.DapperMatic.csproj", "{48C04108-798F-4CED-8874-D146500778EB}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{C1CEAB9E-CD38-4AA7-B004-B0248F7C39A7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DapperMatic.Tests", "tests\DapperMatic.Tests\DapperMatic.Tests.csproj", "{9FF5A12B-6617-4492-9BD0-434C58051054}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MJCZone.DapperMatic.Tests", "tests\MJCZone.DapperMatic.Tests\MJCZone.DapperMatic.Tests.csproj", "{9FF5A12B-6617-4492-9BD0-434C58051054}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Files", "Solution Files", "{93285C01-B819-4C94-8A18-0CCC817EB3EE}" ProjectSection(SolutionItems) = preProject diff --git a/README.md b/README.md index 681f00e..9a46b38 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ -# DapperMatic +# MJCZone.DapperMatic -[![.github/workflows/release.yml](https://github.com/mjczone/DapperMatic/actions/workflows/release.yml/badge.svg)](https://github.com/mjczone/DapperMatic/actions/workflows/release.yml) +[![.github/workflows/release.yml](https://github.com/mjczone/MJCZone.DapperMatic/actions/workflows/release.yml/badge.svg)](https://github.com/mjczone/MJCZone.DapperMatic/actions/workflows/release.yml) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) Additional extensions leveraging Dapper -- [DapperMatic](#dappermatic) +- [MJCZone.DapperMatic](#dappermatic) - [Method Providers](#method-providers) - [Built-in Providers](#built-in-providers) - [Custom Providers](#custom-providers) @@ -55,12 +55,12 @@ public class CentipedeDbConnection: System.Data.Common.DbConnection // ... } -public class CentipedeDbMethods: DapperMatic.Interfaces.IDatabaseMethods +public class CentipedeDbMethods: MJCZone.DapperMatic.Interfaces.IDatabaseMethods { // ... } -public class CentipedeDbMethodsFactory : DapperMatic.Providers.DatabaseMethodsFactoryBase +public class CentipedeDbMethodsFactory : MJCZone.DapperMatic.Providers.DatabaseMethodsFactoryBase { public override bool SupportsConnection(IDbConnection db) => connection.GetType().Name == nameof(CentipedeDbConnection); @@ -79,7 +79,7 @@ DatabaseMethodsProvider.RegisterFactory("CentipedeDb", new PestControl.Foundry.C ### Extending an existing Provider Factory You may want to use a library that wraps an existing `IDbConnection` (e.g., ProfiledDbConnection with MiniProfiler). In that case, you can simply extend -a built-in factory and register your new factory implementation with DapperMatic. +a built-in factory and register your new factory implementation with MJCZone.DapperMatic. Your factory class would like like this. @@ -103,37 +103,37 @@ DatabaseMethodsProvider.RegisterFactory( The test suite uses this method to profile the database and output sql exception details to the unit testing logs. -See it in action with the [ProfiledPostgreSqlMethodsFactory](./tests/DapperMatic.Tests/ProviderTests/PostgreSqlDatabaseMethodsTests.cs#L84) class. This factory class demonstrates using a custom `IDbConnection` type `DbQueryLogging.LoggedDbConnection` from the `DbQueryLogging` package. Similar factory classes exist for the other providers. +See it in action with the [ProfiledPostgreSqlMethodsFactory](./tests/MJCZone.DapperMatic.Tests/ProviderTests/PostgreSqlDatabaseMethodsTests.cs#L84) class. This factory class demonstrates using a custom `IDbConnection` type `DbQueryLogging.LoggedDbConnection` from the `DbQueryLogging` package. Similar factory classes exist for the other providers. ## Models -- [DxCheckConstraint](src/DapperMatic/Models/DxCheckConstraint.cs) -- [DxColumn](src/DapperMatic/Models/DxColumn.cs) -- [DxColumnOrder](src/DapperMatic/Models/DxColumnOrder.cs) -- [DxConstraint](src/DapperMatic/Models/DxConstraint.cs) -- [DxConstraintType](src/DapperMatic/Models/DxConstraintType.cs) -- [DxDefaultConstraint](src/DapperMatic/Models/DxDefaultConstraint.cs) -- [DxForeignKeyAction](src/DapperMatic/Models/DxForeignKeyAction.cs) -- [DxForeignKeyContraint](src/DapperMatic/Models/DxForeignKeyContraint.cs) -- [DxIndex](src/DapperMatic/Models/DxIndex.cs) -- [DxOrderedColumn](src/DapperMatic/Models/DxOrderedColumn.cs) -- [DxPrimaryKeyConstraint](src/DapperMatic/Models/DxPrimaryKeyConstraint.cs) -- [DxTable](src/DapperMatic/Models/DxTable.cs) -- [DxUniqueConstraint](src/DapperMatic/Models/DxUniqueConstraint.cs) -- [DxView](src/DapperMatic/Models/DxView.cs) +- [DmCheckConstraint](src/MJCZone.DapperMatic/Models/DmCheckConstraint.cs) +- [DmColumn](src/MJCZone.DapperMatic/Models/DmColumn.cs) +- [DmColumnOrder](src/MJCZone.DapperMatic/Models/DmColumnOrder.cs) +- [DmConstraint](src/MJCZone.DapperMatic/Models/DmConstraint.cs) +- [DmConstraintType](src/MJCZone.DapperMatic/Models/DmConstraintType.cs) +- [DmDefaultConstraint](src/MJCZone.DapperMatic/Models/DmDefaultConstraint.cs) +- [DmForeignKeyAction](src/MJCZone.DapperMatic/Models/DmForeignKeyAction.cs) +- [DmForeignKeyConstraint](src/MJCZone.DapperMatic/Models/DmForeignKeyConstraint.cs) +- [DmIndex](src/MJCZone.DapperMatic/Models/DmIndex.cs) +- [DmOrderedColumn](src/MJCZone.DapperMatic/Models/DmOrderedColumn.cs) +- [DmPrimaryKeyConstraint](src/MJCZone.DapperMatic/Models/DmPrimaryKeyConstraint.cs) +- [DmTable](src/MJCZone.DapperMatic/Models/DmTable.cs) +- [DmUniqueConstraint](src/MJCZone.DapperMatic/Models/DmUniqueConstraint.cs) +- [DmView](src/MJCZone.DapperMatic/Models/DmView.cs) ### Model related factory methods -- [DxTableFactory](src/DapperMatic/Models/DxTableFactory.cs) +- [DmTableFactory](src/MJCZone.DapperMatic/Models/DmTableFactory.cs) ```cs -DxTable table = DxTableFactory.GetTable(typeof(app_employees)) +DmTable table = DmTableFactory.GetTable(typeof(app_employees)) ``` -- [DxViewFactory](src/DapperMatic/Models/DxViewFactory.cs) +- [DmViewFactory](src/MJCZone.DapperMatic/Models/DmViewFactory.cs) ```cs -DxView view = DxViewFactory.GetView(typeof(vw_onboarded_employees)) +DmView view = DmViewFactory.GetView(typeof(vw_onboarded_employees)) ``` ## `IDbConnection` CRUD extension methods @@ -179,7 +179,7 @@ var (/* Type */ dotnetType, /* int? */ length, /* int? */ precision, /* int? */ // Normalize a database name identifier to some idiomatic standard, namely alpha numeric with underscores and without spaces var normalizedName = db.NormalizeName(name); -// Get the last sql executed inside DapperMatic +// Get the last sql executed inside MJCZone.DapperMatic var lastSql = db.GetLastSql(); (string sql, object? parameters) lastSqlWithParams = db.GetLastSqlWithParms(); ``` @@ -216,24 +216,24 @@ using var tx = db.BeginTransaction(); bool exists = await db.DoesTableExistAsync("app","app_employees", tx, cancellationToken).ConfigureAwait(false) // CREATE: Create a database table -bool created = await db.CreateTableIfNotExistsAsync("app", /* DxTable */ table); +bool created = await db.CreateTableIfNotExistsAsync("app", /* DmTable */ table); // or created = await db.CreateTableIfNotExistsAsync( "app", "app_employees", - // DxColumn[] columns, + // DmColumn[] columns, columns, - // DxPrimaryKeyConstraint? primaryKey = null, + // DmPrimaryKeyConstraint? primaryKey = null, primaryKey, - // DxCheckConstraint[]? checkConstraints = null, + // DmCheckConstraint[]? checkConstraints = null, checkConstraints, - // DxDefaultConstraint[]? defaultConstraints = null, + // DmDefaultConstraint[]? defaultConstraints = null, defaultConstraints, - // DxUniqueConstraint[]? uniqueConstraints = null, + // DmUniqueConstraint[]? uniqueConstraints = null, uniqueConstraints, - // DxForeignKeyConstraint[]? foreignKeyConstraints = null, + // DmForeignKeyConstraint[]? foreignKeyConstraints = null, foreignKeyConstraints, - // DxIndex[]? indexes = null, + // DmIndex[]? indexes = null, indexes, ... ); @@ -242,10 +242,10 @@ bool created = await db.CreateTableIfNotExistsAsync("app", /* DxTable */ table); List names = await db.GetTableNamesAsync("app", "app_*", ...); // GET: Retrieve tables -List tables = await db.GetTablesAsync("app", "app_*", ...); +List tables = await db.GetTablesAsync("app", "app_*", ...); // GET: Retrieve single table -DxTable? table = await db.GetTableAsync("app", "app_employees", ...); +DmTable? table = await db.GetTableAsync("app", "app_employees", ...); // DROP: Drop a database table bool dropped = await db.DropTableIfExistsAsync("app", "app_employees", ...); @@ -267,7 +267,7 @@ using var tx = db.BeginTransaction(); bool exists = await db.DoesColumnExistAsync("app", "app_employees", "title", tx, cancellationToken).ConfigureAwait(false) // CREATE: Create a table column -bool created = await db.CreateColumnIfNotExistsAsync("app", /* DxColumn */ column); +bool created = await db.CreateColumnIfNotExistsAsync("app", /* DmColumn */ column); // or created = await db.CreateColumnIfNotExistsAsync( "app", @@ -291,8 +291,8 @@ bool created = await db.CreateColumnIfNotExistsAsync("app", /* DxColumn */ colum isForeignKey: true, referencedTableName: (string?) "app_managers", referencedColumnName: (string?) "id", - onDelete: (DxForeignKeyAction?) DxForeignKeyAction.Cascade, - onUpdate: (DxForeignKeyAction?) DxForeignKeyAction.NoAction, + onDelete: (DmForeignKeyAction?) DmForeignKeyAction.Cascade, + onUpdate: (DmForeignKeyAction?) DmForeignKeyAction.NoAction, ... ); @@ -300,10 +300,10 @@ bool created = await db.CreateColumnIfNotExistsAsync("app", /* DxColumn */ colum List names = await db.GetColumnNamesAsync("app", "app_employees", "*title*", ...); // GET: Retrieve table columns -List tables = await db.GetColumnsAsync("app", "app_employees", "*title*", ...); +List tables = await db.GetColumnsAsync("app", "app_employees", "*title*", ...); // GET: Retrieve single table column -DxColumn? column = await db.GetColumnAsync("app", "app_employees", "title", ...); +DmColumn? column = await db.GetColumnAsync("app", "app_employees", "title", ...); // DROP: Drop a table column bool dropped = await db.DropColumnIfExistsAsync("app", "app_employees", "title", ...); @@ -327,7 +327,7 @@ bool exists = await db.DoesCheckConstraintExistAsync("app","app_employees", cons exists = await db.DoesCheckConstraintExistOnColumnAsync("app","app_employees", "age", tx, cancellationToken).ConfigureAwait(false) // CREATE: Create a check constraint -bool created = await db.CreateCheckConstraintIfNotExistsAsync("app", /* DxCheckConstraint */ checkConstraint); +bool created = await db.CreateCheckConstraintIfNotExistsAsync("app", /* DmCheckConstraint */ checkConstraint); // or created = await db.CreateCheckConstraintIfNotExistsAsync( "app", @@ -347,10 +347,10 @@ List names = await db.GetCheckConstraintNamesAsync("app", "app_employees string name = await db.GetCheckConstraintNameOnColumnAsync("app", "app_employees", "age", ...); // GET: Retrieve check constraints -List checkConstraints = await db.GetCheckConstraintsAsync("app", "app_employees", "ck_*", ...); +List checkConstraints = await db.GetCheckConstraintsAsync("app", "app_employees", "ck_*", ...); // GET: Retrieve single check constraint -DxCheckConstraint? checkConstraint = await db.GetCheckConstraintAsync("app", "app_employees", constraintName, ...); +DmCheckConstraint? checkConstraint = await db.GetCheckConstraintAsync("app", "app_employees", constraintName, ...); // GET: Retrieve single check constraint on column checkConstraint = await db.GetCheckConstraintOnColumnAsync("app", "app_employees", "age", ...); @@ -377,7 +377,7 @@ bool exists = await db.DoesDefaultConstraintExistAsync("app","app_employees", co exists = await db.DoesDefaultConstraintExistOnColumnAsync("app","app_employees", "age", tx, cancellationToken).ConfigureAwait(false) // CREATE: Create a default constraint -bool created = await db.CreateDefaultConstraintIfNotExistsAsync("app", /* DxDefaultConstraint */ defaultConstraint); +bool created = await db.CreateDefaultConstraintIfNotExistsAsync("app", /* DmDefaultConstraint */ defaultConstraint); // or created = await db.CreateDefaultConstraintIfNotExistsAsync( "app", @@ -397,10 +397,10 @@ List names = await db.GetDefaultConstraintNamesAsync("app", "app_employe string name = await db.GetDefaultConstraintNameOnColumnAsync("app", "app_employees", "age", ...); // GET: Retrieve default constraints -List defaultConstraints = await db.GetDefaultConstraintsAsync("app", "app_employees", "df*", ...); +List defaultConstraints = await db.GetDefaultConstraintsAsync("app", "app_employees", "df*", ...); // GET: Retrieve single default constraint -DxDefaultConstraint? defaultConstraint = await db.GetDefaultConstraintAsync("app", "app_employees", constraintName, ...); +DmDefaultConstraint? defaultConstraint = await db.GetDefaultConstraintAsync("app", "app_employees", constraintName, ...); // GET: Retrieve single default constraint on column defaultConstraint = await db.GetDefaultConstraintOnColumnAsync("app", "app_employees", "age", ...); @@ -427,21 +427,21 @@ bool exists = await db.DoesForeignKeyConstraintExistAsync("app","app_employees", exists = await db.DoesForeignKeyConstraintExistOnColumnAsync("app","app_employees", "manager_id", tx, cancellationToken).ConfigureAwait(false) // CREATE: Create a foreign key -bool created = await db.CreateForeignKeyConstraintIfNotExistsAsync("app", /* DxForeignKeyConstraint */ foreignKeyConstraint); +bool created = await db.CreateForeignKeyConstraintIfNotExistsAsync("app", /* DmForeignKeyConstraint */ foreignKeyConstraint); // or created = await db.CreateForeignKeyConstraintIfNotExistsAsync( "app", "app_employees", // string constraintName, constraintName, - // DxOrderedColumn[] sourceColumns, - [ new DxOrderedColumn("manager_id") ] + // DmOrderedColumn[] sourceColumns, + [ new DmOrderedColumn("manager_id") ] // string referencedTableName, "app_managers", - // DxOrderedColumn[] referencedColumns, - [ new DxOrderedColumn("id") ], - onDelete: DxForeignKeyAction.Cascade, - onUpdate: DxForeignKeyAction.NoAction, + // DmOrderedColumn[] referencedColumns, + [ new DmOrderedColumn("id") ], + onDelete: DmForeignKeyAction.Cascade, + onUpdate: DmForeignKeyAction.NoAction, ... ); @@ -452,10 +452,10 @@ List names = await db.GetForeignKeyConstraintNamesAsync("app", "app_empl string name = await db.GetForeignKeyConstraintNameOnColumnAsync("app", "app_employees", "manager_id", ...); // GET: Retrieve foreign keys -List foreignKeyConstraints = await db.GetForeignKeyConstraintsAsync("app", "app_employees", "fk_*", ...); +List foreignKeyConstraints = await db.GetForeignKeyConstraintsAsync("app", "app_employees", "fk_*", ...); // GET: Retrieve single foreign key -DxForeignKeyConstraint? foreignKeyConstraint = await db.GetForeignKeyConstraintAsync("app", "app_employees", constraintName, ...); +DmForeignKeyConstraint? foreignKeyConstraint = await db.GetForeignKeyConstraintAsync("app", "app_employees", constraintName, ...); // GET: Retrieve single foreign key on column foreignKeyConstraint = await db.GetForeignKeyConstraintOnColumnAsync("app", "app_employees", "manager_id", ...); @@ -482,15 +482,15 @@ bool exists = await db.DoesUniqueConstraintExistAsync("app","app_employees", uni exists = await db.DoesUniqueConstraintExistOnColumnAsync("app","app_employees", "email", tx, cancellationToken).ConfigureAwait(false) // CREATE: Create a unique constraint -bool created = await db.CreateUniqueConstraintIfNotExistsAsync("app", /* DxUniqueConstraint */ uniqueConstraint, ...); +bool created = await db.CreateUniqueConstraintIfNotExistsAsync("app", /* DmUniqueConstraint */ uniqueConstraint, ...); // or created = await db.CreateUniqueConstraintIfNotExistsAsync( "app", "app_employees", // string uniqueConstraintName, uniqueConstraintName, - // DxOrderedColumn[] columns, - [ new DxOrderedColumn("email", DxColumnOrder.Descending) ], + // DmOrderedColumn[] columns, + [ new DmOrderedColumn("email", DmColumnOrder.Descending) ], ... ); @@ -501,10 +501,10 @@ List names = await db.GetUniqueConstraintNamesAsync("app", "app_employee names = await db.GetUniqueConstraintNamesOnColumnAsync("app", "app_employees", "email", ...); // GET: Retrieve uniqueConstraints -List uniqueConstraints = await db.GetUniqueConstraintsAsync("app", "app_employees", "uc_*", ...); +List uniqueConstraints = await db.GetUniqueConstraintsAsync("app", "app_employees", "uc_*", ...); // GET: Retrieve single unique constraint -DxUniqueConstraint? uniqueConstraint = await db.GetUniqueConstraintAsync("app", "app_employees", uniqueConstraintName, ...); +DmUniqueConstraint? uniqueConstraint = await db.GetUniqueConstraintAsync("app", "app_employees", uniqueConstraintName, ...); // GET: Retrieve single unique constraint on column uniqueConstraint = await db.GetUniqueConstraintOnColumnAsync("app", "app_employees", "email", ...); @@ -531,15 +531,15 @@ bool exists = await db.DoesIndexExistAsync("app","app_employees", indexName, tx, exists = await db.DoesIndexExistOnColumnAsync("app","app_employees", "is_onboarded", tx, cancellationToken).ConfigureAwait(false) // CREATE: Create a index -bool created = await db.CreateIndexIfNotExistsAsync("app", /* DxIndex */ index); +bool created = await db.CreateIndexIfNotExistsAsync("app", /* DmIndex */ index); // or created = await db.CreateIndexIfNotExistsAsync( "app", "app_employees", // string indexName, indexName, - // DxOrderedColumn[] columns, - [ new DxOrderedColumn("is_onboarded", DxColumnOrder.Descending) ], + // DmOrderedColumn[] columns, + [ new DmOrderedColumn("is_onboarded", DmColumnOrder.Descending) ], isUnique: false, ... ); @@ -550,11 +550,11 @@ List names = await db.GetIndexNamesAsync("app", "app_employees", "ix_*", // GET: Retrieve index names on column names = await db.GetIndexNamesOnColumnAsync("app", "app_employees", "is_onboarded", ...); -// GET: Retrieve indexs -List indexes = await db.GetIndexesAsync("app", "app_employees", "ix_*", ...); +// GET: Retrieve indexes +List indexes = await db.GetIndexesAsync("app", "app_employees", "ix_*", ...); // GET: Retrieve single index -DxIndex? index = await db.GetIndexAsync("app", "app_employees", indexName, ...); +DmIndex? index = await db.GetIndexAsync("app", "app_employees", indexName, ...); // GET: Retrieve single index on column index = await db.GetIndexOnColumnAsync("app", "app_employees", "is_onboarded", ...); @@ -578,20 +578,20 @@ var primaryKeyConstraintName = ProviderUtils.GeneratePrimaryKeyConstraintName("a bool exists = await db.DoesPrimaryKeyConstraintExistAsync("app","app_employees", tx, cancellationToken).ConfigureAwait(false) // CREATE: Create a primary key constraint -bool created = await db.CreatePrimaryKeyConstraintIfNotExistsAsync("app", /* DxPrimaryKeyConstraint */ primaryKeyConstraint, ...); +bool created = await db.CreatePrimaryKeyConstraintIfNotExistsAsync("app", /* DmPrimaryKeyConstraint */ primaryKeyConstraint, ...); // or created = await db.CreatePrimaryKeyConstraintIfNotExistsAsync( "app", "app_employees", // string primaryKeyConstraintName, primaryKeyConstraintName, - // DxOrderedColumn[] columns, - [ new DxOrderedColumn("email", DxColumnOrder.Descending) ], + // DmOrderedColumn[] columns, + [ new DmOrderedColumn("email", DmColumnOrder.Descending) ], ... ); // GET: Retrieve single primary key constraint -DxPrimaryKeyConstraint? primaryKeyConstraint = await db.GetPrimaryKeyConstraintAsync("app", "app_employees", ...); +DmPrimaryKeyConstraint? primaryKeyConstraint = await db.GetPrimaryKeyConstraintAsync("app", "app_employees", ...); // DROP: Drop a primary key constraint bool dropped = await db.DropPrimaryKeyConstraintIfExistsAsync("app", "app_employees", primaryKeyConstraintName, ...); @@ -609,7 +609,7 @@ var viewName = "vw_employees_not_yet_onboarded"; bool exists = await db.DoesViewExistAsync("app", viewName, tx, cancellationToken).ConfigureAwait(false) // CREATE: Create a view -bool created = await db.CreateViewIfNotExistsAsync("app", /* DxView */ view, ...); +bool created = await db.CreateViewIfNotExistsAsync("app", /* DmView */ view, ...); // or created = await db.CreateViewIfNotExistsAsync( "app", @@ -634,10 +634,10 @@ bool updated = await db.CreateViewIfNotExistsAsync( List viewNames = await db.GetViewNames("app", "vw_*", ...); // GET: Retrieve single view -List views = await db.GetViewsAsync("app", "vw_*", ...); +List views = await db.GetViewsAsync("app", "vw_*", ...); // GET: Retrieve single view -DxView? view = await db.GetViewAsync("app", viewName, ...); +DmView? view = await db.GetViewAsync("app", viewName, ...); // DROP: Drop a view bool dropped = await db.DropViewIfExistsAsync("app", viewName, ...); diff --git a/docs/components/docs-drawer.vue b/docs/components/docs-drawer.vue new file mode 100644 index 0000000..8a880c4 --- /dev/null +++ b/docs/components/docs-drawer.vue @@ -0,0 +1,99 @@ + + + diff --git a/docs/components/docs-header.vue b/docs/components/docs-header.vue new file mode 100644 index 0000000..b3c27b0 --- /dev/null +++ b/docs/components/docs-header.vue @@ -0,0 +1,67 @@ + + diff --git a/docs/components/docs-layout.vue b/docs/components/docs-layout.vue new file mode 100644 index 0000000..c3a4f71 --- /dev/null +++ b/docs/components/docs-layout.vue @@ -0,0 +1,174 @@ + + + diff --git a/docs/components/pages/docs-content.vue b/docs/components/pages/docs-content.vue new file mode 100644 index 0000000..2ff5ce3 --- /dev/null +++ b/docs/components/pages/docs-content.vue @@ -0,0 +1,47 @@ + + + diff --git a/docs/components/pages/docs-package.vue b/docs/components/pages/docs-package.vue new file mode 100644 index 0000000..cb6e32c --- /dev/null +++ b/docs/components/pages/docs-package.vue @@ -0,0 +1,456 @@ + + + diff --git a/docs/content/404.md b/docs/content/404.md new file mode 100644 index 0000000..00562a5 --- /dev/null +++ b/docs/content/404.md @@ -0,0 +1,3 @@ +# 404 + +The requested page could not be found. diff --git a/docs/content/about.md b/docs/content/about.md new file mode 100644 index 0000000..cc11d5f --- /dev/null +++ b/docs/content/about.md @@ -0,0 +1,3 @@ +# About + +This project is sponsored by [MJCZone Inc.](https://www.mjczone.com), based in Tulsa, Oklahoma. diff --git a/docs/content/about/roadmap.md b/docs/content/about/roadmap.md new file mode 100644 index 0000000..83073a6 --- /dev/null +++ b/docs/content/about/roadmap.md @@ -0,0 +1,14 @@ +# Roadmap + +The following are things we're thinking about, and may be added as-needed. + +- Add support for: + - Stored procedures + - Triggers + - Users + - Roles + - Databases and Tablespaces +- Add per-method provider `Option` parameters for greater coverage of provider-specific capabilities and nuances. +- Improve on some of the convention-based design decisions, and support a fluent configuration syntax for handling types and data type mappings. +- Add database CRUD methods +- Add account management CRUD methods (for users and roles) diff --git a/docs/content/getting-started.md b/docs/content/getting-started.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/content/getting-started/configuration.md b/docs/content/getting-started/configuration.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/content/getting-started/installation.md b/docs/content/getting-started/installation.md new file mode 100644 index 0000000..d0e45fe --- /dev/null +++ b/docs/content/getting-started/installation.md @@ -0,0 +1,21 @@ +# Installation + +To get started, add the github nuget source for the package to your nuget.config. + +```sh +# create the nuget.config file if it doesn't exist +dotnet new nuget.config + +# add the package source +dotnet nuget add source https://nuget.pkg.github.com/mjczone/index.json -n mjczone@nuget.pkg.github +``` + +Add the nuget package to your project. + +```sh +dotnet add package MJCZone.DapperMatic +``` + +Explore the extension methods you can use in your project. + +- [Extension Methods](#/usage/extension-methods) diff --git a/docs/content/getting-started/models.md b/docs/content/getting-started/models.md new file mode 100644 index 0000000..e0ec98c --- /dev/null +++ b/docs/content/getting-started/models.md @@ -0,0 +1,30 @@ +# Models + +- [DmCheckConstraint](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmCheckConstraint) ([src](src/MJCZone.DapperMatic/Models/DmCheckConstraint.cs)) +- [DmColumn](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmColumn) ([src](src/MJCZone.DapperMatic/Models/DmColumn.cs)) +- [DmColumnOrder](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmColumnOrder) ([src](src/MJCZone.DapperMatic/Models/DmColumnOrder.cs)) +- [DmConstraint](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmConstraint) ([src](src/MJCZone.DapperMatic/Models/DmConstraint.cs)) +- [DmConstraintType](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmConstraintType) ([src](src/MJCZone.DapperMatic/Models/DmConstraintType.cs)) +- [DmDefaultConstraint](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmDefaultConstraint) ([src](src/MJCZone.DapperMatic/Models/DmDefaultConstraint.cs)) +- [DmForeignKeyAction](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmForeignKeyAction) ([src](src/MJCZone.DapperMatic/Models/DmForeignKeyAction.cs)) +- [DmForeignKeyConstraint](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmForeignKeyConstraint) ([src](src/MJCZone.DapperMatic/Models/DmForeignKeyConstraint.cs)) +- [DmIndex](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmIndex) ([src](src/MJCZone.DapperMatic/Models/DmIndex.cs)) +- [DmOrderedColumn](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmOrderedColumn) ([src](src/MJCZone.DapperMatic/Models/DmOrderedColumn.cs)) +- [DmPrimaryKeyConstraint](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmPrimaryKeyConstraint) ([src](src/MJCZone.DapperMatic/Models/DmPrimaryKeyConstraint.cs)) +- [DmTable](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmTable) ([src](src/MJCZone.DapperMatic/Models/DmTable.cs)) +- [DmUniqueConstraint](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmUniqueConstraint) ([src](src/MJCZone.DapperMatic/Models/DmUniqueConstraint.cs)) +- [DmView](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmView) ([src](src/MJCZone.DapperMatic/Models/DmView.cs)) + +## Model related factory methods + +- [DmTableFactory](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmTableFactory) ([src](src/MJCZone.DapperMatic/Models/DmTableFactory.cs)) + +```csharp +DmTable table = DmTableFactory.GetTable(typeof(app_employees)) +``` + +- [DmViewFactory](#/packages/MJCZone.DapperMatic/ns/MJCZone.DapperMatic.Models/t/DmViewFactory) ([src](src/MJCZone.DapperMatic/Models/DmViewFactory.cs)) + +```csharp +DmView view = DmViewFactory.GetView(typeof(vw_onboarded_employees)) +``` diff --git a/docs/content/getting-started/providers.md b/docs/content/getting-started/providers.md new file mode 100644 index 0000000..1b2df6e --- /dev/null +++ b/docs/content/getting-started/providers.md @@ -0,0 +1,92 @@ +# Providers + +The following providers are currently supported. Unit tested versions are in parenthesis. + +- [x] SQLite (v3) +- [x] MySQL (v5.7, 8.4) +- [x] MariaDB (v10.11) +- [x] PostgreSQL (v15, v16) +- [x] SQL Server (v2017, v2019, v2022) +- [ ] Oracle +- [ ] IBM DB2 + +## Register a custom provider + +First override the `IDatabaseMethods`, and `IDatabaseMethodsFactory` interfaces: + +```csharp +namespace PestControl.Foundry; + +public class CentipedeDbConnection: System.Data.Common.DbConnection +{ + // ... +} + +public class CentipedeDbMethods: MJCZone.DapperMatic.Interfaces.IDatabaseMethods +{ + // ... +} + +public class CentipedeDbMethodsFactory : MJCZone.DapperMatic.Providers.DatabaseMethodsFactoryBase +{ + public override bool SupportsConnection(IDbConnection db) + => connection.GetType().Name == nameof(CentipedeDbConnection); + + protected override IDatabaseMethods CreateMethodsCore() + => new CentipedeDbMethods(); +} +``` + +Then register the provider: + +```csharp +DatabaseMethodsProvider.RegisterFactory("CentipedeDb", new PestControl.Foundry.CentipedeDbMethodsFactory()); +``` + +## Extend an existing provider + +You may want to use a library that wraps an existing `IDbConnection` (e.g., ProfiledDbConnection with MiniProfiler). In that case, you can simply extend +a built-in factory and register your new factory implementation with MJCZone.DapperMatic. + +Your factory class would like like this. + +```csharp +public class ProfiledPostgreSqlMethodsFactory: PostgreSqlMethodsFactory +{ + public override bool SupportsConnectionCustom(IDbConnection db) + { + return (db is ProfiledDbConnection pdc) ? base.SupportsConnectionCustom(pdc.InnerConnection): false; + } +} +``` + +Then register the factory as follows. + +```csharp +DatabaseMethodsProvider.RegisterFactory( + "ProfiledDbConnection.PostgreSql", new ProfiledPostgreSqlMethodsFactory()); +``` + +The test suite uses this method to profile the database and output sql exception details +to the unit testing logs. + +See it in action with the [ProfiledPostgreSqlMethodsFactory](https://github.com/mjczone/MJCZone.DapperMatic/tests/MJCZone.DapperMatic.Tests/ProviderTests/PostgreSqlDatabaseMethodsTests.cs#L84) class. Similar factory classes exist for the other providers. + +## Provider documentation links + +The extension methods and operation implementations are derived from the SQL documentation residing at the following links: + +- MySQL + - MySQL 8.4: + - MySQL 5.7: +- MariaDB + - MariaDB 10.11: +- PostgreSQL + - PostgreSQL 16: + - PostgreSQL 15: +- SQLite + - SQLite (v3): +- SQL Server + - SQL Server 2022: + - SQL Server 2019: + - SQL Server 2017: diff --git a/docs/content/index.md b/docs/content/index.md new file mode 100644 index 0000000..4d1469b --- /dev/null +++ b/docs/content/index.md @@ -0,0 +1,9 @@ +# Welcome + +The `MJCZone.DapperMatic` library adds a number of extension methods to an `IDbConnection` instance. + +Currently the methods revolve around DDL operations, such as creating, updating, selecting and dropping schemas, tables, columns, constraints, indexes, and views. + +The intention of this library is to make these operations easy to use for a variety of purposes, while leveling the field between database providers. The methods provide a consistent way of managing DDL objects in a database, hopefully addressing the top 80% of use-cases typical applications need. + +This is VERY Early in the release cycle for this project, use the APIs at your own risk. diff --git a/docs/content/test.md b/docs/content/test.md new file mode 100644 index 0000000..a2f3de3 --- /dev/null +++ b/docs/content/test.md @@ -0,0 +1,148 @@ +# GitHub Markdown Syntax using Showdown + +See + +This page demonstrates the typical GitHub Markdown syntax for various elements. + +## Headers + +Headers are created by using `#`. The number of `#` symbols indicates the header level. + +### H3 Header + +#### H4 Header + +##### H5 Header + +###### H6 Header + +## Paragraphs + +Paragraphs are created by simply writing text. Separate paragraphs by one or more blank lines. + +This is a paragraph. + +This is another paragraph, separated by a blank line. + +## Links + +To create links, use the following syntax: + +[GitHub](https://github.com) + +### Example with Title Attribute + +[GitHub](https://github.com "Visit GitHub") + +## Images + +Images are similar to links, but with an exclamation mark `!` before the link. You can also configure the width and height in a number of ways, see this example and the next. + +![GitHub Logo]( =400x400) + +### Image with Title Attribute + +![GitHub Logo](https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png?w=500&h=400 "GitHub") + +## Ordered Lists + +To create an ordered list, simply use numbers followed by a period. + +1. First item +2. Second item +3. Third item + +## Unordered Lists + +To create an unordered list, use asterisks (`*`), plus signs (`+`), or hyphens (`-`). + +- Item 1 +- Item 2 +- Item 3 + +## Task Lists + +GitHub supports task lists. These can be created by adding `- [ ]` for an unchecked box and `- [x]` for a checked box. + +- [x] Task 1 (completed) +- [ ] Task 2 (incomplete) + +## Blockquotes + +Blockquotes are created by using the `>` symbol. + +> This is a blockquote. +> +> > It can span multiple lines. +> +> - A list +> - with items + +## Bold and Italic + +You can make text bold or italic. + +*This text will be italic*
+**This text will be bold** + +Both bold and italic can use either a * or an _ around the text for styling. This allows you to combine both bold and italic if needed. + +**Everyone *must* attend the meeting at 5 o'clock today.** + +## Strikethrough + +The syntax is the same as GFM, that is, by adding two tilde (~~) characters around a word or groups of words. + +a ~~strikethrough~~ element + +## Code + +### Inline Code + +To highlight a small piece of code inline, wrap it with backticks (`). + +Use `git status` to check the repository status. + +### Code Blocks + +To create a code block, use triple backticks (```). + +```python +def hello_world(): + print("Hello, World!") +``` + +And here's some c#. + +```csharp +namespace PestControl.Foundry; + +public class CentipedeDbConnection: System.Data.Common.DbConnection +{ + // ... +} + +public class CentipedeDbMethods: MJCZone.DapperMatic.Interfaces.IDatabaseMethods +{ + // ... +} + +public class CentipedeDbMethodsFactory : MJCZone.DapperMatic.Providers.DatabaseMethodsFactoryBase +{ + public override bool SupportsConnection(IDbConnection db) + => connection.GetType().Name == nameof(CentipedeDbConnection); + + protected override IDatabaseMethods CreateMethodsCore() + => new CentipedeDbMethods(); +} +``` + +## Tables + +| Tables | Are | Cool | +| ------------- |:-------------:| -----:| +| **col 3 is** | right-aligned | $1600 | +| col 2 is | *centered* | $12 | +| zebra stripes | ~~are neat~~ | $1 | + +All done. diff --git a/docs/content/usage.md b/docs/content/usage.md new file mode 100644 index 0000000..c30e623 --- /dev/null +++ b/docs/content/usage.md @@ -0,0 +1,20 @@ +# Usage + +## `IDbConnection` CRUD extension methods + +All methods are async and support an optional transaction (recommended), and cancellation token. + +## About `Schemas` + +The schema name parameter is nullable in all methods, as many database providers don't support schemas (e.g., SQLite and MySql). If a database supports schemas, and the schema name passed in is `null` or an empty string, then a default schema name is used for that database provider. + +The following default schema names apply: + +- SqLite: "" (empty string) +- MySql: "" (empty string) +- PostgreSql: "public" +- SqlServer: "dbo" + +## Explore + +- [Extension Methods](#/usage/extension-methods) diff --git a/docs/content/usage/extension-methods.md b/docs/content/usage/extension-methods.md new file mode 100644 index 0000000..31fb0c8 --- /dev/null +++ b/docs/content/usage/extension-methods.md @@ -0,0 +1,15 @@ +# Extension Methods + +The following method groups are available. + +- [General Methods](#/usage/extension-methods/general-methods) +- [Schema Methods](#/usage/extension-methods/schema-methods) +- [Table Methods](#/usage/extension-methods/table-methods) +- [Column Methods](#/usage/extension-methods/column-methods) +- [Primary Key Constraint Methods](#/usage/extension-methods/primary-key-constraint-methods) +- [Check Constraint Methods](#/usage/extension-methods/check-constraint-methods) +- [Default Constraint Methods](#/usage/extension-methods/default-constraint-methods) +- [Foreign Key Constraint Methods](#/usage/extension-methods/foreign-key-constraint-methods) +- [Unique Constraint Methods](#/usage/extension-methods/unique-constraint-methods) +- [Index Methods](#/usage/extension-methods/index-methods) +- [View Methods](#/usage/extension-methods/view-methods) diff --git a/docs/content/usage/extension-methods/check-constraint-methods.md b/docs/content/usage/extension-methods/check-constraint-methods.md new file mode 100644 index 0000000..9e74837 --- /dev/null +++ b/docs/content/usage/extension-methods/check-constraint-methods.md @@ -0,0 +1,49 @@ +# Check constraint methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +var constraintName = ProviderUtils.GenerateCheckConstraintName("app_employees", "age"); + +// EXISTS: Check to see if a check constraint exists +bool exists = await db.DoesCheckConstraintExistAsync("app","app_employees", constraintName, tx, cancellationToken).ConfigureAwait(false) + +// EXISTS: Check to see if a check constraint exists on a column +exists = await db.DoesCheckConstraintExistOnColumnAsync("app","app_employees", "age", tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a check constraint +bool created = await db.CreateCheckConstraintIfNotExistsAsync("app", /* DmCheckConstraint */ checkConstraint); +// or + created = await db.CreateCheckConstraintIfNotExistsAsync( + "app", + "app_employees", + // string? columnName, + "age", + // string constraintName, + constraintName, + // string expression, + "age > 21", + ... + ); + +// GET: Retrieve check constraints +List names = await db.GetCheckConstraintNamesAsync("app", "app_employees", "ck_*", ...); + +string name = await db.GetCheckConstraintNameOnColumnAsync("app", "app_employees", "age", ...); + +// GET: Retrieve check constraints +List checkConstraints = await db.GetCheckConstraintsAsync("app", "app_employees", "ck_*", ...); + +// GET: Retrieve single check constraint +DmCheckConstraint? checkConstraint = await db.GetCheckConstraintAsync("app", "app_employees", constraintName, ...); + +// GET: Retrieve single check constraint on column +checkConstraint = await db.GetCheckConstraintOnColumnAsync("app", "app_employees", "age", ...); + +// DROP: Drop a check constraint +bool dropped = await db.DropCheckConstraintIfExistsAsync("app", "app_employees", constraintName, ...); + +// DROP: Drop a check constraint on column +dropped = await db.DropCheckConstraintOnColumnIfExistsAsync("app", "app_employees", "age", ...); +``` diff --git a/docs/content/usage/extension-methods/column-methods.md b/docs/content/usage/extension-methods/column-methods.md new file mode 100644 index 0000000..57c83fb --- /dev/null +++ b/docs/content/usage/extension-methods/column-methods.md @@ -0,0 +1,54 @@ +# Column methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +// EXISTS: Check to see if a table column exists +bool exists = await db.DoesColumnExistAsync("app", "app_employees", "title", tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a table column +bool created = await db.CreateColumnIfNotExistsAsync("app", /* DmColumn */ column); +// or + created = await db.CreateColumnIfNotExistsAsync( + "app", + "app_employees", + // string columnName, + "manager_id" + // Type dotnetType, + typeof(Guid), + // optional parameters (the actual sql data type is derived from the dotnet type, but can be specified if desired) + providerDataType: (string?) null, + length: (int?) null, + precision: (int?) null, + scale: (int?) null, + checkExpression: (string?)null, + defaultExpression: (string?)null, + isNullable: false /* default */, + isPrimaryKey: false /* default */, + isAutoIncrement: false /* default */, + isUnique: false /* default */, + isIndexed: false /* default */, + isForeignKey: true, + referencedTableName: (string?) "app_managers", + referencedColumnName: (string?) "id", + onDelete: (DmForeignKeyAction?) DmForeignKeyAction.Cascade, + onUpdate: (DmForeignKeyAction?) DmForeignKeyAction.NoAction, + ... + ); + +// GET: Retrieve table column names +List names = await db.GetColumnNamesAsync("app", "app_employees", "*title*", ...); + +// GET: Retrieve table columns +List tables = await db.GetColumnsAsync("app", "app_employees", "*title*", ...); + +// GET: Retrieve single table column +DmColumn? column = await db.GetColumnAsync("app", "app_employees", "title", ...); + +// DROP: Drop a table column +bool dropped = await db.DropColumnIfExistsAsync("app", "app_employees", "title", ...); + +// RENAME: Rename a table column +bool renamed = await db.RenameColumnIfExistsAsync("app", "app_employees", "title", /* new name */ "job_title", ...); +``` diff --git a/docs/content/usage/extension-methods/default-constraint-methods.md b/docs/content/usage/extension-methods/default-constraint-methods.md new file mode 100644 index 0000000..7705c7a --- /dev/null +++ b/docs/content/usage/extension-methods/default-constraint-methods.md @@ -0,0 +1,49 @@ +# Default constraint methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +var constraintName = ProviderUtils.GenerateDefaultConstraintName("app_employees", "age"); + +// EXISTS: Check to see if a default constraint exists +bool exists = await db.DoesDefaultConstraintExistAsync("app","app_employees", constraintName, tx, cancellationToken).ConfigureAwait(false) + +// EXISTS: Check to see if a default constraint exists on a column +exists = await db.DoesDefaultConstraintExistOnColumnAsync("app","app_employees", "age", tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a default constraint +bool created = await db.CreateDefaultConstraintIfNotExistsAsync("app", /* DmDefaultConstraint */ defaultConstraint); +// or + created = await db.CreateDefaultConstraintIfNotExistsAsync( + "app", + "app_employees", + // string? columnName, + "age", + // string constraintName, + constraintName, + // string expression, + "-1", + ... + ); + +// GET: Retrieve default constraints +List names = await db.GetDefaultConstraintNamesAsync("app", "app_employees", "df_*", ...); + +string name = await db.GetDefaultConstraintNameOnColumnAsync("app", "app_employees", "age", ...); + +// GET: Retrieve default constraints +List defaultConstraints = await db.GetDefaultConstraintsAsync("app", "app_employees", "df*", ...); + +// GET: Retrieve single default constraint +DmDefaultConstraint? defaultConstraint = await db.GetDefaultConstraintAsync("app", "app_employees", constraintName, ...); + +// GET: Retrieve single default constraint on column +defaultConstraint = await db.GetDefaultConstraintOnColumnAsync("app", "app_employees", "age", ...); + +// DROP: Drop a default constraint +bool dropped = await db.DropDefaultConstraintIfExistsAsync("app", "app_employees", constraintName, ...); + +// DROP: Drop a default constraint on column +dropped = await db.DropDefaultConstraintOnColumnIfExistsAsync("app", "app_employees", "age", ...); +``` diff --git a/docs/content/usage/extension-methods/foreign-key-constraint-methods.md b/docs/content/usage/extension-methods/foreign-key-constraint-methods.md new file mode 100644 index 0000000..d71bfee --- /dev/null +++ b/docs/content/usage/extension-methods/foreign-key-constraint-methods.md @@ -0,0 +1,54 @@ +# Foreign Key constraint methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +var constraintName = ProviderUtils.GenerateForeignKeyConstraintName("app_employees", "manager_id", "app_managers", "id"); + +// EXISTS: Check to see if a foreign key exists +bool exists = await db.DoesForeignKeyConstraintExistAsync("app","app_employees", constraintName, tx, cancellationToken).ConfigureAwait(false) + +// EXISTS: Check to see if a foreign key exists on a column +exists = await db.DoesForeignKeyConstraintExistOnColumnAsync("app","app_employees", "manager_id", tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a foreign key +bool created = await db.CreateForeignKeyConstraintIfNotExistsAsync("app", /* DmForeignKeyConstraint */ foreignKeyConstraint); +// or + created = await db.CreateForeignKeyConstraintIfNotExistsAsync( + "app", + "app_employees", + // string constraintName, + constraintName, + // DmOrderedColumn[] sourceColumns, + [ new DmOrderedColumn("manager_id") ] + // string referencedTableName, + "app_managers", + // DmOrderedColumn[] referencedColumns, + [ new DmOrderedColumn("id") ], + onDelete: DmForeignKeyAction.Cascade, + onUpdate: DmForeignKeyAction.NoAction, + ... + ); + +// GET: Retrieve foreign key names +List names = await db.GetForeignKeyConstraintNamesAsync("app", "app_employees", "fk_*", ...); + +// GET: Retrieve foreign key name on column +string name = await db.GetForeignKeyConstraintNameOnColumnAsync("app", "app_employees", "manager_id", ...); + +// GET: Retrieve foreign keys +List foreignKeyConstraints = await db.GetForeignKeyConstraintsAsync("app", "app_employees", "fk_*", ...); + +// GET: Retrieve single foreign key +DmForeignKeyConstraint? foreignKeyConstraint = await db.GetForeignKeyConstraintAsync("app", "app_employees", constraintName, ...); + +// GET: Retrieve single foreign key on column +foreignKeyConstraint = await db.GetForeignKeyConstraintOnColumnAsync("app", "app_employees", "manager_id", ...); + +// DROP: Drop a foreign key +bool dropped = await db.DropForeignKeyConstraintIfExistsAsync("app", "app_employees", constraintName, ...); + +// DROP: Drop a foreign key on column +dropped = await db.DropForeignKeyConstraintOnColumnIfExistsAsync("app", "app_employees", "age", ...); +``` diff --git a/docs/content/usage/extension-methods/general-methods.md b/docs/content/usage/extension-methods/general-methods.md new file mode 100644 index 0000000..527c777 --- /dev/null +++ b/docs/content/usage/extension-methods/general-methods.md @@ -0,0 +1,33 @@ + +# General methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +// Get the version of the database (e.g., 3.46.1 for a SQLite database) +Version version = await db.GetDatabaseVersionAsync(tx, cancellationToken).ConfigureAwait(false) + +// Get a .NET type descriptor for a provider specific sql type +DbProviderDotnetTypeDescriptor descriptor = db.GetDotnetTypeFromSqlType("nvarchar(255)"); +// descriptor.AutoIncrement -> False +// descriptor.DotnetType -> typeof (String) +// descriptor.Length -> 255 +// descriptor.Precision -> null +// descriptor.Scale -> null +// descriptor.Unicode -> True + +// Get a provider specific sql type for a specific .NET type +string sqlType = db.GetSqlTypeFromDotnetType(new DbProviderDotnetTypeDescriptor(typeof(string), 47, unicode: true)); +// sqlType => nvarchar(47) + +// Get the mapped .NET type matching a specific provider sql data type (e.g., varchar(255), decimal(15,4)) +var (/* Type */ dotnetType, /* int? */ length, /* int? */ precision, /* int? */ scale) = db.GetDotnetTypeFromSqlType(string sqlType); + +// Normalize a database name identifier to some idiomatic standard, namely alpha numeric with underscores and without spaces +var normalizedName = db.NormalizeName(name); + +// Get the last sql executed inside MJCZone.DapperMatic +var lastSql = db.GetLastSql(); +(string sql, object? parameters) lastSqlWithParams = db.GetLastSqlWithParms(); +``` diff --git a/docs/content/usage/extension-methods/index-methods.md b/docs/content/usage/extension-methods/index-methods.md new file mode 100644 index 0000000..25c267b --- /dev/null +++ b/docs/content/usage/extension-methods/index-methods.md @@ -0,0 +1,49 @@ +# Index methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +var indexName = ProviderUtils.GenerateIndexName("app_employees", "is_onboarded"); + +// EXISTS: Check to see if a index exists +bool exists = await db.DoesIndexExistAsync("app","app_employees", indexName, tx, cancellationToken).ConfigureAwait(false) + +// EXISTS: Check to see if a index exists on a column +exists = await db.DoesIndexExistOnColumnAsync("app","app_employees", "is_onboarded", tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a index +bool created = await db.CreateIndexIfNotExistsAsync("app", /* DmIndex */ index); +// or + created = await db.CreateIndexIfNotExistsAsync( + "app", + "app_employees", + // string indexName, + indexName, + // DmOrderedColumn[] columns, + [ new DmOrderedColumn("is_onboarded", DmColumnOrder.Descending) ], + isUnique: false, + ... + ); + +// GET: Retrieve index names +List names = await db.GetIndexNamesAsync("app", "app_employees", "ix_*", ...); + +// GET: Retrieve index names on column +names = await db.GetIndexNamesOnColumnAsync("app", "app_employees", "is_onboarded", ...); + +// GET: Retrieve indexes +List indexes = await db.GetIndexesAsync("app", "app_employees", "ix_*", ...); + +// GET: Retrieve single index +DmIndex? index = await db.GetIndexAsync("app", "app_employees", indexName, ...); + +// GET: Retrieve single index on column +index = await db.GetIndexOnColumnAsync("app", "app_employees", "is_onboarded", ...); + +// DROP: Drop an index +bool dropped = await db.DropIndexIfExistsAsync("app", "app_employees", indexName, ...); + +// DROP: Drop indexes on column +dropped = await db.DropIndexesOnColumnIfExistsAsync("app", "app_employees", "is_onboarded", ...); +``` diff --git a/docs/content/usage/extension-methods/primary-key-constraint-methods.md b/docs/content/usage/extension-methods/primary-key-constraint-methods.md new file mode 100644 index 0000000..ff97685 --- /dev/null +++ b/docs/content/usage/extension-methods/primary-key-constraint-methods.md @@ -0,0 +1,35 @@ +# PrimaryKeyConstraint constraint methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +var primaryKeyConstraintName = + ProviderUtils.GeneratePrimaryKeyConstraintName("app_employees", "email"); + +// EXISTS: Check to see if a primary key constraint exists +bool exists = await db.DoesPrimaryKeyConstraintExistAsync("app","app_employees", + tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a primary key constraint +bool created = await db.CreatePrimaryKeyConstraintIfNotExistsAsync("app", + /* DmPrimaryKeyConstraint */ primaryKeyConstraint, ...); +// or + created = await db.CreatePrimaryKeyConstraintIfNotExistsAsync( + "app", + "app_employees", + // string primaryKeyConstraintName, + primaryKeyConstraintName, + // DmOrderedColumn[] columns, + [ new DmOrderedColumn("email", DmColumnOrder.Descending) ], + ... + ); + +// GET: Retrieve single primary key constraint +DmPrimaryKeyConstraint? primaryKeyConstraint = + await db.GetPrimaryKeyConstraintAsync("app", "app_employees", ...); + +// DROP: Drop a primary key constraint +bool dropped = + await db.DropPrimaryKeyConstraintIfExistsAsync("app", "app_employees", primaryKeyConstraintName, ...); +``` diff --git a/docs/content/usage/extension-methods/schema-methods.md b/docs/content/usage/extension-methods/schema-methods.md new file mode 100644 index 0000000..485558d --- /dev/null +++ b/docs/content/usage/extension-methods/schema-methods.md @@ -0,0 +1,21 @@ +# Schema methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +// Check to see if the database supports schemas +var supportsSchemas = db.SupportsSchemas(); + +// EXISTS: Check to see if a database schema exists +bool exists = await db.DoesSchemaExistAsync("app", tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a database schema +bool created = await db.CreateSchemaIfNotExistsAsync("app", ...); + +// GET: Retrieve database schema names +List names = await db.GetSchemaNamesAsync("*ap*", ...); + +// DROP: Drop a database schema +bool dropped = await db.DropSchemaIfExistsAsync("app", ...) +``` diff --git a/docs/content/usage/extension-methods/table-methods.md b/docs/content/usage/extension-methods/table-methods.md new file mode 100644 index 0000000..54ef434 --- /dev/null +++ b/docs/content/usage/extension-methods/table-methods.md @@ -0,0 +1,50 @@ +# Table methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +// EXISTS: Check to see if a database table exists +bool exists = await db.DoesTableExistAsync("app","app_employees", tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a database table +bool created = await db.CreateTableIfNotExistsAsync("app", /* DmTable */ table); +// or + created = await db.CreateTableIfNotExistsAsync( + "app", + "app_employees", + // DmColumn[] columns, + columns, + // DmPrimaryKeyConstraint? primaryKey = null, + primaryKey, + // DmCheckConstraint[]? checkConstraints = null, + checkConstraints, + // DmDefaultConstraint[]? defaultConstraints = null, + defaultConstraints, + // DmUniqueConstraint[]? uniqueConstraints = null, + uniqueConstraints, + // DmForeignKeyConstraint[]? foreignKeyConstraints = null, + foreignKeyConstraints, + // DmIndex[]? indexes = null, + indexes, + ... + ); + +// GET: Retrieve table names +List names = await db.GetTableNamesAsync("app", "app_*", ...); + +// GET: Retrieve tables +List tables = await db.GetTablesAsync("app", "app_*", ...); + +// GET: Retrieve single table +DmTable? table = await db.GetTableAsync("app", "app_employees", ...); + +// DROP: Drop a database table +bool dropped = await db.DropTableIfExistsAsync("app", "app_employees", ...); + +// RENAME: Rename a database table +bool renamed = await db.RenameTableIfExistsAsync("app", "app_employees", /* new name */ "app_staff", ...); + +// TRUNCATE: Drop a database table +bool truncated = await db.TruncateTableIfExistsAsync("app", "app_employees", ...); +``` diff --git a/docs/content/usage/extension-methods/unique-constraint-methods.md b/docs/content/usage/extension-methods/unique-constraint-methods.md new file mode 100644 index 0000000..870b393 --- /dev/null +++ b/docs/content/usage/extension-methods/unique-constraint-methods.md @@ -0,0 +1,48 @@ +# Unique Constraint constraint methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +var uniqueConstraintName = ProviderUtils.GenerateUniqueConstraintName("app_employees", "email"); + +// EXISTS: Check to see if a unique constraint exists +bool exists = await db.DoesUniqueConstraintExistAsync("app","app_employees", uniqueConstraintName, tx, cancellationToken).ConfigureAwait(false) + +// EXISTS: Check to see if a unique constraint exists on a column +exists = await db.DoesUniqueConstraintExistOnColumnAsync("app","app_employees", "email", tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a unique constraint +bool created = await db.CreateUniqueConstraintIfNotExistsAsync("app", /* DmUniqueConstraint */ uniqueConstraint, ...); +// or + created = await db.CreateUniqueConstraintIfNotExistsAsync( + "app", + "app_employees", + // string uniqueConstraintName, + uniqueConstraintName, + // DmOrderedColumn[] columns, + [ new DmOrderedColumn("email", DmColumnOrder.Descending) ], + ... + ); + +// GET: Retrieve unique constraint names +List names = await db.GetUniqueConstraintNamesAsync("app", "app_employees", "uc_*", ...); + +// GET: Retrieve uniqueConstraint names on column +names = await db.GetUniqueConstraintNamesOnColumnAsync("app", "app_employees", "email", ...); + +// GET: Retrieve uniqueConstraints +List uniqueConstraints = await db.GetUniqueConstraintsAsync("app", "app_employees", "uc_*", ...); + +// GET: Retrieve single unique constraint +DmUniqueConstraint? uniqueConstraint = await db.GetUniqueConstraintAsync("app", "app_employees", uniqueConstraintName, ...); + +// GET: Retrieve single unique constraint on column +uniqueConstraint = await db.GetUniqueConstraintOnColumnAsync("app", "app_employees", "email", ...); + +// DROP: Drop an unique constraint +bool dropped = await db.DropUniqueConstraintIfExistsAsync("app", "app_employees", uniqueConstraintName, ...); + +// DROP: Drop unique constraints on column +dropped = await db.DropUniqueConstraintsOnColumnIfExistsAsync("app", "app_employees", "email", ...); +``` diff --git a/docs/content/usage/extension-methods/view-methods.md b/docs/content/usage/extension-methods/view-methods.md new file mode 100644 index 0000000..d730e88 --- /dev/null +++ b/docs/content/usage/extension-methods/view-methods.md @@ -0,0 +1,55 @@ +# View methods + +```cs +using var db = await connectionFactory.OpenConnectionAsync(); +using var tx = db.BeginTransaction(); + +var viewName = "vw_employees_not_yet_onboarded"; + +// EXISTS: Check to see if a view exists +bool exists = await db.DoesViewExistAsync("app", viewName, tx, cancellationToken).ConfigureAwait(false) + +// CREATE: Create a view +bool created = await db.CreateViewIfNotExistsAsync("app", /* DmView */ view, ...); +// or + created = await db.CreateViewIfNotExistsAsync( + "app", + // string viewName, + viewName, + // string viewDefinition, + "SELECT * FROM app_employees WHERE is_onboarded = 0", + ... + ); + +// UPDATE: Update a view +bool updated = await db.CreateViewIfNotExistsAsync( + "app", + // string viewName, + viewName, + // string viewDefinition, + "SELECT * FROM app_employees WHERE is_onboarded = 0 and employment_date_ended is null", + ... +); + +// GET: Retrieve view names +List viewNames = await db.GetViewNames("app", "vw_*", ...); + +// GET: Retrieve single view +List views = await db.GetViewsAsync("app", "vw_*", ...); + +// GET: Retrieve single view +DmView? view = await db.GetViewAsync("app", viewName, ...); + +// DROP: Drop a view +bool dropped = await db.DropViewIfExistsAsync("app", viewName, ...); + +// RENAME: Rename a view +bool dropped = await db.RenameViewIfExistsAsync( + "app", + // string viewName, + "vw_employees_not_yet_onboarded", + // string newViewName, + "vw_current_employees_not_yet_onboarded", + ... +); +``` diff --git a/docs/content/usage/testing.md b/docs/content/usage/testing.md new file mode 100644 index 0000000..ec15d12 --- /dev/null +++ b/docs/content/usage/testing.md @@ -0,0 +1,16 @@ +# Testing + +The testing methodology consists of using the following very handy `Testcontainers.*` nuget library packages. +Tests are executed on Linux, and can be run on WSL during development. + +```xml + + + + +``` + +The exact same tests are run for each database provider, ensuring consistent behavior across all providers. + +The tests leverage docker containers for each supported database version (created and disposed of automatically at runtime). +The local file system is used for SQLite. diff --git a/docs/docs.config.json b/docs/docs.config.json new file mode 100644 index 0000000..03a7684 --- /dev/null +++ b/docs/docs.config.json @@ -0,0 +1,143 @@ +{ + "title": "DapperMatic", + "repositoryUrl": "https://github.com/mjczone/MJCZone.DapperMatic", + "version": "VERSION_NUMBER", + "content": { + "label": "Guides", + "expanded": ["/getting-started", "/usage"], + "items": [ + { + "id": "/", + "label": "Welcome", + "selectable": true, + "children": [] + }, + { + "id": "/getting-started", + "label": "Getting Started", + "selectable": false, + "children": [ + { + "id": "/getting-started/installation", + "label": "Installation", + "selectable": true + }, + { + "id": "/getting-started/providers", + "label": "Providers", + "selectable": true + }, + { + "id": "/getting-started/models", + "label": "Models", + "selectable": true + } + ] + }, + { + "id": "/usage", + "label": "Usage", + "selectable": true, + "children": [ + { + "id": "/usage/extension-methods", + "label": "Extension Methods", + "selectable": true, + "children": [ + { + "id": "/usage/extension-methods/general-methods", + "label": "General Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/schema-methods", + "label": "Schema Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/table-methods", + "label": "Table Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/column-methods", + "label": "Column Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/primary-key-constraint-methods", + "label": "Primary Key Constraint Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/check-constraint-methods", + "label": "Check Constraint Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/default-constraint-methods", + "label": "Default Constraint Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/foreign-key-constraint-methods", + "label": "Foreign Key Constraint Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/unique-constraint-methods", + "label": "Unique Constraint Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/index-methods", + "label": "Index Methods", + "selectable": true + }, + { + "id": "/usage/extension-methods/view-methods", + "label": "View Methods", + "selectable": true + } + ] + }, + { + "id": "/usage/testing", + "label": "Testing", + "selectable": true + } + ] + } + ] + }, + "packages": { + "label": "Packages", + "expanded": [], + "items": [ + { + "id": "/packages/MJCZone.DapperMatic", + "label": "MJCZone.DapperMatic", + "selectable": true, + "children": [] + } + ] + }, + "about": { + "label": "About", + "expanded": ["/about"], + "items": [ + { + "id": "/about", + "label": "About", + "selectable": true, + "children": [] + }, + { + "id": "/about/roadmap", + "label": "Roadmap", + "selectable": true, + "children": [] + } + ] + } +} diff --git a/docs/docs.css b/docs/docs.css new file mode 100644 index 0000000..5ef319d --- /dev/null +++ b/docs/docs.css @@ -0,0 +1,614 @@ +:root { + /* greys */ + --q-grey: #9e9e9e; + --q-grey-1: #fafafa; + --q-grey-2: #f5f5f5; + --q-grey-3: #eeeeee; + --q-grey-4: #e0e0e0; + --q-grey-5: #bdbdbd; + --q-grey-6: #9e9e9e; + --q-grey-7: #757575; + --q-grey-8: #616161; + --q-grey-9: #424242; + --q-grey-10: #212121; + --q-grey-11: #f5f5f5; + --q-grey-12: #eeeeee; + --q-grey-13: #bdbdbd; + --q-grey-14: #616161; + + /* blue greys */ + --q-blue-grey: #607d8b; + --q-blue-grey-1: #eceff1; + --q-blue-grey-2: #cfd8dc; + --q-blue-grey-3: #b0bec5; + --q-blue-grey-4: #90a4ae; + --q-blue-grey-5: #78909c; + --q-blue-grey-6: #607d8b; + --q-blue-grey-7: #546e7a; + --q-blue-grey-8: #455a64; + --q-blue-grey-9: #37474f; + --q-blue-grey-10: #263238; + --q-blue-grey-11: #cfd8dc; + --q-blue-grey-12: #b0bec5; + --q-blue-grey-13: #78909c; + --q-blue-grey-14: #455a64; + + /* reds */ + --q-red: #f44336; + --q-red-1: #ffebee; + --q-red-2: #ffcdd2; + --q-red-3: #ef9a9a; + --q-red-4: #e57373; + --q-red-5: #ef5350; + --q-red-6: #f44336; + --q-red-7: #e53935; + --q-red-8: #d32f2f; + --q-red-9: #c62828; + --q-red-10: #b71c1c; + --q-red-11: #ff8a80; + --q-red-12: #ff5252; + --q-red-13: #ff1744; + --q-red-14: #d50000; + + /* pinks */ + --q-pink: #e91e63; + --q-pink-1: #fce4ec; + --q-pink-2: #f8bbd0; + --q-pink-3: #f48fb1; + --q-pink-4: #f06292; + --q-pink-5: #ec407a; + --q-pink-6: #e91e63; + --q-pink-7: #d81b60; + --q-pink-8: #c2185b; + --q-pink-9: #ad1457; + --q-pink-10: #880e4f; + --q-pink-11: #ff80ab; + --q-pink-12: #ff4081; + --q-pink-13: #f50057; + --q-pink-14: #c51162; + + /* purples */ + --q-purple: #9c27b0; + --q-purple-1: #f3e5f5; + --q-purple-2: #e1bee7; + --q-purple-3: #ce93d8; + --q-purple-4: #ba68c8; + --q-purple-5: #ab47bc; + --q-purple-6: #9c27b0; + --q-purple-7: #8e24aa; + --q-purple-8: #7b1fa2; + --q-purple-9: #6a1b9a; + --q-purple-10: #4a148c; + --q-purple-11: #ea80fc; + --q-purple-12: #e040fb; + --q-purple-13: #d500f9; + --q-purple-14: #aa00ff; + + /* deep purples */ + --q-deep-purple: #673ab7; + --q-deep-purple-1: #ede7f6; + --q-deep-purple-2: #d1c4e9; + --q-deep-purple-3: #b39ddb; + --q-deep-purple-4: #9575cd; + --q-deep-purple-5: #7e57c2; + --q-deep-purple-6: #673ab7; + --q-deep-purple-7: #5e35b1; + --q-deep-purple-8: #512da8; + --q-deep-purple-9: #4527a0; + --q-deep-purple-10: #311b92; + --q-deep-purple-11: #b388ff; + --q-deep-purple-12: #7c4dff; + --q-deep-purple-13: #651fff; + --q-deep-purple-14: #6200ea; + + /* indigos */ + --q-indigo: #3f51b5; + --q-indigo-1: #e8eaf6; + --q-indigo-2: #c5cae9; + --q-indigo-3: #9fa8da; + --q-indigo-4: #7986cb; + --q-indigo-5: #5c6bc0; + --q-indigo-6: #3f51b5; + --q-indigo-7: #3949ab; + --q-indigo-8: #303f9f; + --q-indigo-9: #283593; + --q-indigo-10: #1a237e; + --q-indigo-11: #8c9eff; + --q-indigo-12: #536dfe; + --q-indigo-13: #3d5afe; + --q-indigo-14: #304ffe; + + /* blues */ + --q-blue: #2196f3; + --q-blue-1: #e3f2fd; + --q-blue-2: #bbdefb; + --q-blue-3: #90caf9; + --q-blue-4: #64b5f6; + --q-blue-5: #42a5f5; + --q-blue-6: #2196f3; + --q-blue-7: #1e88e5; + --q-blue-8: #1976d2; + --q-blue-9: #1565c0; + --q-blue-10: #0d47a1; + --q-blue-11: #82b1ff; + --q-blue-12: #448aff; + --q-blue-13: #2979ff; + --q-blue-14: #2962ff; + + /* light blues */ + --q-light-blue: #03a9f4; + --q-light-blue-1: #e1f5fe; + --q-light-blue-2: #b3e5fc; + --q-light-blue-3: #81d4fa; + --q-light-blue-4: #4fc3f7; + --q-light-blue-5: #29b6f6; + --q-light-blue-6: #03a9f4; + --q-light-blue-7: #039be5; + --q-light-blue-8: #0288d1; + --q-light-blue-9: #0277bd; + --q-light-blue-10: #01579b; + --q-light-blue-11: #80d8ff; + --q-light-blue-12: #40c4ff; + --q-light-blue-13: #00b0ff; + --q-light-blue-14: #0091ea; + + /* cyans */ + --q-cyan: #00bcd4; + --q-cyan-1: #e0f7fa; + --q-cyan-2: #b2ebf2; + --q-cyan-3: #80deea; + --q-cyan-4: #4dd0e1; + --q-cyan-5: #26c6da; + --q-cyan-6: #00bcd4; + --q-cyan-7: #00acc1; + --q-cyan-8: #0097a7; + --q-cyan-9: #00838f; + --q-cyan-10: #006064; + --q-cyan-11: #84ffff; + --q-cyan-12: #18ffff; + --q-cyan-13: #00e5ff; + --q-cyan-14: #00b8d4; + + /* teals */ + --q-teal: #009688; + --q-teal-1: #e0f2f1; + --q-teal-2: #b2dfdb; + --q-teal-3: #80cbc4; + --q-teal-4: #4db6ac; + --q-teal-5: #26a69a; + --q-teal-6: #009688; + --q-teal-7: #00897b; + --q-teal-8: #00796b; + --q-teal-9: #00695c; + --q-teal-10: #004d40; + --q-teal-11: #a7ffeb; + --q-teal-12: #64ffda; + --q-teal-13: #1de9b6; + --q-teal-14: #00bfa5; + + /* greens */ + --q-green: #4caf50; + --q-green-1: #e8f5e9; + --q-green-2: #c8e6c9; + --q-green-3: #a5d6a7; + --q-green-4: #81c784; + --q-green-5: #66bb6a; + --q-green-6: #4caf50; + --q-green-7: #43a047; + --q-green-8: #388e3c; + --q-green-9: #2e7d32; + --q-green-10: #1b5e20; + --q-green-11: #b9f6ca; + --q-green-12: #69f0ae; + --q-green-13: #00e676; + --q-green-14: #00c853; + + /* light greens */ + --q-light-green: #8bc34a; + --q-light-green-1: #f1f8e9; + --q-light-green-2: #dcedc8; + --q-light-green-3: #c5e1a5; + --q-light-green-4: #aed581; + --q-light-green-5: #9ccc65; + --q-light-green-6: #8bc34a; + --q-light-green-7: #7cb342; + --q-light-green-8: #689f38; + --q-light-green-9: #558b2f; + --q-light-green-10: #33691e; + --q-light-green-11: #ccff90; + --q-light-green-12: #b2ff59; + --q-light-green-13: #76ff03; + --q-light-green-14: #64dd17; + + /* limes */ + --q-lime: #cddc39; + --q-lime-1: #f9fbe7; + --q-lime-2: #f0f4c3; + --q-lime-3: #e6ee9c; + --q-lime-4: #dce775; + --q-lime-5: #d4e157; + --q-lime-6: #cddc39; + --q-lime-7: #c0ca33; + --q-lime-8: #afb42b; + --q-lime-9: #9e9d24; + --q-lime-10: #827717; + --q-lime-11: #f4ff81; + --q-lime-12: #eeff41; + --q-lime-13: #c6ff00; + --q-lime-14: #aeea00; + + /* yellows */ + --q-yellow: #ffeb3b; + --q-yellow-1: #fffde7; + --q-yellow-2: #fff9c4; + --q-yellow-3: #fff59d; + --q-yellow-4: #fff176; + --q-yellow-5: #ffee58; + --q-yellow-6: #ffeb3b; + --q-yellow-7: #fdd835; + --q-yellow-8: #fbc02d; + --q-yellow-9: #f9a825; + --q-yellow-10: #f57f17; + --q-yellow-11: #ffff8d; + --q-yellow-12: #ffff00; + --q-yellow-13: #ffea00; + --q-yellow-14: #ffd600; + + /* ambers */ + --q-amber: #ffc107; + --q-amber-1: #fff8e1; + --q-amber-2: #ffecb3; + --q-amber-3: #ffe082; + --q-amber-4: #ffd54f; + --q-amber-5: #ffca28; + --q-amber-6: #ffc107; + --q-amber-7: #ffb300; + --q-amber-8: #ffa000; + --q-amber-9: #ff8f00; + --q-amber-10: #ff6f00; + --q-amber-11: #ffe57f; + --q-amber-12: #ffd740; + --q-amber-13: #ffc400; + --q-amber-14: #ffab00; + + /* oranges */ + --q-orange: #ff9800; + --q-orange-1: #fff3e0; + --q-orange-2: #ffe0b2; + --q-orange-3: #ffcc80; + --q-orange-4: #ffb74d; + --q-orange-5: #ffa726; + --q-orange-6: #ff9800; + --q-orange-7: #fb8c00; + --q-orange-8: #f57c00; + --q-orange-9: #ef6c00; + --q-orange-10: #e65100; + --q-orange-11: #ffd180; + --q-orange-12: #ffab40; + --q-orange-13: #ff9100; + --q-orange-14: #ff6d00; + + /* deep oranges */ + --q-deep-orange: #ff5722; + --q-deep-orange-1: #fbe9e7; + --q-deep-orange-2: #ffccbc; + --q-deep-orange-3: #ffab91; + --q-deep-orange-4: #ff8a65; + --q-deep-orange-5: #ff7043; + --q-deep-orange-6: #ff5722; + --q-deep-orange-7: #f4511e; + --q-deep-orange-8: #e64a19; + --q-deep-orange-9: #d84315; + --q-deep-orange-10: #bf360c; + --q-deep-orange-11: #ff9e80; + --q-deep-orange-12: #ff6e40; + --q-deep-orange-13: #ff3d00; + --q-deep-orange-14: #dd2c00; + + /* browns */ + --q-brown: #795548; + --q-brown-1: #efebe9; + --q-brown-2: #d7ccc8; + --q-brown-3: #bcaaa4; + --q-brown-4: #a1887f; + --q-brown-5: #8d6e63; + --q-brown-6: #795548; + --q-brown-7: #6d4c41; + --q-brown-8: #5d4037; + --q-brown-9: #4e342e; + --q-brown-10: #3e2723; + --q-brown-11: #d7ccc8; + --q-brown-12: #bcaaa4; + --q-brown-13: #8d6e63; + --q-brown-14: #5d4037; + + /* theme colors */ + --q-primary: var(--q-blue-8); + --q-secondary: var(--q-blue-9); + --q-info: var(--q-blue-3); + --q-accent: var(--q-brown-6); + --q-positive: var(--q-green); + --q-negative: var(--q-red); + --q-warning: var(--q-orange); + + --q-dark: var(--q-grey-10); + --q-light: var(--q-grey-1); + --q-white: #fff; + --q-black: #000; +} + +/* Use the tailwindcss font-family sizes */ +h1, +.text-h1 { + font-size: 1.5rem; /* 24px */ + line-height: 2rem; /* 32px */ +} +h2, +.text-h2 { + font-size: 1.25rem; /* 20px */ + line-height: 1.75rem; /* 28px */ +} +h3, +.text-h3 { + font-size: 1.125rem; /* 18px */ + line-height: 1.75rem; /* 28px */ +} +h4, +.text-h4 { + font-size: 1rem; /* 16px */ + line-height: 1.5rem; /* 24px */ +} +h5, +.text-h5 { + font-size: 0.875rem; /* 14px */ + line-height: 1.25rem; /* 20px */ +} +h6, +.text-h6 { + font-size: 0.75rem; /* 12px */ + line-height: 1rem; /* 16px */ +} + +/* highlight.js styles */ +.hljs { + color: var(--q-grey-4) !important; + background: var(--q-blue-grey-10) !important; +} +.hljs-params { + color: var(--q-grey-4) !important; +} +.hljs-comment, +.hljs-quote { + color: var(--q-grey-8) !important; +} +.hljs-doctag, +.hljs-keyword, +.hljs-formula { + color: var(--q-light-blue-8) !important; +} +.hljs-section, +.hljs-name, +.hljs-tag, +.hljs-selector-tag, +.hljs-deletion, +.hljs-subst { + color: var(--q-red-4) !important; +} +.hljs-literal { + color: var(--q-cyan-7) !important; +} +.hljs-string, +.hljs-regexp, +.hljs-addition, +.hljs-attribute, +.hljs-meta .hljs-string { + color: var(--q-light-green-5) !important; +} +.hljs-attr, +.hljs-variable, +.hljs-template-variable, +.hljs-type, +.hljs-selector-class, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-number { + color: var(--q-yellow-8) !important; +} +.hljs-symbol, +.hljs-bullet, +.hljs-link, +.hljs-meta, +.hljs-selector-id, +.hljs-title { + color: var(--q-blue-3) !important; +} +.hljs-built_in, +.hljs-title.class_, +.hljs-class .hljs-title { + color: var(--q-amber-4) !important; +} + +/* blockquote { + font-style: italic; + margin-left: auto; + margin-right: auto; + background-color: var(--q-grey-2); +} */ +blockquote { + font-size: 1.4em; + width: auto; + margin: 14px auto; + font-family: Open Sans; + font-style: italic; + color: #555555; + padding: 20px 20px 10px 65px; + border-left: 8px solid var(--q-brown-4); + line-height: 1; + position: relative; + background: var(--q-brown-1); +} + +blockquote::before { + font-family: Arial; + content: "\201C"; + color: var(--q-brown-4); + font-size: 4em; + position: absolute; + left: 10px; + top: 4px; +} + +blockquote > blockquote { + margin: 0; + border-left: 4px solid var(--q-brown-2); + font-size: 0.9em; + padding: 10px 10px 1px 14px; +} + +blockquote > blockquote::before { + display: none; +} + +blockquote::after { + content: ""; +} + +blockquote span { + display: block; + color: #333333; + font-style: normal; + font-weight: bold; + margin-top: 1em; +} + +p > code { + background-color: var(--q-grey-4); + padding: 0.2em 0.4em; + border-radius: 4px; + font-size: 1em; +} + +#q-app { + /* HEADER STYLES */ + .q-header { + background: linear-gradient(45deg, var(--q-dark), var(--q-primary)); + + .page-title { + color: var(--q-white); + font-size: 2.125rem; + font-weight: 400; + line-height: 2.5rem; + letter-spacing: 0.00735em; + font-weight: 100; + } + + .header-title { + display: block; + } + .header-version { + display: block; + } + } + + /* DRAWER STYLES */ + .left-drawer { + .drawer-section-label { + border-top: 1px solid var(--q-grey-2); + border-bottom: 1px solid var(--q-grey-3); + background: var(--q-grey-1); + padding-bottom: 5px; + } + .drawer-section-label:first-child { + border-top: 0px; + } + .q-tree { + .q-tree__node { + .q-tree__node-header-content { + padding-left: 10px; + } + /* .q-focusable { + color: var(--q-primary) !important; + .q-tree__node-header-content { + color: var(--q-primary) !important; + } + } */ + } + .q-tree__node--selected { + background-color: var(--q-grey-3); + font-weight: 500; + .q-tree__node-header-content { + color: var(--q-black) !important; + } + } + } + } + + /* PAGE CONTAINER STYLES */ + .q-page-container { + background-color: var(--q-white); + .q-page { + padding-left: 20px; + padding-right: 20px; + + .content-page { + > div > .q-img { + margin: 0 auto; + display: block; + } + } + + .package-page { + // allow wrapping on the package page + .q-table--no-wrap td, + .q-table--no-wrap th { + white-space: wrap; + } + table { + min-width: 50%; + } + td code { + background-color: var(--q-grey-4); + padding: 0.2em 0.4em; + border-radius: 4px; + font-size: 1em; + } + td .q-badge { + margin-right: 5px; + } + } + + table { + border-spacing: 0px !important; + margin-bottom: 20px; + } + + table > thead > tr > th, + table > tbody > tr > td { + border: 1px solid var(--q-grey-3); + padding: 4px 8px; + margin: 0; + } + + table > thead > tr { + background-color: var(--q-grey-1); + th { + border-bottom: 2px solid var(--q-grey-3); + } + } + + a, + a:visited { + color: var(--q-primary); + text-decoration: none; + &:hover { + text-decoration: underline; + } + } + } + } + + /* GLOBAL STYLES */ + .q-btn.btn--no-hover .q-focus-helper { + display: none; + } +} diff --git a/docs/favicon.ico b/docs/favicon.ico new file mode 100644 index 0000000..406c318 Binary files /dev/null and b/docs/favicon.ico differ diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..ea19136 --- /dev/null +++ b/docs/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/main-min.js b/docs/main-min.js new file mode 100644 index 0000000..47ac0e7 --- /dev/null +++ b/docs/main-min.js @@ -0,0 +1 @@ +function isScriptLoadedByUrl(e){return Boolean(document.querySelector(`script[src="${e}"]`))}function isStyleLoadedByUrl(e){return Boolean(document.querySelector(`link[href="${e}"]`))}function loadScript(e){return new Promise((function(t,n){let r=null;const o=document.createElement("script");let i="";if("string"==typeof e)i=e;else{if(i=e.src,e.id&&e.id.length){if(r=document.getElementById(e.id),r&&!e.replace)return void t(i);o.id=e.id}o.async=e.async||!1,e.crossorigin&&e.crossorigin.length&&o.setAttribute("crossorigin",e.crossorigin),e.integrity&&e.integrity.length&&o.setAttribute("integrity",e.integrity),e.referrerpolicy&&e.referrerpolicy.length&&o.setAttribute("referrerpolicy",e.referrerpolicy)}o.src=i,isScriptLoadedByUrl(i)?t(i):(o.onload=function(){setTimeout((()=>{t(i)}),0)},o.onerror=function(){setTimeout((()=>{n(o.src)}),0)},r&&r.remove(),document.head.appendChild(o))}))}async function loadScripts(e){const t=[];for(const n of e)try{const e=await loadScript(n);t.push(e)}catch(e){break}return t}function unloadScript(e){if(!e)return;let t=document.getElementById(e);t||(t=document.querySelector(`script[src="${e}"]`)),t&&t.remove()}function loadLink(e){return new Promise((function(t,n){let r=null;const o=document.createElement("link");o.rel="stylesheet",o.type="text/css",o.media="all";let i="";if("string"==typeof e)i=e;else if(i=e.href,e.id&&e.id.length){if(r=document.getElementById(e.id),r&&!e.replace)return void t(i);o.id=e.id}o.href=i,isStyleLoadedByUrl(i)?t(i):(o.onload=function(){setTimeout((()=>{t(i)}),0)},o.onerror=function(){setTimeout((()=>{n(i)}),0)},r&&r.remove(),document.head.appendChild(o))}))}const loadStyle=loadLink;function unloadStyle(e){if(!e)return;let t=document.getElementById(e);t||(t=document.querySelector(`link[href="${e}"]`)),t&&t.remove()}function loadStyles(e){const t=[];return e.forEach((e=>{t.push(loadLink(e))})),Promise.all(t)}async function boot(){await loadStyles(["https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons","https://cdn.jsdelivr.net/npm/quasar@2.17.4/dist/quasar.prod.css","https://cdn.jsdelivr.net/npm/highlight.js@11.10.0/styles/default.min.css","./docs.css"]),await Promise.all([loadScripts(["https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js","https://cdn.jsdelivr.net/npm/vuex@4.1.0/dist/vuex.global.min.js","https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue3-sfc-loader.js","https://cdn.jsdelivr.net/npm/quasar@2.17.4/dist/quasar.umd.prod.js"]),loadScripts(["https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js","https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js",{src:"https://cdn.jsdelivr.net/npm/showdown@2.1.0/dist/showdown.min.js",crossorigin:"anonymous",integrity:"sha256-iOtvu+DCcN3zOEruDJYg0HDgkKJuB8Z0Ia42yQO11kk=",referrerpolicy:"no-referrer"}])])}function dynamicSort(e){var t=1;return"-"===e[0]&&(t=-1,e=e.substr(1)),function(n,r){return(n[e]r[e]?1:0)*t}}function createElementFromHtml(e){var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild}function extractQueryParam(e,t,n){return new URL(e).searchParams.get(t)||n||null}function docsComponent(e){const t={moduleCache:{vue:Vue},async getFile(e){const t=await fetch(e);if(!t.ok)throw Object.assign(new Error(t.statusText+" "+e),{res:t});return{getContentData:e=>e?t.arrayBuffer():t.text()}},addStyle(e){const t=Object.assign(document.createElement("style"),{textContent:e}),n=document.head.getElementsByTagName("style")[0]||null;document.head.insertBefore(t,n)}};return Vue.defineAsyncComponent((()=>window["vue3-sfc-loader"].loadModule(e,t)))}let markdownConverter=null;function markdownToHtml(e,t){markdownConverter||(showdown.setOption("emoji","true"),showdown.setOption("strikethrough","true"),showdown.setOption("tables","true"),showdown.setOption("tablesHeaderId","true"),showdown.setOption("backslashEscapesHTMLTags","true"),showdown.setOption("excludeTrailingPunctuationFromURLs","true"),showdown.setOption("parseImgDimensions","true"),markdownConverter=new showdown.Converter);try{let n=markdownConverter.makeHtml(e);n=n.replace(/\[x\]/g,''),n=n.replace(/\[\s\]/g,'');const r=(new DOMParser).parseFromString(n,"text/html");return r.querySelectorAll("a").forEach((e=>{let n=e.getAttribute("href");n=n.replace(/^\//,""),n.startsWith("src/")&&t&&t.repositoryUrl&&(n=n.replace("src/",`${t.repositoryUrl.trimEnd("/")}/src/`)),n.startsWith("http")&&(e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer")),n.startsWith("#")||n.startsWith("http")||(n=n.replace(/^#/,""),n=`${window.location.origin}/#/${n}`),e.setAttribute("href",n)})),r.querySelectorAll("p > img").forEach((e=>{const t=e.getAttribute("alt"),n=e.getAttribute("title"),r=e.getAttribute("src");let o=e.getAttribute("height")||extractQueryParam(r,"h");o&&o.length>0&&!o.endsWith("px")&&!o.endsWith("vh")&&!o.endsWith("%")&&(o+="px");let i=e.getAttribute("width")||extractQueryParam(r,"w");i&&i.length>0&&!i.endsWith("px")&&!i.endsWith("vw")&&!i.endsWith("%")&&(i+="px");let s="";i&&i.length>0&&(s+=`width: ${i};`),o&&o.length>0&&(s+=`height: ${o};`);const a=`\n `;e.parentElement.replaceWith(createElementFromHtml(a))})),n=r.body.innerHTML,n}catch(e){return""}}boot().then((()=>{var e=document.createElement("div");e.id="q-app",e.appendChild(document.createElement("docs-layout")),document.body.prepend(e),window["sfc-loader-options"]={moduleCache:{vue:Vue},async getFile(e){const t=await fetch(e);if(!t.ok)throw Object.assign(new Error(t.statusText+" "+e),{res:t});return{getContentData:e=>e?t.arrayBuffer():t.text()}},addStyle(e){const t=Object.assign(document.createElement("style"),{textContent:e}),n=document.head.getElementsByTagName("style")[0]||null;document.head.insertBefore(t,n)}},fetch("./docs.config.json").then((e=>e.json())).then((e=>{"VERSION_NUMBER"===e.version&&(e.version="v0.0.1-dev");const t=new Vuex.Store({state:{config:e,packages:[]},mutations:{addPackage(e,t){e.packages||(e.packages=[]),e.packages.find((e=>e.name===t.name))||e.packages.push(t)}}}),n=Vue.createApp({components:{docsLayout:docsComponent("./components/docs-layout.vue")},setup:()=>({})});n.use(t),n.use(Quasar,{config:{}}),n.mount("#q-app")}))})).catch((e=>{})); \ No newline at end of file diff --git a/docs/main.js b/docs/main.js new file mode 100644 index 0000000..08979be --- /dev/null +++ b/docs/main.js @@ -0,0 +1,382 @@ +// functions: isScriptLoadedByUrl, isStyleLoadedByUrl, loadScript, loadScripts, unloadScript, loadLink, loadStyle, unloadStyle, loadStyles +function isScriptLoadedByUrl(e) { + return Boolean(document.querySelector(`script[src="${e}"]`)); +} +function isStyleLoadedByUrl(e) { + return Boolean(document.querySelector(`link[href="${e}"]`)); +} +function loadScript(e) { + return new Promise(function (t, n) { + let o = null; + const r = document.createElement("script"); + let i = ""; + if ("string" == typeof e) i = e; + else { + if (((i = e.src), e.id && e.id.length)) { + if (((o = document.getElementById(e.id)), o && !e.replace)) + return void t(i); + r.id = e.id; + } + (r.async = e.async || !1), + e.crossorigin && + e.crossorigin.length && + r.setAttribute("crossorigin", e.crossorigin), + e.integrity && + e.integrity.length && + r.setAttribute("integrity", e.integrity), + e.referrerpolicy && + e.referrerpolicy.length && + r.setAttribute("referrerpolicy", e.referrerpolicy); + } + (r.src = i), + isScriptLoadedByUrl(i) + ? t(i) + : ((r.onload = function () { + setTimeout(() => { + t(i); + }, 0); + }), + (r.onerror = function () { + setTimeout(() => { + n(r.src); + }, 0); + }), + o && o.remove(), + document.head.appendChild(r)); + }); +} +async function loadScripts(e) { + const t = []; + for (const n of e) + try { + const e = await loadScript(n); + t.push(e); + } catch (e) { + break; + } + return t; +} +function unloadScript(e) { + if (!e) return; + let t = document.getElementById(e); + t || (t = document.querySelector(`script[src="${e}"]`)), t && t.remove(); +} +function loadLink(e) { + return new Promise(function (t, n) { + let o = null; + const r = document.createElement("link"); + (r.rel = "stylesheet"), (r.type = "text/css"), (r.media = "all"); + let i = ""; + if ("string" == typeof e) i = e; + else if (((i = e.href), e.id && e.id.length)) { + if (((o = document.getElementById(e.id)), o && !e.replace)) + return void t(i); + r.id = e.id; + } + (r.href = i), + isStyleLoadedByUrl(i) + ? t(i) + : ((r.onload = function () { + setTimeout(() => { + t(i); + }, 0); + }), + (r.onerror = function () { + setTimeout(() => { + n(i); + }, 0); + }), + o && o.remove(), + document.head.appendChild(r)); + }); +} +const loadStyle = loadLink; +function unloadStyle(e) { + if (!e) return; + let t = document.getElementById(e); + t || (t = document.querySelector(`link[href="${e}"]`)), t && t.remove(); +} +function loadStyles(e) { + const t = []; + return ( + e.forEach((e) => { + t.push(loadLink(e)); + }), + Promise.all(t) + ); +} + +async function boot() { + await loadStyles([ + "https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons", + "https://cdn.jsdelivr.net/npm/quasar@2.17.4/dist/quasar.prod.css", + "https://cdn.jsdelivr.net/npm/highlight.js@11.10.0/styles/default.min.css", + "./docs.css", + ]); + // process loaders in parallel + await Promise.all([ + loadScripts([ + "https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js", + "https://cdn.jsdelivr.net/npm/vuex@4.1.0/dist/vuex.global.min.js", + "https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue3-sfc-loader.js", + "https://cdn.jsdelivr.net/npm/quasar@2.17.4/dist/quasar.umd.prod.js", + ]), + loadScripts([ + "https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js", + "https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js", + { + src: "https://cdn.jsdelivr.net/npm/showdown@2.1.0/dist/showdown.min.js", + crossorigin: "anonymous", + integrity: "sha256-iOtvu+DCcN3zOEruDJYg0HDgkKJuB8Z0Ia42yQO11kk=", + referrerpolicy: "no-referrer", + }, + ]), + ]); +} + +// from: https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value +// example: People.sort(dynamicSort("Name")); +function dynamicSort(property) { + var sortOrder = 1; + if (property[0] === "-") { + sortOrder = -1; + property = property.substr(1); + } + return function (a, b) { + /* + * next line works with strings and numbers, + * and you may want to customize it to your needs + */ + var result = + a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0; + return result * sortOrder; + }; +} + +/** + * Create a DOM element from an HTML string with a single root element + */ +function createElementFromHtml(html) { + var div = document.createElement("div"); + div.innerHTML = html.trim(); + return div.firstChild; +} + +function extractQueryParam(url, key, defaultValue) { + return new URL(url).searchParams.get(key) || defaultValue || null; +} + +function docsComponent(componentUrl) { + const options = { + moduleCache: { + vue: Vue, + }, + async getFile(url) { + const res = await fetch(url); + if (!res.ok) + throw Object.assign(new Error(res.statusText + " " + url), { res }); + return { + getContentData: (asBinary) => + asBinary ? res.arrayBuffer() : res.text(), + }; + }, + addStyle(textContent) { + const style = Object.assign(document.createElement("style"), { + textContent, + }); + const ref = document.head.getElementsByTagName("style")[0] || null; + document.head.insertBefore(style, ref); + }, + }; + return Vue.defineAsyncComponent(() => + window["vue3-sfc-loader"].loadModule(componentUrl, options) + ); +} + +let markdownConverter = null; +function markdownToHtml(markdown, config) { + if (!markdownConverter) { + // setup the showdown markdown converter + showdown.setOption("emoji", "true"); + showdown.setOption("strikethrough", "true"); + showdown.setOption("tables", "true"); + showdown.setOption("tablesHeaderId", "true"); + showdown.setOption("backslashEscapesHTMLTags", "true"); + showdown.setOption("excludeTrailingPunctuationFromURLs", "true"); + showdown.setOption("parseImgDimensions", "true"); + markdownConverter = new showdown.Converter(); + } + try { + let html = markdownConverter.makeHtml(markdown); + + // replace [x] with and + // [ ] with + // html = html.replace(/\[x\]/g, ''); + html = html.replace( + /\[x\]/g, + '' + ); + // html = html.replace(/\[\s\]/g, ''); + html = html.replace( + /\[\s\]/g, + '' + ); + + // WARNING: the following is a SPECIFIC implementation for this docs website + // parse the html string into a DOM object + // convert all relative links to absolute url hash links + const parser = new DOMParser(); + const doc = parser.parseFromString(html, "text/html"); + doc.querySelectorAll("a").forEach((a) => { + let href = a.getAttribute("href"); + + // strip slash from the beginning of the href using regex + href = href.replace(/^\//, ""); + + if (href.startsWith("src/") && config && config.repositoryUrl) { + href = href.replace( + "src/", + `${config.repositoryUrl.trimEnd("/")}/src/` + ); + } + if (href.startsWith("http")) { + a.setAttribute("target", "_blank"); + a.setAttribute("rel", "noopener noreferrer"); + } + if (!href.startsWith("#") && !href.startsWith("http")) { + // strip hash from the beginning of the href using regex + href = href.replace(/^#/, ""); + // make the href an absolute url hash link + href = `${window.location.origin}/#/${href}`; + } + + // set the href + a.setAttribute("href", href); + }); + // const replaceImgs = []; + doc.querySelectorAll("p > img").forEach((img) => { + const alt = img.getAttribute("alt"); + const title = img.getAttribute("title"); + const src = img.getAttribute("src"); + let h = img.getAttribute("height") || extractQueryParam(src, "h"); + if ( + h && + h.length > 0 && + !h.endsWith("px") && + !h.endsWith("vh") && + !h.endsWith("%") + ) { + h = h + "px"; + } + let w = img.getAttribute("width") || extractQueryParam(src, "w"); + if ( + w && + w.length > 0 && + !w.endsWith("px") && + !w.endsWith("vw") && + !w.endsWith("%") + ) { + w = w + "px"; + } + let styles = ""; + if (w && w.length > 0) styles += `width: ${w};`; + if (h && h.length > 0) styles += `height: ${h};`; + const newHtml = ` + `; + img.parentElement.replaceWith(createElementFromHtml(newHtml)); + }); + html = doc.body.innerHTML; + return html; + } catch (e) { + console.error("Unable to convert markdown to html", { markdown, error: e }); + return ""; + } +} + +boot() + .then(() => { + var a = document.createElement("div"); + a.id = "q-app"; + a.appendChild(document.createElement("docs-layout")); + document.body.prepend(a); + window["sfc-loader-options"] = { + moduleCache: { + vue: Vue, + }, + async getFile(url) { + const res = await fetch(url); + if (!res.ok) + throw Object.assign(new Error(res.statusText + " " + url), { res }); + return { + getContentData: (asBinary) => + asBinary ? res.arrayBuffer() : res.text(), + }; + }, + addStyle(textContent) { + const style = Object.assign(document.createElement("style"), { + textContent, + }); + const ref = document.head.getElementsByTagName("style")[0] || null; + document.head.insertBefore(style, ref); + }, + }; + + fetch("./docs.config.json") + .then((response) => response.json()) + .then((config) => { + if (config.version === "VERSION_NUMBER") { + config.version = "v0.0.1-dev"; + } + const vuex_store = new Vuex.Store({ + state: { + config, + packages: [], + }, + mutations: { + addPackage(state, package) { + if (!state.packages) state.packages = []; + if (!state.packages.find((p) => p.name === package.name)) { + state.packages.push(package); + } + }, + }, + }); + const app = Vue.createApp({ + components: { + docsLayout: docsComponent("./components/docs-layout.vue"), + }, + setup() { + return {}; + }, + }); + app.use(vuex_store); + app.use(Quasar, { + config: { + // brand: {}, + // ... + }, + }); + app.mount("#q-app"); + }); + }) + .catch((err) => { + console.error("Docs failed to load:", err); + }); diff --git a/package.json b/package.json index 0154e62..5522f1f 100644 --- a/package.json +++ b/package.json @@ -1,21 +1,12 @@ { - "name": "dappermatic", + "name": "mjczone.dappermatic", "version": "1.0.0", - "description": "[![.github/workflows/release.yml](https://github.com/mjczone/DapperMatic/actions/workflows/release.yml/badge.svg)](https://github.com/mjczone/DapperMatic/actions/workflows/release.yml)", + "description": "", "main": "index.js", - "directories": { - "doc": "docs", - "test": "tests" - }, "scripts": { - "docs:tools": "dotnet tool install DocFxTocGenerator -g && dotnet tool install DocLanguageTranslator -g && dotnet tool install DocLinkChecker -g && dotnet tool install DocFxOpenApi -g", - "docs:links": "DocLinkChecker -d ./docs -a", - "docs:toc:general": "DocFxTocGenerator -d ./docs/general -sr --indexing NotExists", - "docs:toc:services": "DocFxTocGenerator -d ./docs/services -sr --indexing NotExists", - "docs:install": "dotnet tool install docfx -g", - "docs:build": "docfx ./docs/docfx.json", "build": "dotnet build", - "tests": "dotnet test ./tests/DapperMatic.Tests/DapperMatic.Tests.csproj" + "docs": "npx serve ./docs/", + "test": "dotnet test" }, "keywords": [], "author": "", diff --git a/src/DapperMatic/DapperMatic.csproj b/src/DapperMatic/DapperMatic.csproj deleted file mode 100644 index 0792b59..0000000 --- a/src/DapperMatic/DapperMatic.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - DapperMatic - 0.0.1 - MJC - MJCZone Inc. - - Additional extensions leveraging Dapper. - - https://github.com/mjczone/DapperMatic - - - - - - - - - <_Parameter1>DapperMatic.Tests - - - - diff --git a/src/DapperMatic/DotnetTypeDescriptor.cs b/src/DapperMatic/DotnetTypeDescriptor.cs deleted file mode 100644 index c58f11e..0000000 --- a/src/DapperMatic/DotnetTypeDescriptor.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System.Text; - -namespace DapperMatic -{ - /// - /// Describes a .NET type with its SQL type properties. - /// - public class DotnetTypeDescriptor - { - /// - /// Initializes a new instance of the class. - /// - /// The .NET type. - /// The length of the type. - /// The precision of the type. - /// The scale of the type. - /// Indicates if the type is auto-incrementing. - /// Indicates if the type is Unicode. - /// Indicates if the type has a fixed length. - public DotnetTypeDescriptor( - Type dotnetType, - int? length = null, - int? precision = null, - int? scale = null, - bool? isAutoIncrementing = null, - bool? isUnicode = null, - bool? isFixedLength = null - ) - { - DotnetType = - dotnetType?.OrUnderlyingTypeIfNullable() - ?? throw new ArgumentNullException(nameof(dotnetType)); - Length = length; - Precision = precision; - Scale = scale; - IsAutoIncrementing = isAutoIncrementing; - IsUnicode = isUnicode; - IsFixedLength = isFixedLength; - } - - /// - /// Gets or sets the .NET type. - /// - public Type DotnetType { get; set; } - - /// - /// Gets or sets the length of the type. - /// - public int? Length { get; set; } - - /// - /// Gets or sets the precision of the type. - /// - public int? Precision { get; set; } - - /// - /// Gets or sets the scale of the type. - /// - public int? Scale { get; set; } - - /// - /// Gets or sets a value indicating whether the type is auto-incrementing. - /// - public bool? IsAutoIncrementing { get; set; } - - /// - /// Gets or sets a value indicating whether the type is Unicode. - /// - public bool? IsUnicode { get; set; } - - /// - /// Gets or sets a value indicating whether the type has a fixed length. - /// - public bool? IsFixedLength { get; set; } - - /// - /// Describes the object as a string. - /// - /// The string representation of the object. - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append(DotnetType.GetFriendlyName()); - if (Length.GetValueOrDefault(0) > 0) - { - sb.Append($" length({Length})"); - } - - if (Precision.GetValueOrDefault(0) > 0) - { - if (Scale.GetValueOrDefault(0) > 0) - { - sb.Append($" precision({Precision},{Scale})"); - } - else - { - sb.Append($" precision({Precision})"); - } - } - - if (IsAutoIncrementing.GetValueOrDefault(false)) - { - sb.Append(" auto_increment"); - } - - if (IsUnicode.GetValueOrDefault(false)) - { - sb.Append(" unicode"); - } - - return sb.ToString(); - } - } -} diff --git a/src/DapperMatic/GlobalSuppressions.cs b/src/DapperMatic/GlobalSuppressions.cs deleted file mode 100644 index bd2b237..0000000 --- a/src/DapperMatic/GlobalSuppressions.cs +++ /dev/null @@ -1,109 +0,0 @@ -// // This file is used by Code Analysis to maintain SuppressMessage -// // attributes that are applied to this project. -// // Project-level suppressions either have no target or are given -// // a specific target and scoped to a namespace, type, member, etc. - -// using System.Diagnostics.CodeAnalysis; - -// [assembly: SuppressMessage( -// "StyleCop.CSharp.OrderingRules", -// "SA1200:Using directives should be placed correctly", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.ReadabilityRules", -// "SA1111:Closing parenthesis should be on line of last parameter", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.SpacingRules", -// "SA1009:Closing parenthesis should be spaced correctly", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.LayoutRules", -// "SA1503:Braces should not be omitted", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.SpacingRules", -// "SA1000:Keywords should be spaced correctly", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.LayoutRules", -// "SA1513:Closing brace should be followed by blank line", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.LayoutRules", -// "SA1515:Single-line comment should be preceded by blank line", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.LayoutRules", -// "SA1512:Single-line comments should not be followed by blank line", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.SpacingRules", -// "SA1027:Use tabs correctly", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.SpacingRules", -// "SA1010:Opening square brackets should be spaced correctly", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.SpacingRules", -// "SA1011:Closing square brackets should be spaced correctly", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.SpacingRules", -// "SA1028:Code should not contain trailing whitespace", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.ReadabilityRules", -// "SA1124:DoNotUseRegions", -// Justification = "Reviewed." -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.ReadabilityRules", -// "SA1118:Parameter must not span multiple lines", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.NamingRules", -// "SA1310:Field names should not contain underscore", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.NamingRules", -// "SA1303:Const field names should begin with upper-case letter", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.OrderingRules", -// "SA1206:Declaration keywords should follow order", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.LayoutRules", -// "SA1502:Element should not be on a single line", -// Justification = "Reviewed" -// )] -// [assembly: SuppressMessage( -// "StyleCop.CSharp.OrderingRules", -// "SA1204:Static elements should appear before instance elements", -// Justification = "Reviewed" -// )] - -// // Documentation rules -// [assembly: SuppressMessage( -// "StyleCop.CSharp.DocumentationRules", -// "SA1601:Partial elements should be documented", -// Justification = "Reviewed" -// )] diff --git a/src/Directory.Build.props b/src/Directory.Build.props index ef0601a..b73db00 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -4,12 +4,28 @@ All true net8.0 - 12.0 + latestmajor enable enable - True true + True + + README.md + + + + MJC + MJCZone Inc. + Copyright © 2024 + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive @@ -20,4 +36,10 @@ all + + + + + + diff --git a/src/DapperMatic/Converters/DotnetTypeToSqlTypeConverter.cs b/src/MJCZone.DapperMatic/Converters/DotnetTypeToSqlTypeConverter.cs similarity index 95% rename from src/DapperMatic/Converters/DotnetTypeToSqlTypeConverter.cs rename to src/MJCZone.DapperMatic/Converters/DotnetTypeToSqlTypeConverter.cs index 70bc97a..f7498c4 100644 --- a/src/DapperMatic/Converters/DotnetTypeToSqlTypeConverter.cs +++ b/src/MJCZone.DapperMatic/Converters/DotnetTypeToSqlTypeConverter.cs @@ -1,34 +1,34 @@ -namespace DapperMatic.Converters; - -/// -/// .NET Type to SQL Type converter. -/// -public class DotnetTypeToSqlTypeConverter - : IDbTypeConverter -{ - /// - /// Initializes a new instance of the class. - /// - /// The function to use for converting to . - public DotnetTypeToSqlTypeConverter(Func convertFunc) - { - ConvertFunc = convertFunc ?? throw new ArgumentNullException(nameof(convertFunc)); - } - - /// - /// Gets the function used for converting to . - /// - public Func ConvertFunc { get; } - - /// - /// Tries to convert a to a . - /// - /// The to convert from. - /// The converted , if the conversion was successful. - /// True if the conversion was successful; otherwise, false. - public bool TryConvert(DotnetTypeDescriptor from, out SqlTypeDescriptor? to) - { - to = ConvertFunc(from); - return to != null; - } -} +namespace MJCZone.DapperMatic.Converters; + +/// +/// .NET Type to SQL Type converter. +/// +public class DotnetTypeToSqlTypeConverter + : IDbTypeConverter +{ + /// + /// Initializes a new instance of the class. + /// + /// The function to use for converting to . + public DotnetTypeToSqlTypeConverter(Func convertFunc) + { + ConvertFunc = convertFunc ?? throw new ArgumentNullException(nameof(convertFunc)); + } + + /// + /// Gets the function used for converting to . + /// + public Func ConvertFunc { get; } + + /// + /// Tries to convert a to a . + /// + /// The to convert from. + /// The converted , if the conversion was successful. + /// True if the conversion was successful; otherwise, false. + public bool TryConvert(DotnetTypeDescriptor from, out SqlTypeDescriptor? to) + { + to = ConvertFunc(from); + return to != null; + } +} diff --git a/src/DapperMatic/Converters/IDbTypeConverter.cs b/src/MJCZone.DapperMatic/Converters/IDbTypeConverter.cs similarity index 92% rename from src/DapperMatic/Converters/IDbTypeConverter.cs rename to src/MJCZone.DapperMatic/Converters/IDbTypeConverter.cs index b914c19..fb9d518 100644 --- a/src/DapperMatic/Converters/IDbTypeConverter.cs +++ b/src/MJCZone.DapperMatic/Converters/IDbTypeConverter.cs @@ -1,4 +1,4 @@ -namespace DapperMatic.Converters; +namespace MJCZone.DapperMatic.Converters; /// /// Interface for a type of database type conversion. diff --git a/src/DapperMatic/Converters/SqlTypeToDotnetTypeConverter.cs b/src/MJCZone.DapperMatic/Converters/SqlTypeToDotnetTypeConverter.cs similarity index 95% rename from src/DapperMatic/Converters/SqlTypeToDotnetTypeConverter.cs rename to src/MJCZone.DapperMatic/Converters/SqlTypeToDotnetTypeConverter.cs index f183bdf..8bab49d 100644 --- a/src/DapperMatic/Converters/SqlTypeToDotnetTypeConverter.cs +++ b/src/MJCZone.DapperMatic/Converters/SqlTypeToDotnetTypeConverter.cs @@ -1,34 +1,34 @@ -namespace DapperMatic.Converters; - -/// -/// Converts a to a . -/// -public class SqlTypeToDotnetTypeConverter - : IDbTypeConverter -{ - /// - /// Initializes a new instance of the class. - /// - /// The function to use for converting to . - public SqlTypeToDotnetTypeConverter(Func convertFunc) - { - ConvertFunc = convertFunc ?? throw new ArgumentNullException(nameof(convertFunc)); - } - - /// - /// Gets the function used for converting to . - /// - public Func ConvertFunc { get; } - - /// - /// Tries to convert a to a . - /// - /// The to convert from. - /// The converted , if the conversion was successful. - /// True if the conversion was successful; otherwise, false. - public bool TryConvert(SqlTypeDescriptor from, out DotnetTypeDescriptor? to) - { - to = ConvertFunc(from); - return to != null; - } -} +namespace MJCZone.DapperMatic.Converters; + +/// +/// Converts a to a . +/// +public class SqlTypeToDotnetTypeConverter + : IDbTypeConverter +{ + /// + /// Initializes a new instance of the class. + /// + /// The function to use for converting to . + public SqlTypeToDotnetTypeConverter(Func convertFunc) + { + ConvertFunc = convertFunc ?? throw new ArgumentNullException(nameof(convertFunc)); + } + + /// + /// Gets the function used for converting to . + /// + public Func ConvertFunc { get; } + + /// + /// Tries to convert a to a . + /// + /// The to convert from. + /// The converted , if the conversion was successful. + /// True if the conversion was successful; otherwise, false. + public bool TryConvert(SqlTypeDescriptor from, out DotnetTypeDescriptor? to) + { + to = ConvertFunc(from); + return to != null; + } +} diff --git a/src/DapperMatic/DataAnnotations/DxCheckConstraintAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmCheckConstraintAttribute.cs similarity index 79% rename from src/DapperMatic/DataAnnotations/DxCheckConstraintAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmCheckConstraintAttribute.cs index 51c8943..f6d5bd9 100644 --- a/src/DapperMatic/DataAnnotations/DxCheckConstraintAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmCheckConstraintAttribute.cs @@ -1,22 +1,22 @@ -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Check Constraint Attribute. /// /// -/// [DxCheckConstraint("Age > 18")] +/// [DmCheckConstraint("Age > 18")] /// public int Age { get; set; } /// ... /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)] -public sealed class DxCheckConstraintAttribute : Attribute +public sealed class DmCheckConstraintAttribute : Attribute { /// - /// Initializes a new instance of the class with the specified expression. + /// Initializes a new instance of the class with the specified expression. /// /// The check constraint expression. /// Thrown when the expression is null or whitespace. - public DxCheckConstraintAttribute(string expression) + public DmCheckConstraintAttribute(string expression) { if (string.IsNullOrWhiteSpace(expression)) { @@ -27,12 +27,12 @@ public DxCheckConstraintAttribute(string expression) } /// - /// Initializes a new instance of the class with the specified constraint name and expression. + /// Initializes a new instance of the class with the specified constraint name and expression. /// /// The name of the check constraint. /// The check constraint expression. /// Thrown when the constraint name or expression is null or whitespace. - public DxCheckConstraintAttribute(string constraintName, string expression) + public DmCheckConstraintAttribute(string constraintName, string expression) { if (string.IsNullOrWhiteSpace(constraintName)) { diff --git a/src/DapperMatic/DataAnnotations/DxColumnAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmColumnAttribute.cs similarity index 91% rename from src/DapperMatic/DataAnnotations/DxColumnAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmColumnAttribute.cs index d077537..4e4662b 100644 --- a/src/DapperMatic/DataAnnotations/DxColumnAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmColumnAttribute.cs @@ -1,15 +1,15 @@ -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Attribute to define a database column. /// [AttributeUsage(AttributeTargets.Property)] -public sealed class DxColumnAttribute : Attribute +public sealed class DmColumnAttribute : Attribute { /// - /// Initializes a new instance of the class representing a column in a database table. + /// Initializes a new instance of the class representing a column in a database table. /// /// The name of the column. /// The data type of the column as defined by the database provider. Can be null if not specified. @@ -36,7 +36,7 @@ public sealed class DxColumnAttribute : Attribute /// The name of the referenced column in the referenced table for foreign key columns. Can be null if not specified. /// The action to take when a referenced row is deleted. Can be null if not specified. /// The action to take when a referenced row is updated. Can be null if not specified. - public DxColumnAttribute( + public DmColumnAttribute( string columnName, string? providerDataType = null, int? length = null, @@ -52,8 +52,8 @@ public DxColumnAttribute( bool isForeignKey = false, string? referencedTableName = null, string? referencedColumnName = null, - DxForeignKeyAction? onDelete = null, - DxForeignKeyAction? onUpdate = null + DmForeignKeyAction? onDelete = null, + DmForeignKeyAction? onUpdate = null ) { ColumnName = columnName; @@ -154,10 +154,10 @@ public DxColumnAttribute( /// /// Gets the action to perform on delete. /// - public DxForeignKeyAction? OnDelete { get; } + public DmForeignKeyAction? OnDelete { get; } /// /// Gets the action to perform on update. /// - public DxForeignKeyAction? OnUpdate { get; } + public DmForeignKeyAction? OnUpdate { get; } } diff --git a/src/DapperMatic/DataAnnotations/DxDefaultConstraintAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmDefaultConstraintAttribute.cs similarity index 77% rename from src/DapperMatic/DataAnnotations/DxDefaultConstraintAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmDefaultConstraintAttribute.cs index e0388f6..131c9dc 100644 --- a/src/DapperMatic/DataAnnotations/DxDefaultConstraintAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmDefaultConstraintAttribute.cs @@ -1,21 +1,21 @@ -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Attribute to define a default constraint on a property. /// /// -/// [DxDefaultConstraint("0")] +/// [DmDefaultConstraint("0")] /// public int Age { get; set; } /// ... /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] -public sealed class DxDefaultConstraintAttribute : Attribute +public sealed class DmDefaultConstraintAttribute : Attribute { /// - /// Initializes a new instance of the class with an expression. + /// Initializes a new instance of the class with an expression. /// /// The default value expression. - public DxDefaultConstraintAttribute(string expression) + public DmDefaultConstraintAttribute(string expression) { if (string.IsNullOrWhiteSpace(expression)) { @@ -26,11 +26,11 @@ public DxDefaultConstraintAttribute(string expression) } /// - /// Initializes a new instance of the class with a constraint name and expression. + /// Initializes a new instance of the class with a constraint name and expression. /// /// The name of the constraint. /// The default value expression. - public DxDefaultConstraintAttribute(string constraintName, string expression) + public DmDefaultConstraintAttribute(string constraintName, string expression) { if (string.IsNullOrWhiteSpace(constraintName)) { diff --git a/src/DapperMatic/DataAnnotations/DxForeignKeyConstraintAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmForeignKeyConstraintAttribute.cs similarity index 75% rename from src/DapperMatic/DataAnnotations/DxForeignKeyConstraintAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmForeignKeyConstraintAttribute.cs index 8962c9b..dd62324 100644 --- a/src/DapperMatic/DataAnnotations/DxForeignKeyConstraintAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmForeignKeyConstraintAttribute.cs @@ -1,30 +1,30 @@ -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Attribute to define foreign key constraints on a class or property. /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true)] -public sealed class DxForeignKeyConstraintAttribute : Attribute +public sealed class DmForeignKeyConstraintAttribute : Attribute { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Constructor for single-column foreign key constraint. /// /// The name of the source column in the foreign key constraint. /// The type of the referenced entity in the foreign key constraint. /// The name of the referenced column in the foreign key constraint. Optional. /// The name of the foreign key constraint. Optional. - /// The action to take when a referenced row is deleted. Default is . - /// The action to take when a referenced row is updated. Default is . - public DxForeignKeyConstraintAttribute( + /// The action to take when a referenced row is deleted. Default is . + /// The action to take when a referenced row is updated. Default is . + public DmForeignKeyConstraintAttribute( string sourceColumnName, Type referencedType, string? referencedColumnName = null, string? constraintName = null, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction ) { ConstraintName = constraintName; @@ -38,22 +38,22 @@ public DxForeignKeyConstraintAttribute( } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Constructor for multi-column foreign key constraint (composite keys). /// /// The names of the source columns in the foreign key constraint. /// The type of the referenced entity in the foreign key constraint. /// The names of the referenced columns in the foreign key constraint. Optional. /// The name of the foreign key constraint. Optional. - /// The action to take when a referenced row is deleted. Default is . - /// The action to take when a referenced row is updated. Default is . - public DxForeignKeyConstraintAttribute( + /// The action to take when a referenced row is deleted. Default is . + /// The action to take when a referenced row is updated. Default is . + public DmForeignKeyConstraintAttribute( string[] sourceColumnNames, Type referencedType, string[]? referencedColumnNames = null, string? constraintName = null, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction ) { ConstraintName = constraintName; @@ -68,22 +68,22 @@ public DxForeignKeyConstraintAttribute( } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Constructor for single-column foreign key constraint. /// /// The name of the source column in the foreign key constraint. /// The name of the referenced table in the foreign key constraint. /// The name of the referenced column in the foreign key constraint. /// The name of the foreign key constraint. Optional. - /// The action to take when a referenced row is deleted. Default is . - /// The action to take when a referenced row is updated. Default is . - public DxForeignKeyConstraintAttribute( + /// The action to take when a referenced row is deleted. Default is . + /// The action to take when a referenced row is updated. Default is . + public DmForeignKeyConstraintAttribute( string sourceColumnName, string referencedTableName, string referencedColumnName, string? constraintName = null, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction ) { ConstraintName = constraintName; @@ -95,22 +95,22 @@ public DxForeignKeyConstraintAttribute( } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Constructor for multi-column foreign key constraint (composite keys). /// /// The names of the source columns in the foreign key constraint. /// The name of the referenced table in the foreign key constraint. /// The names of the referenced columns in the foreign key constraint. /// The name of the foreign key constraint. Optional. - /// The action to take when a referenced row is deleted. Default is . - /// The action to take when a referenced row is updated. Default is . - public DxForeignKeyConstraintAttribute( + /// The action to take when a referenced row is deleted. Default is . + /// The action to take when a referenced row is updated. Default is . + public DmForeignKeyConstraintAttribute( string[] sourceColumnNames, string referencedTableName, string[] referencedColumnNames, string? constraintName = null, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction ) { ConstraintName = constraintName; @@ -122,20 +122,20 @@ public DxForeignKeyConstraintAttribute( } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Constructor for single-column foreign key constraint. /// /// The type of the referenced entity in the foreign key constraint. /// The name of the referenced column in the foreign key constraint. Optional. /// The name of the foreign key constraint. Optional. - /// The action to take when a referenced row is deleted. Default is . - /// The action to take when a referenced row is updated. Default is . - public DxForeignKeyConstraintAttribute( + /// The action to take when a referenced row is deleted. Default is . + /// The action to take when a referenced row is updated. Default is . + public DmForeignKeyConstraintAttribute( Type referencedType, string? referencedColumnName = null, string? constraintName = null, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction ) { ConstraintName = constraintName; @@ -148,20 +148,20 @@ public DxForeignKeyConstraintAttribute( } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Constructor for single-column foreign key constraint. /// /// The name of the referenced table in the foreign key constraint. /// The name of the referenced column in the foreign key constraint. Optional. /// The name of the foreign key constraint. Optional. - /// The action to take when a referenced row is deleted. Default is . - /// The action to take when a referenced row is updated. Default is . - public DxForeignKeyConstraintAttribute( + /// The action to take when a referenced row is deleted. Default is . + /// The action to take when a referenced row is updated. Default is . + public DmForeignKeyConstraintAttribute( string referencedTableName, string? referencedColumnName = null, string? constraintName = null, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction ) { ConstraintName = constraintName; @@ -201,10 +201,10 @@ public DxForeignKeyConstraintAttribute( /// /// Gets the action to take when a referenced row is deleted. /// - public DxForeignKeyAction? OnDelete { get; } + public DmForeignKeyAction? OnDelete { get; } /// /// Gets the action to take when a referenced row is updated. /// - public DxForeignKeyAction? OnUpdate { get; } + public DmForeignKeyAction? OnUpdate { get; } } diff --git a/src/DapperMatic/DataAnnotations/DxIgnoreAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmIgnoreAttribute.cs similarity index 53% rename from src/DapperMatic/DataAnnotations/DxIgnoreAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmIgnoreAttribute.cs index 7f3514f..235340d 100644 --- a/src/DapperMatic/DataAnnotations/DxIgnoreAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmIgnoreAttribute.cs @@ -1,7 +1,7 @@ -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Attribute to ignore a property in the mapping. /// [AttributeUsage(AttributeTargets.Property)] -public sealed class DxIgnoreAttribute : Attribute { } +public sealed class DmIgnoreAttribute : Attribute { } diff --git a/src/DapperMatic/DataAnnotations/DxIndexAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmIndexAttribute.cs similarity index 69% rename from src/DapperMatic/DataAnnotations/DxIndexAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmIndexAttribute.cs index 03ab8d8..419f7f8 100644 --- a/src/DapperMatic/DataAnnotations/DxIndexAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmIndexAttribute.cs @@ -1,44 +1,44 @@ -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Attribute to define a database index. /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true)] -public sealed class DxIndexAttribute : Attribute +public sealed class DmIndexAttribute : Attribute { /// - /// Initializes a new instance of the class with the specified constraint name, uniqueness, and column names. + /// Initializes a new instance of the class with the specified constraint name, uniqueness, and column names. /// /// The name of the index constraint. /// A value indicating whether the index is unique. /// The names of the columns included in the index. - public DxIndexAttribute(string constraintName, bool isUnique, params string[] columnNames) + public DmIndexAttribute(string constraintName, bool isUnique, params string[] columnNames) { IndexName = constraintName; IsUnique = isUnique; - Columns = columnNames.Select(columnName => new DxOrderedColumn(columnName)).ToArray(); + Columns = columnNames.Select(columnName => new DmOrderedColumn(columnName)).ToArray(); } /// - /// Initializes a new instance of the class with the specified uniqueness and column names. + /// Initializes a new instance of the class with the specified uniqueness and column names. /// /// A value indicating whether the index is unique. /// The names of the columns included in the index. - public DxIndexAttribute(bool isUnique, params string[] columnNames) + public DmIndexAttribute(bool isUnique, params string[] columnNames) { IsUnique = isUnique; - Columns = columnNames.Select(columnName => new DxOrderedColumn(columnName)).ToArray(); + Columns = columnNames.Select(columnName => new DmOrderedColumn(columnName)).ToArray(); } /// - /// Initializes a new instance of the class with the specified constraint name, uniqueness, and columns. + /// Initializes a new instance of the class with the specified constraint name, uniqueness, and columns. /// /// The name of the index constraint. /// A value indicating whether the index is unique. /// The columns included in the index. - public DxIndexAttribute(string constraintName, bool isUnique, params DxOrderedColumn[] columns) + public DmIndexAttribute(string constraintName, bool isUnique, params DmOrderedColumn[] columns) { IndexName = constraintName; IsUnique = isUnique; @@ -46,11 +46,11 @@ public DxIndexAttribute(string constraintName, bool isUnique, params DxOrderedCo } /// - /// Initializes a new instance of the class with the specified uniqueness and columns. + /// Initializes a new instance of the class with the specified uniqueness and columns. /// /// A value indicating whether the index is unique. /// The columns included in the index. - public DxIndexAttribute(bool isUnique, params DxOrderedColumn[] columns) + public DmIndexAttribute(bool isUnique, params DmOrderedColumn[] columns) { IsUnique = isUnique; Columns = columns; @@ -69,5 +69,5 @@ public DxIndexAttribute(bool isUnique, params DxOrderedColumn[] columns) /// /// Gets the columns included in the index. /// - public DxOrderedColumn[]? Columns { get; } + public DmOrderedColumn[]? Columns { get; } } diff --git a/src/DapperMatic/DataAnnotations/DxPrimaryKeyConstraintAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmPrimaryKeyConstraintAttribute.cs similarity index 60% rename from src/DapperMatic/DataAnnotations/DxPrimaryKeyConstraintAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmPrimaryKeyConstraintAttribute.cs index c87f114..4db3f00 100644 --- a/src/DapperMatic/DataAnnotations/DxPrimaryKeyConstraintAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmPrimaryKeyConstraintAttribute.cs @@ -1,45 +1,45 @@ -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Attribute to define a primary key constraint on a table. /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true)] -public sealed class DxPrimaryKeyConstraintAttribute : Attribute +public sealed class DmPrimaryKeyConstraintAttribute : Attribute { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public DxPrimaryKeyConstraintAttribute() { } + public DmPrimaryKeyConstraintAttribute() { } /// - /// Initializes a new instance of the class with a constraint name. + /// Initializes a new instance of the class with a constraint name. /// /// The name of the constraint. - public DxPrimaryKeyConstraintAttribute(string constraintName) + public DmPrimaryKeyConstraintAttribute(string constraintName) { ConstraintName = constraintName; } /// - /// Initializes a new instance of the class with a constraint name and column names. + /// Initializes a new instance of the class with a constraint name and column names. /// /// The name of the constraint. /// The column names that form the primary key constraint. - public DxPrimaryKeyConstraintAttribute(string constraintName, params string[] columnNames) + public DmPrimaryKeyConstraintAttribute(string constraintName, params string[] columnNames) { ConstraintName = constraintName; - Columns = columnNames.Select(columnName => new DxOrderedColumn(columnName)).ToArray(); + Columns = columnNames.Select(columnName => new DmOrderedColumn(columnName)).ToArray(); } /// - /// Initializes a new instance of the class with column names. + /// Initializes a new instance of the class with column names. /// /// The column names that form the primary key constraint. - public DxPrimaryKeyConstraintAttribute(string[] columnNames) + public DmPrimaryKeyConstraintAttribute(string[] columnNames) { - Columns = columnNames.Select(columnName => new DxOrderedColumn(columnName)).ToArray(); + Columns = columnNames.Select(columnName => new DmOrderedColumn(columnName)).ToArray(); } /// @@ -50,5 +50,5 @@ public DxPrimaryKeyConstraintAttribute(string[] columnNames) /// /// Gets the columns that form the primary key constraint. /// - public DxOrderedColumn[]? Columns { get; } + public DmOrderedColumn[]? Columns { get; } } diff --git a/src/DapperMatic/DataAnnotations/DxTableAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmTableAttribute.cs similarity index 65% rename from src/DapperMatic/DataAnnotations/DxTableAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmTableAttribute.cs index cf12eba..6e2482c 100644 --- a/src/DapperMatic/DataAnnotations/DxTableAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmTableAttribute.cs @@ -1,31 +1,31 @@ -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Attribute to define the table name and schema for a class. /// [AttributeUsage(AttributeTargets.Class)] -public sealed class DxTableAttribute : Attribute +public sealed class DmTableAttribute : Attribute { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public DxTableAttribute() { } + public DmTableAttribute() { } /// - /// Initializes a new instance of the class with a table name. + /// Initializes a new instance of the class with a table name. /// /// The name of the table. - public DxTableAttribute(string? tableName) + public DmTableAttribute(string? tableName) { TableName = tableName; } /// - /// Initializes a new instance of the class with a schema name and table name. + /// Initializes a new instance of the class with a schema name and table name. /// /// The name of the schema. /// The name of the table. - public DxTableAttribute(string? schemaName, string? tableName) + public DmTableAttribute(string? schemaName, string? tableName) { SchemaName = schemaName; TableName = tableName; diff --git a/src/DapperMatic/DataAnnotations/DxUniqueConstraintAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmUniqueConstraintAttribute.cs similarity index 63% rename from src/DapperMatic/DataAnnotations/DxUniqueConstraintAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmUniqueConstraintAttribute.cs index d5ebe16..b361411 100644 --- a/src/DapperMatic/DataAnnotations/DxUniqueConstraintAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmUniqueConstraintAttribute.cs @@ -1,49 +1,49 @@ -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Attribute to define a unique constraint on a table. /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true)] -public sealed class DxUniqueConstraintAttribute : Attribute +public sealed class DmUniqueConstraintAttribute : Attribute { /// - /// Initializes a new instance of the class with a constraint name and column names. + /// Initializes a new instance of the class with a constraint name and column names. /// /// The name of the constraint. /// The column names that form the unique constraint. - public DxUniqueConstraintAttribute(string constraintName, params string[] columnNames) + public DmUniqueConstraintAttribute(string constraintName, params string[] columnNames) { ConstraintName = constraintName; - Columns = columnNames.Select(columnName => new DxOrderedColumn(columnName)).ToArray(); + Columns = columnNames.Select(columnName => new DmOrderedColumn(columnName)).ToArray(); } /// - /// Initializes a new instance of the class with column names. + /// Initializes a new instance of the class with column names. /// /// The column names that form the unique constraint. - public DxUniqueConstraintAttribute(params string[] columnNames) + public DmUniqueConstraintAttribute(params string[] columnNames) { - Columns = columnNames.Select(columnName => new DxOrderedColumn(columnName)).ToArray(); + Columns = columnNames.Select(columnName => new DmOrderedColumn(columnName)).ToArray(); } /// - /// Initializes a new instance of the class with a constraint name and ordered columns. + /// Initializes a new instance of the class with a constraint name and ordered columns. /// /// The name of the constraint. /// The ordered columns that form the unique constraint. - public DxUniqueConstraintAttribute(string constraintName, params DxOrderedColumn[] columns) + public DmUniqueConstraintAttribute(string constraintName, params DmOrderedColumn[] columns) { ConstraintName = constraintName; Columns = columns; } /// - /// Initializes a new instance of the class with ordered columns. + /// Initializes a new instance of the class with ordered columns. /// /// The ordered columns that form the unique constraint. - public DxUniqueConstraintAttribute(params DxOrderedColumn[] columns) + public DmUniqueConstraintAttribute(params DmOrderedColumn[] columns) { Columns = columns; } @@ -56,5 +56,5 @@ public DxUniqueConstraintAttribute(params DxOrderedColumn[] columns) /// /// Gets the columns that form the unique constraint. /// - public DxOrderedColumn[]? Columns { get; } + public DmOrderedColumn[]? Columns { get; } } diff --git a/src/DapperMatic/DataAnnotations/DxViewAttribute.cs b/src/MJCZone.DapperMatic/DataAnnotations/DmViewAttribute.cs similarity index 69% rename from src/DapperMatic/DataAnnotations/DxViewAttribute.cs rename to src/MJCZone.DapperMatic/DataAnnotations/DmViewAttribute.cs index 08f6426..58a794f 100644 --- a/src/DapperMatic/DataAnnotations/DxViewAttribute.cs +++ b/src/MJCZone.DapperMatic/DataAnnotations/DmViewAttribute.cs @@ -1,32 +1,32 @@ -namespace DapperMatic.DataAnnotations; +namespace MJCZone.DapperMatic.DataAnnotations; /// /// Attribute to define a database view. /// [AttributeUsage(AttributeTargets.Class)] -public sealed class DxViewAttribute : Attribute +public sealed class DmViewAttribute : Attribute { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public DxViewAttribute() { } + public DmViewAttribute() { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The SQL definition for the view. Use '{0}' to represent the schema name. - public DxViewAttribute(string definition) + public DmViewAttribute(string definition) { Definition = definition; } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The schema name. /// The view name. /// The SQL definition for the view. Use '{0}' to represent the schema name. - public DxViewAttribute(string? schemaName, string? viewName, string definition) + public DmViewAttribute(string? schemaName, string? viewName, string definition) { SchemaName = schemaName; ViewName = viewName; diff --git a/src/DapperMatic/DbConnectionExtensions_CheckConstraintMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_CheckConstraintMethods.cs similarity index 95% rename from src/DapperMatic/DbConnectionExtensions_CheckConstraintMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_CheckConstraintMethods.cs index ea0dbb3..d47e951 100644 --- a/src/DapperMatic/DbConnectionExtensions_CheckConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_CheckConstraintMethods.cs @@ -1,347 +1,347 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic; - -public static partial class DbConnectionExtensions -{ - #region IDatabaseCheckConstraintMethods - - /// - /// Checks if a check constraint exists in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the constraint exists, otherwise false. - public static async Task DoesCheckConstraintExistAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesCheckConstraintExistAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Checks if a check constraint exists on the specified column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the constraint exists, otherwise false. - public static async Task DoesCheckConstraintExistOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesCheckConstraintExistOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Creates a check constraint if it does not exist. - /// - /// The database connection. - /// The check constraint. - /// The transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - public static async Task CreateCheckConstraintIfNotExistsAsync( - this IDbConnection db, - DxCheckConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateCheckConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a check constraint if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The constraint name. - /// The constraint expression. - /// The transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - public static async Task CreateCheckConstraintIfNotExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? columnName, - string constraintName, - string expression, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateCheckConstraintIfNotExistsAsync( - db, - schemaName, - tableName, - columnName, - constraintName, - expression, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the check constraint with the specified name. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// The check constraint, or null if not found. - public static async Task GetCheckConstraintAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetCheckConstraintAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the name of the check constraint on the specified column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The name of the check constraint, or null if not found. - public static async Task GetCheckConstraintNameOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetCheckConstraintNameOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the names of the check constraints in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of check constraint names. - public static async Task> GetCheckConstraintNamesAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetCheckConstraintNamesAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the check constraint on the specified column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The check constraint, or null if not found. - public static async Task GetCheckConstraintOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetCheckConstraintOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the check constraints in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of check constraints. - public static async Task> GetCheckConstraintsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetCheckConstraintsAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops the check constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - public static async Task DropCheckConstraintIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropCheckConstraintIfExistsAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops the check constraint on the specified column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - public static async Task DropCheckConstraintOnColumnIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropCheckConstraintOnColumnIfExistsAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - #endregion // IDatabaseCheckConstraintMethods -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic; + +public static partial class DbConnectionExtensions +{ + #region IDatabaseCheckConstraintMethods + + /// + /// Checks if a check constraint exists in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the constraint exists, otherwise false. + public static async Task DoesCheckConstraintExistAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesCheckConstraintExistAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Checks if a check constraint exists on the specified column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the constraint exists, otherwise false. + public static async Task DoesCheckConstraintExistOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesCheckConstraintExistOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Creates a check constraint if it does not exist. + /// + /// The database connection. + /// The check constraint. + /// The transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + public static async Task CreateCheckConstraintIfNotExistsAsync( + this IDbConnection db, + DmCheckConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateCheckConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a check constraint if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The constraint name. + /// The constraint expression. + /// The transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + public static async Task CreateCheckConstraintIfNotExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? columnName, + string constraintName, + string expression, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateCheckConstraintIfNotExistsAsync( + db, + schemaName, + tableName, + columnName, + constraintName, + expression, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the check constraint with the specified name. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// The check constraint, or null if not found. + public static async Task GetCheckConstraintAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetCheckConstraintAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the name of the check constraint on the specified column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The name of the check constraint, or null if not found. + public static async Task GetCheckConstraintNameOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetCheckConstraintNameOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the names of the check constraints in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of check constraint names. + public static async Task> GetCheckConstraintNamesAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetCheckConstraintNamesAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the check constraint on the specified column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The check constraint, or null if not found. + public static async Task GetCheckConstraintOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetCheckConstraintOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the check constraints in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of check constraints. + public static async Task> GetCheckConstraintsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetCheckConstraintsAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops the check constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + public static async Task DropCheckConstraintIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropCheckConstraintIfExistsAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops the check constraint on the specified column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + public static async Task DropCheckConstraintOnColumnIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropCheckConstraintOnColumnIfExistsAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + #endregion // IDatabaseCheckConstraintMethods +} diff --git a/src/DapperMatic/DbConnectionExtensions_ColumnMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_ColumnMethods.cs similarity index 94% rename from src/DapperMatic/DbConnectionExtensions_ColumnMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_ColumnMethods.cs index 3765c89..e450b63 100644 --- a/src/DapperMatic/DbConnectionExtensions_ColumnMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_ColumnMethods.cs @@ -1,266 +1,266 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic; - -public static partial class DbConnectionExtensions -{ - #region IDatabaseColumnMethods - - /// - /// Checks if a column exists in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column exists, otherwise false. - public static async Task DoesColumnExistAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesColumnExistAsync(db, schemaName, tableName, columnName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Gets the details of a column in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// The column details, or null if the column does not exist. - public static async Task GetColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetColumnAsync(db, schemaName, tableName, columnName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Gets the names of columns in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// An optional filter for column names. - /// The transaction to use, or null. - /// The cancellation token. - /// A list of column names. - public static async Task> GetColumnNamesAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? columnNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetColumnNamesAsync(db, schemaName, tableName, columnNameFilter, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Gets the details of columns in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// An optional filter for column names. - /// The transaction to use, or null. - /// The cancellation token. - /// A list of column details. - public static async Task> GetColumnsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? columnNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetColumnsAsync(db, schemaName, tableName, columnNameFilter, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a column if it does not exist. - /// - /// The database connection. - /// The column details. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column was created, otherwise false. - public static async Task CreateColumnIfNotExistsAsync( - this IDbConnection db, - DxColumn column, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateColumnIfNotExistsAsync(db, column, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a column if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The .NET type of the column. - /// The provider-specific data type of the column. - /// The length of the column. - /// The precision of the column. - /// The scale of the column. - /// The check expression for the column. - /// The default expression for the column. - /// Whether the column is nullable. - /// Whether the column is a primary key. - /// Whether the column is auto-incremented. - /// Whether the column is unique. - /// Whether the column is indexed. - /// Whether the column is a foreign key. - /// The referenced table name for the foreign key. - /// The referenced column name for the foreign key. - /// The action to take on delete. - /// The action to take on update. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column was created, otherwise false. - public static async Task CreateColumnIfNotExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - Type dotnetType, - string? providerDataType = null, - int? length = null, - int? precision = null, - int? scale = null, - string? checkExpression = null, - string? defaultExpression = null, - bool isNullable = true, - bool isPrimaryKey = false, - bool isAutoIncrement = false, - bool isUnique = false, - bool isIndexed = false, - bool isForeignKey = false, - string? referencedTableName = null, - string? referencedColumnName = null, - DxForeignKeyAction? onDelete = null, - DxForeignKeyAction? onUpdate = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateColumnIfNotExistsAsync( - db, - schemaName, - tableName, - columnName, - dotnetType, - providerDataType, - length, - precision, - scale, - checkExpression, - defaultExpression, - isNullable, - isPrimaryKey, - isAutoIncrement, - isUnique, - isIndexed, - isForeignKey, - referencedTableName, - referencedColumnName, - onDelete, - onUpdate, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops a column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column was dropped, otherwise false. - public static async Task DropColumnIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropColumnIfExistsAsync(db, schemaName, tableName, columnName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Renames a column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The new column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column was renamed, otherwise false. - public static async Task RenameColumnIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - string newColumnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .RenameColumnIfExistsAsync( - db, - schemaName, - tableName, - columnName, - newColumnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - #endregion // IDatabaseColumnMethods -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic; + +public static partial class DbConnectionExtensions +{ + #region IDatabaseColumnMethods + + /// + /// Checks if a column exists in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column exists, otherwise false. + public static async Task DoesColumnExistAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesColumnExistAsync(db, schemaName, tableName, columnName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets the details of a column in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// The column details, or null if the column does not exist. + public static async Task GetColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetColumnAsync(db, schemaName, tableName, columnName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets the names of columns in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// An optional filter for column names. + /// The transaction to use, or null. + /// The cancellation token. + /// A list of column names. + public static async Task> GetColumnNamesAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? columnNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetColumnNamesAsync(db, schemaName, tableName, columnNameFilter, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets the details of columns in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// An optional filter for column names. + /// The transaction to use, or null. + /// The cancellation token. + /// A list of column details. + public static async Task> GetColumnsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? columnNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetColumnsAsync(db, schemaName, tableName, columnNameFilter, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a column if it does not exist. + /// + /// The database connection. + /// The column details. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column was created, otherwise false. + public static async Task CreateColumnIfNotExistsAsync( + this IDbConnection db, + DmColumn column, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateColumnIfNotExistsAsync(db, column, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a column if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The .NET type of the column. + /// The provider-specific data type of the column. + /// The length of the column. + /// The precision of the column. + /// The scale of the column. + /// The check expression for the column. + /// The default expression for the column. + /// Whether the column is nullable. + /// Whether the column is a primary key. + /// Whether the column is auto-incremented. + /// Whether the column is unique. + /// Whether the column is indexed. + /// Whether the column is a foreign key. + /// The referenced table name for the foreign key. + /// The referenced column name for the foreign key. + /// The action to take on delete. + /// The action to take on update. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column was created, otherwise false. + public static async Task CreateColumnIfNotExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + Type dotnetType, + string? providerDataType = null, + int? length = null, + int? precision = null, + int? scale = null, + string? checkExpression = null, + string? defaultExpression = null, + bool isNullable = true, + bool isPrimaryKey = false, + bool isAutoIncrement = false, + bool isUnique = false, + bool isIndexed = false, + bool isForeignKey = false, + string? referencedTableName = null, + string? referencedColumnName = null, + DmForeignKeyAction? onDelete = null, + DmForeignKeyAction? onUpdate = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateColumnIfNotExistsAsync( + db, + schemaName, + tableName, + columnName, + dotnetType, + providerDataType, + length, + precision, + scale, + checkExpression, + defaultExpression, + isNullable, + isPrimaryKey, + isAutoIncrement, + isUnique, + isIndexed, + isForeignKey, + referencedTableName, + referencedColumnName, + onDelete, + onUpdate, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops a column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column was dropped, otherwise false. + public static async Task DropColumnIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropColumnIfExistsAsync(db, schemaName, tableName, columnName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Renames a column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The new column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column was renamed, otherwise false. + public static async Task RenameColumnIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + string newColumnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .RenameColumnIfExistsAsync( + db, + schemaName, + tableName, + columnName, + newColumnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + #endregion // IDatabaseColumnMethods +} diff --git a/src/DapperMatic/DbConnectionExtensions_DatabaseMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_DatabaseMethods.cs similarity index 94% rename from src/DapperMatic/DbConnectionExtensions_DatabaseMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_DatabaseMethods.cs index 99a8489..3f7d1ba 100644 --- a/src/DapperMatic/DbConnectionExtensions_DatabaseMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_DatabaseMethods.cs @@ -1,91 +1,91 @@ -using System.Data; -using System.Diagnostics.CodeAnalysis; -using DapperMatic.Interfaces; -using DapperMatic.Providers; - -namespace DapperMatic; - -/// -/// Extension methods for . -/// -[SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "Reviewed")] -[SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global", Justification = "Reviewed")] -public static partial class DbConnectionExtensions -{ - #region IDatabaseMethods - - /// - /// Gets the of the database connection. - /// - /// The database connection. - /// The of the database connection. - public static DbProviderType GetDbProviderType(this IDbConnection db) - { - return Database(db).ProviderType; - } - - /// - /// Gets the version of the database. - /// - /// The database connection. - /// The transaction to use. - /// The cancellation token. - /// The version of the database. - public static async Task GetDatabaseVersionAsync( - this IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetDatabaseVersionAsync(db, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Gets the of the database connection. - /// - /// The database connection. - /// The of the database connection. - public static IDbProviderTypeMap GetProviderTypeMap(this IDbConnection db) - { - return Database(db).ProviderTypeMap; - } - - /// - /// Gets the .NET type descriptor from the SQL type. - /// - /// The database connection. - /// The SQL type. - /// The corresponding to the SQL type. - public static DotnetTypeDescriptor GetDotnetTypeFromSqlType( - this IDbConnection db, - string sqlType - ) - { - return Database(db).GetDotnetTypeFromSqlType(sqlType); - } - - /// - /// Gets the SQL type from the .NET type descriptor. - /// - /// The database connection. - /// The .NET type descriptor. - /// The SQL type corresponding to the .NET type descriptor. - public static string GetSqlTypeFromDotnetType( - this IDbConnection db, - DotnetTypeDescriptor descriptor - ) - { - return Database(db).GetSqlTypeFromDotnetType(descriptor); - } - - #endregion // IDatabaseMethods - - #region Private static methods - private static IDatabaseMethods Database(this IDbConnection db) - { - return DatabaseMethodsProvider.GetMethods(db); - } - #endregion // Private static methods -} +using System.Data; +using System.Diagnostics.CodeAnalysis; +using MJCZone.DapperMatic.Interfaces; +using MJCZone.DapperMatic.Providers; + +namespace MJCZone.DapperMatic; + +/// +/// Extension methods for . +/// +[SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "Reviewed")] +[SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global", Justification = "Reviewed")] +public static partial class DbConnectionExtensions +{ + #region IDatabaseMethods + + /// + /// Gets the of the database connection. + /// + /// The database connection. + /// The of the database connection. + public static DbProviderType GetDbProviderType(this IDbConnection db) + { + return Database(db).ProviderType; + } + + /// + /// Gets the version of the database. + /// + /// The database connection. + /// The transaction to use. + /// The cancellation token. + /// The version of the database. + public static async Task GetDatabaseVersionAsync( + this IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetDatabaseVersionAsync(db, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets the of the database connection. + /// + /// The database connection. + /// The of the database connection. + public static IDbProviderTypeMap GetProviderTypeMap(this IDbConnection db) + { + return Database(db).ProviderTypeMap; + } + + /// + /// Gets the .NET type descriptor from the SQL type. + /// + /// The database connection. + /// The SQL type. + /// The corresponding to the SQL type. + public static DotnetTypeDescriptor GetDotnetTypeFromSqlType( + this IDbConnection db, + string sqlType + ) + { + return Database(db).GetDotnetTypeFromSqlType(sqlType); + } + + /// + /// Gets the SQL type from the .NET type descriptor. + /// + /// The database connection. + /// The .NET type descriptor. + /// The SQL type corresponding to the .NET type descriptor. + public static string GetSqlTypeFromDotnetType( + this IDbConnection db, + DotnetTypeDescriptor descriptor + ) + { + return Database(db).GetSqlTypeFromDotnetType(descriptor); + } + + #endregion // IDatabaseMethods + + #region Private static methods + private static IDatabaseMethods Database(this IDbConnection db) + { + return DatabaseMethodsProvider.GetMethods(db); + } + #endregion // Private static methods +} diff --git a/src/DapperMatic/DbConnectionExtensions_DefaultConstraintMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_DefaultConstraintMethods.cs similarity index 94% rename from src/DapperMatic/DbConnectionExtensions_DefaultConstraintMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_DefaultConstraintMethods.cs index a381dd7..2ef7288 100644 --- a/src/DapperMatic/DbConnectionExtensions_DefaultConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_DefaultConstraintMethods.cs @@ -1,346 +1,346 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic; - -public static partial class DbConnectionExtensions -{ - #region IDatabaseDefaultConstraintMethods - - /// - /// Checks if a default constraint exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the constraint exists, otherwise false. - public static async Task DoesDefaultConstraintExistAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesDefaultConstraintExistAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Checks if a default constraint exists on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the constraint exists on the column, otherwise false. - public static async Task DoesDefaultConstraintExistOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesDefaultConstraintExistOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Creates a default constraint if it does not exist. - /// - /// The database connection. - /// The default constraint. - /// The transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - public static async Task CreateDefaultConstraintIfNotExistsAsync( - this IDbConnection db, - DxDefaultConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateDefaultConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a default constraint if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The constraint name. - /// The expression. - /// The transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - public static async Task CreateDefaultConstraintIfNotExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - string constraintName, - string expression, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateDefaultConstraintIfNotExistsAsync( - db, - schemaName, - tableName, - columnName, - constraintName, - expression, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets a default constraint. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// The default constraint. - public static async Task GetDefaultConstraintAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetDefaultConstraintAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the name of the default constraint on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The name of the default constraint on the column. - public static async Task GetDefaultConstraintNameOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetDefaultConstraintNameOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the names of default constraints. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of default constraint names. - public static async Task> GetDefaultConstraintNamesAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetDefaultConstraintNamesAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the default constraint on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The default constraint on the column. - public static async Task GetDefaultConstraintOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetDefaultConstraintOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the default constraints. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of default constraints. - public static async Task> GetDefaultConstraintsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetDefaultConstraintsAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops a default constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - public static async Task DropDefaultConstraintIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropDefaultConstraintIfExistsAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops a default constraint on a column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - public static async Task DropDefaultConstraintOnColumnIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropDefaultConstraintOnColumnIfExistsAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - #endregion // IDatabaseDefaultConstraintMethods -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic; + +public static partial class DbConnectionExtensions +{ + #region IDatabaseDefaultConstraintMethods + + /// + /// Checks if a default constraint exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the constraint exists, otherwise false. + public static async Task DoesDefaultConstraintExistAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesDefaultConstraintExistAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Checks if a default constraint exists on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the constraint exists on the column, otherwise false. + public static async Task DoesDefaultConstraintExistOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesDefaultConstraintExistOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Creates a default constraint if it does not exist. + /// + /// The database connection. + /// The default constraint. + /// The transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + public static async Task CreateDefaultConstraintIfNotExistsAsync( + this IDbConnection db, + DmDefaultConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateDefaultConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a default constraint if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The constraint name. + /// The expression. + /// The transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + public static async Task CreateDefaultConstraintIfNotExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + string constraintName, + string expression, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateDefaultConstraintIfNotExistsAsync( + db, + schemaName, + tableName, + columnName, + constraintName, + expression, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets a default constraint. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// The default constraint. + public static async Task GetDefaultConstraintAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetDefaultConstraintAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the name of the default constraint on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The name of the default constraint on the column. + public static async Task GetDefaultConstraintNameOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetDefaultConstraintNameOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the names of default constraints. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of default constraint names. + public static async Task> GetDefaultConstraintNamesAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetDefaultConstraintNamesAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the default constraint on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The default constraint on the column. + public static async Task GetDefaultConstraintOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetDefaultConstraintOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the default constraints. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of default constraints. + public static async Task> GetDefaultConstraintsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetDefaultConstraintsAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops a default constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + public static async Task DropDefaultConstraintIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropDefaultConstraintIfExistsAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops a default constraint on a column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + public static async Task DropDefaultConstraintOnColumnIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropDefaultConstraintOnColumnIfExistsAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + #endregion // IDatabaseDefaultConstraintMethods +} diff --git a/src/DapperMatic/DbConnectionExtensions_ForeignKeyConstraintMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_ForeignKeyConstraintMethods.cs similarity index 93% rename from src/DapperMatic/DbConnectionExtensions_ForeignKeyConstraintMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_ForeignKeyConstraintMethods.cs index 1a56d36..ee78c0f 100644 --- a/src/DapperMatic/DbConnectionExtensions_ForeignKeyConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_ForeignKeyConstraintMethods.cs @@ -1,355 +1,355 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic; - -public static partial class DbConnectionExtensions -{ - #region IDatabaseForeignKeyConstraintMethods - - /// - /// Checks if a foreign key constraint exists on a specific column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the foreign key constraint exists, otherwise false. - public static async Task DoesForeignKeyConstraintExistOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesForeignKeyConstraintExistOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Checks if a foreign key constraint exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the foreign key constraint exists, otherwise false. - public static async Task DoesForeignKeyConstraintExistAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesForeignKeyConstraintExistAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Creates a foreign key constraint if it does not exist. - /// - /// The database connection. - /// The foreign key constraint. - /// The transaction. - /// The cancellation token. - /// True if the foreign key constraint was created, otherwise false. - public static async Task CreateForeignKeyConstraintIfNotExistsAsync( - this IDbConnection db, - DxForeignKeyConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateForeignKeyConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a foreign key constraint if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The source columns. - /// The referenced table name. - /// The referenced columns. - /// The action on delete. - /// The action on update. - /// The transaction. - /// The cancellation token. - /// True if the foreign key constraint was created, otherwise false. - public static async Task CreateForeignKeyConstraintIfNotExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - DxOrderedColumn[] sourceColumns, - string referencedTableName, - DxOrderedColumn[] referencedColumns, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateForeignKeyConstraintIfNotExistsAsync( - db, - schemaName, - tableName, - constraintName, - sourceColumns, - referencedTableName, - referencedColumns, - onDelete, - onUpdate, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the foreign key constraint on a specific column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The foreign key constraint if it exists, otherwise null. - public static async Task GetForeignKeyConstraintOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetForeignKeyConstraintOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the foreign key constraint. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// The foreign key constraint if it exists, otherwise null. - public static async Task GetForeignKeyConstraintAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetForeignKeyConstraintAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the foreign key constraints. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of foreign key constraints. - public static async Task> GetForeignKeyConstraintsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetForeignKeyConstraintsAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the foreign key constraint name on a specific column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The foreign key constraint name if it exists, otherwise null. - public static async Task GetForeignKeyConstraintNameOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetForeignKeyConstraintNameOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the foreign key constraint names. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of foreign key constraint names. - public static async Task> GetForeignKeyConstraintNamesAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetForeignKeyConstraintNamesAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops the foreign key constraint on a specific column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the foreign key constraint was dropped, otherwise false. - public static async Task DropForeignKeyConstraintOnColumnIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropForeignKeyConstraintOnColumnIfExistsAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops the foreign key constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the foreign key constraint was dropped, otherwise false. - public static async Task DropForeignKeyConstraintIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropForeignKeyConstraintIfExistsAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - #endregion // IDatabaseForeignKeyConstraintMethods -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic; + +public static partial class DbConnectionExtensions +{ + #region IDatabaseForeignKeyConstraintMethods + + /// + /// Checks if a foreign key constraint exists on a specific column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the foreign key constraint exists, otherwise false. + public static async Task DoesForeignKeyConstraintExistOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesForeignKeyConstraintExistOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Checks if a foreign key constraint exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the foreign key constraint exists, otherwise false. + public static async Task DoesForeignKeyConstraintExistAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesForeignKeyConstraintExistAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Creates a foreign key constraint if it does not exist. + /// + /// The database connection. + /// The foreign key constraint. + /// The transaction. + /// The cancellation token. + /// True if the foreign key constraint was created, otherwise false. + public static async Task CreateForeignKeyConstraintIfNotExistsAsync( + this IDbConnection db, + DmForeignKeyConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateForeignKeyConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a foreign key constraint if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The source columns. + /// The referenced table name. + /// The referenced columns. + /// The action on delete. + /// The action on update. + /// The transaction. + /// The cancellation token. + /// True if the foreign key constraint was created, otherwise false. + public static async Task CreateForeignKeyConstraintIfNotExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + DmOrderedColumn[] sourceColumns, + string referencedTableName, + DmOrderedColumn[] referencedColumns, + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateForeignKeyConstraintIfNotExistsAsync( + db, + schemaName, + tableName, + constraintName, + sourceColumns, + referencedTableName, + referencedColumns, + onDelete, + onUpdate, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the foreign key constraint on a specific column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The foreign key constraint if it exists, otherwise null. + public static async Task GetForeignKeyConstraintOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetForeignKeyConstraintOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the foreign key constraint. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// The foreign key constraint if it exists, otherwise null. + public static async Task GetForeignKeyConstraintAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetForeignKeyConstraintAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the foreign key constraints. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of foreign key constraints. + public static async Task> GetForeignKeyConstraintsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetForeignKeyConstraintsAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the foreign key constraint name on a specific column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The foreign key constraint name if it exists, otherwise null. + public static async Task GetForeignKeyConstraintNameOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetForeignKeyConstraintNameOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the foreign key constraint names. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of foreign key constraint names. + public static async Task> GetForeignKeyConstraintNamesAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetForeignKeyConstraintNamesAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops the foreign key constraint on a specific column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the foreign key constraint was dropped, otherwise false. + public static async Task DropForeignKeyConstraintOnColumnIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropForeignKeyConstraintOnColumnIfExistsAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops the foreign key constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the foreign key constraint was dropped, otherwise false. + public static async Task DropForeignKeyConstraintIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropForeignKeyConstraintIfExistsAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + #endregion // IDatabaseForeignKeyConstraintMethods +} diff --git a/src/DapperMatic/DbConnectionExtensions_IndexMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_IndexMethods.cs similarity index 94% rename from src/DapperMatic/DbConnectionExtensions_IndexMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_IndexMethods.cs index 61ee42e..1646b6d 100644 --- a/src/DapperMatic/DbConnectionExtensions_IndexMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_IndexMethods.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic; +namespace MJCZone.DapperMatic; public static partial class DbConnectionExtensions { @@ -72,7 +72,7 @@ public static async Task DoesIndexExistAsync( /// True if the index was created, otherwise false. public static async Task CreateIndexIfNotExistsAsync( this IDbConnection db, - DxIndex index, + DmIndex index, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -99,7 +99,7 @@ public static async Task CreateIndexIfNotExistsAsync( string? schemaName, string tableName, string indexName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, bool isUnique = false, IDbTransaction? tx = null, CancellationToken cancellationToken = default @@ -129,7 +129,7 @@ public static async Task CreateIndexIfNotExistsAsync( /// The transaction. /// The cancellation token. /// A list of indexes on the column. - public static async Task> GetIndexesOnColumnAsync( + public static async Task> GetIndexesOnColumnAsync( this IDbConnection db, string? schemaName, string tableName, @@ -153,7 +153,7 @@ public static async Task> GetIndexesOnColumnAsync( /// The transaction. /// The cancellation token. /// The index if found, otherwise null. - public static async Task GetIndexAsync( + public static async Task GetIndexAsync( this IDbConnection db, string? schemaName, string tableName, @@ -177,7 +177,7 @@ public static async Task> GetIndexesOnColumnAsync( /// The transaction. /// The cancellation token. /// A list of indexes on the table. - public static async Task> GetIndexesAsync( + public static async Task> GetIndexesAsync( this IDbConnection db, string? schemaName, string tableName, diff --git a/src/DapperMatic/DbConnectionExtensions_PrimaryKeyConstraintMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_PrimaryKeyConstraintMethods.cs similarity index 93% rename from src/DapperMatic/DbConnectionExtensions_PrimaryKeyConstraintMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_PrimaryKeyConstraintMethods.cs index 903e6d5..83a5e30 100644 --- a/src/DapperMatic/DbConnectionExtensions_PrimaryKeyConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_PrimaryKeyConstraintMethods.cs @@ -1,130 +1,130 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic; - -public static partial class DbConnectionExtensions -{ - #region IDatabasePrimaryKeyConstraintMethods - - /// - /// Checks if a primary key constraint exists in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the primary key constraint exists, otherwise false. - public static async Task DoesPrimaryKeyConstraintExistAsync( - this IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesPrimaryKeyConstraintExistAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a primary key constraint if it does not exist. - /// - /// The database connection. - /// The primary key constraint. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the primary key constraint was created, otherwise false. - public static async Task CreatePrimaryKeyConstraintIfNotExistsAsync( - this IDbConnection db, - DxPrimaryKeyConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreatePrimaryKeyConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a primary key constraint if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The columns that make up the primary key. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the primary key constraint was created, otherwise false. - public static async Task CreatePrimaryKeyConstraintIfNotExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - DxOrderedColumn[] columns, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreatePrimaryKeyConstraintIfNotExistsAsync( - db, - schemaName, - tableName, - constraintName, - columns, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the primary key constraint for the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The transaction to use, or null. - /// The cancellation token. - /// The primary key constraint, or null if it does not exist. - public static async Task GetPrimaryKeyConstraintAsync( - this IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetPrimaryKeyConstraintAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Drops the primary key constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the primary key constraint was dropped, otherwise false. - public static async Task DropPrimaryKeyConstraintIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropPrimaryKeyConstraintIfExistsAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - } - #endregion // IDatabasePrimaryKeyConstraintMethods -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic; + +public static partial class DbConnectionExtensions +{ + #region IDatabasePrimaryKeyConstraintMethods + + /// + /// Checks if a primary key constraint exists in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the primary key constraint exists, otherwise false. + public static async Task DoesPrimaryKeyConstraintExistAsync( + this IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesPrimaryKeyConstraintExistAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a primary key constraint if it does not exist. + /// + /// The database connection. + /// The primary key constraint. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the primary key constraint was created, otherwise false. + public static async Task CreatePrimaryKeyConstraintIfNotExistsAsync( + this IDbConnection db, + DmPrimaryKeyConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreatePrimaryKeyConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a primary key constraint if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The columns that make up the primary key. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the primary key constraint was created, otherwise false. + public static async Task CreatePrimaryKeyConstraintIfNotExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + DmOrderedColumn[] columns, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreatePrimaryKeyConstraintIfNotExistsAsync( + db, + schemaName, + tableName, + constraintName, + columns, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the primary key constraint for the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The transaction to use, or null. + /// The cancellation token. + /// The primary key constraint, or null if it does not exist. + public static async Task GetPrimaryKeyConstraintAsync( + this IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetPrimaryKeyConstraintAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Drops the primary key constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the primary key constraint was dropped, otherwise false. + public static async Task DropPrimaryKeyConstraintIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropPrimaryKeyConstraintIfExistsAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + } + #endregion // IDatabasePrimaryKeyConstraintMethods +} diff --git a/src/DapperMatic/DbConnectionExtensions_SchemaMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_SchemaMethods.cs similarity index 96% rename from src/DapperMatic/DbConnectionExtensions_SchemaMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_SchemaMethods.cs index 91d633d..c683276 100644 --- a/src/DapperMatic/DbConnectionExtensions_SchemaMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_SchemaMethods.cs @@ -1,151 +1,151 @@ -using System.Data; - -namespace DapperMatic; - -public static partial class DbConnectionExtensions -{ - #region IDatabaseSchemaMethods - - /// - /// Determines whether the database supports schemas. - /// - /// The database connection. - /// True if the database supports schemas; otherwise, false. - public static bool SupportsSchemas(this IDbConnection db) - { - return Database(db).SupportsSchemas; - } - - /// - /// Gets the schema-qualified table name. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The schema-qualified table name. - public static string GetSchemaQualifiedTableName( - this IDbConnection db, - string? schemaName, - string tableName - ) - { - return Database(db).GetSchemaQualifiedIdentifierName(schemaName, tableName); - } - - /// - /// Determines whether the database supports check constraints asynchronously. - /// - /// The database connection. - /// The database transaction. - /// The cancellation token. - /// True if the database supports check constraints; otherwise, false. - public static async Task SupportsCheckConstraintsAsync( - this IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .SupportsCheckConstraintsAsync(db, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Determines whether the database supports ordered keys in constraints asynchronously. - /// - /// The database connection. - /// The database transaction. - /// The cancellation token. - /// True if the database supports ordered keys in constraints; otherwise, false. - public static async Task SupportsOrderedKeysInConstraintsAsync( - this IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .SupportsOrderedKeysInConstraintsAsync(db, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates the schema if it does not exist asynchronously. - /// - /// The database connection. - /// The schema name. - /// The database transaction. - /// The cancellation token. - /// True if the schema was created; otherwise, false. - public static async Task CreateSchemaIfNotExistsAsync( - this IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateSchemaIfNotExistsAsync(db, schemaName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Determines whether the schema exists asynchronously. - /// - /// The database connection. - /// The schema name. - /// The database transaction. - /// The cancellation token. - /// True if the schema exists; otherwise, false. - public static async Task DoesSchemaExistAsync( - this IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesSchemaExistAsync(db, schemaName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Gets the schema names asynchronously. - /// - /// The database connection. - /// The schema name filter. - /// The database transaction. - /// The cancellation token. - /// A list of schema names. - public static async Task> GetSchemaNamesAsync( - this IDbConnection db, - string? schemaNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetSchemaNamesAsync(db, schemaNameFilter, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Drops the schema if it exists asynchronously. - /// - /// The database connection. - /// The schema name. - /// The database transaction. - /// The cancellation token. - /// True if the schema was dropped; otherwise, false. - public static async Task DropSchemaIfExistsAsync( - this IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropSchemaIfExistsAsync(db, schemaName, tx, cancellationToken) - .ConfigureAwait(false); - } - #endregion // IDatabaseSchemaMethods -} +using System.Data; + +namespace MJCZone.DapperMatic; + +public static partial class DbConnectionExtensions +{ + #region IDatabaseSchemaMethods + + /// + /// Determines whether the database supports schemas. + /// + /// The database connection. + /// True if the database supports schemas; otherwise, false. + public static bool SupportsSchemas(this IDbConnection db) + { + return Database(db).SupportsSchemas; + } + + /// + /// Gets the schema-qualified table name. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The schema-qualified table name. + public static string GetSchemaQualifiedTableName( + this IDbConnection db, + string? schemaName, + string tableName + ) + { + return Database(db).GetSchemaQualifiedIdentifierName(schemaName, tableName); + } + + /// + /// Determines whether the database supports check constraints asynchronously. + /// + /// The database connection. + /// The database transaction. + /// The cancellation token. + /// True if the database supports check constraints; otherwise, false. + public static async Task SupportsCheckConstraintsAsync( + this IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .SupportsCheckConstraintsAsync(db, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Determines whether the database supports ordered keys in constraints asynchronously. + /// + /// The database connection. + /// The database transaction. + /// The cancellation token. + /// True if the database supports ordered keys in constraints; otherwise, false. + public static async Task SupportsOrderedKeysInConstraintsAsync( + this IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .SupportsOrderedKeysInConstraintsAsync(db, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates the schema if it does not exist asynchronously. + /// + /// The database connection. + /// The schema name. + /// The database transaction. + /// The cancellation token. + /// True if the schema was created; otherwise, false. + public static async Task CreateSchemaIfNotExistsAsync( + this IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateSchemaIfNotExistsAsync(db, schemaName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Determines whether the schema exists asynchronously. + /// + /// The database connection. + /// The schema name. + /// The database transaction. + /// The cancellation token. + /// True if the schema exists; otherwise, false. + public static async Task DoesSchemaExistAsync( + this IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesSchemaExistAsync(db, schemaName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets the schema names asynchronously. + /// + /// The database connection. + /// The schema name filter. + /// The database transaction. + /// The cancellation token. + /// A list of schema names. + public static async Task> GetSchemaNamesAsync( + this IDbConnection db, + string? schemaNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetSchemaNamesAsync(db, schemaNameFilter, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Drops the schema if it exists asynchronously. + /// + /// The database connection. + /// The schema name. + /// The database transaction. + /// The cancellation token. + /// True if the schema was dropped; otherwise, false. + public static async Task DropSchemaIfExistsAsync( + this IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropSchemaIfExistsAsync(db, schemaName, tx, cancellationToken) + .ConfigureAwait(false); + } + #endregion // IDatabaseSchemaMethods +} diff --git a/src/DapperMatic/DbConnectionExtensions_TableMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_TableMethods.cs similarity index 91% rename from src/DapperMatic/DbConnectionExtensions_TableMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_TableMethods.cs index e77b9ba..5dc63c5 100644 --- a/src/DapperMatic/DbConnectionExtensions_TableMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_TableMethods.cs @@ -1,242 +1,242 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic; - -public static partial class DbConnectionExtensions -{ - #region IDatabaseTableMethods - - /// - /// Checks if a table exists in the database. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The transaction to use. - /// The cancellation token. - /// True if the table exists, otherwise false. - public static async Task DoesTableExistAsync( - this IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesTableExistAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a table if it does not exist. - /// - /// The database connection. - /// The table definition. - /// The transaction to use. - /// The cancellation token. - /// True if the table was created, otherwise false. - public static async Task CreateTableIfNotExistsAsync( - this IDbConnection db, - DxTable table, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateTableIfNotExistsAsync(db, table, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a table if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The columns of the table. - /// The primary key constraint. - /// The check constraints. - /// The default constraints. - /// The unique constraints. - /// The foreign key constraints. - /// The indexes. - /// The transaction to use. - /// The cancellation token. - /// True if the table was created, otherwise false. - public static async Task CreateTableIfNotExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - DxColumn[] columns, - DxPrimaryKeyConstraint? primaryKey = null, - DxCheckConstraint[]? checkConstraints = null, - DxDefaultConstraint[]? defaultConstraints = null, - DxUniqueConstraint[]? uniqueConstraints = null, - DxForeignKeyConstraint[]? foreignKeyConstraints = null, - DxIndex[]? indexes = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateTableIfNotExistsAsync( - db, - schemaName, - tableName, - columns, - primaryKey, - checkConstraints, - defaultConstraints, - uniqueConstraints, - foreignKeyConstraints, - indexes, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the table definition. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The transaction to use. - /// The cancellation token. - /// The table definition. - public static async Task GetTableAsync( - this IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetTableAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Gets the list of table definitions. - /// - /// The database connection. - /// The schema name. - /// The table name filter. - /// The transaction to use. - /// The cancellation token. - /// The list of table definitions. - public static async Task> GetTablesAsync( - this IDbConnection db, - string? schemaName, - string? tableNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetTablesAsync(db, schemaName, tableNameFilter, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Gets the list of table names. - /// - /// The database connection. - /// The schema name. - /// The table name filter. - /// The transaction to use. - /// The cancellation token. - /// The list of table names. - public static async Task> GetTableNamesAsync( - this IDbConnection db, - string? schemaName, - string? tableNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetTableNamesAsync(db, schemaName, tableNameFilter, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Drops a table if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The transaction to use. - /// The cancellation token. - /// True if the table was dropped, otherwise false. - public static async Task DropTableIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropTableIfExistsAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Renames a table if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The new table name. - /// The transaction to use. - /// The cancellation token. - /// True if the table was renamed, otherwise false. - public static async Task RenameTableIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string newTableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .RenameTableIfExistsAsync( - db, - schemaName, - tableName, - newTableName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Truncates a table if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The transaction to use. - /// The cancellation token. - /// True if the table was truncated, otherwise false. - public static async Task TruncateTableIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .TruncateTableIfExistsAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - } - #endregion // IDatabaseTableMethods -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic; + +public static partial class DbConnectionExtensions +{ + #region IDatabaseTableMethods + + /// + /// Checks if a table exists in the database. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The transaction to use. + /// The cancellation token. + /// True if the table exists, otherwise false. + public static async Task DoesTableExistAsync( + this IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesTableExistAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a table if it does not exist. + /// + /// The database connection. + /// The table definition. + /// The transaction to use. + /// The cancellation token. + /// True if the table was created, otherwise false. + public static async Task CreateTableIfNotExistsAsync( + this IDbConnection db, + DmTable table, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateTableIfNotExistsAsync(db, table, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a table if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The columns of the table. + /// The primary key constraint. + /// The check constraints. + /// The default constraints. + /// The unique constraints. + /// The foreign key constraints. + /// The indexes. + /// The transaction to use. + /// The cancellation token. + /// True if the table was created, otherwise false. + public static async Task CreateTableIfNotExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + DmColumn[] columns, + DmPrimaryKeyConstraint? primaryKey = null, + DmCheckConstraint[]? checkConstraints = null, + DmDefaultConstraint[]? defaultConstraints = null, + DmUniqueConstraint[]? uniqueConstraints = null, + DmForeignKeyConstraint[]? foreignKeyConstraints = null, + DmIndex[]? indexes = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateTableIfNotExistsAsync( + db, + schemaName, + tableName, + columns, + primaryKey, + checkConstraints, + defaultConstraints, + uniqueConstraints, + foreignKeyConstraints, + indexes, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the table definition. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The transaction to use. + /// The cancellation token. + /// The table definition. + public static async Task GetTableAsync( + this IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetTableAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets the list of table definitions. + /// + /// The database connection. + /// The schema name. + /// The table name filter. + /// The transaction to use. + /// The cancellation token. + /// The list of table definitions. + public static async Task> GetTablesAsync( + this IDbConnection db, + string? schemaName, + string? tableNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetTablesAsync(db, schemaName, tableNameFilter, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets the list of table names. + /// + /// The database connection. + /// The schema name. + /// The table name filter. + /// The transaction to use. + /// The cancellation token. + /// The list of table names. + public static async Task> GetTableNamesAsync( + this IDbConnection db, + string? schemaName, + string? tableNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetTableNamesAsync(db, schemaName, tableNameFilter, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Drops a table if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The transaction to use. + /// The cancellation token. + /// True if the table was dropped, otherwise false. + public static async Task DropTableIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropTableIfExistsAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Renames a table if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The new table name. + /// The transaction to use. + /// The cancellation token. + /// True if the table was renamed, otherwise false. + public static async Task RenameTableIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string newTableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .RenameTableIfExistsAsync( + db, + schemaName, + tableName, + newTableName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Truncates a table if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The transaction to use. + /// The cancellation token. + /// True if the table was truncated, otherwise false. + public static async Task TruncateTableIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .TruncateTableIfExistsAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + } + #endregion // IDatabaseTableMethods +} diff --git a/src/DapperMatic/DbConnectionExtensions_UniqueConstraintMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_UniqueConstraintMethods.cs similarity index 95% rename from src/DapperMatic/DbConnectionExtensions_UniqueConstraintMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_UniqueConstraintMethods.cs index c2be663..3fa8e4d 100644 --- a/src/DapperMatic/DbConnectionExtensions_UniqueConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_UniqueConstraintMethods.cs @@ -1,343 +1,343 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic; - -public static partial class DbConnectionExtensions -{ - #region IDatabaseUniqueConstraintMethods - - /// - /// Checks if a unique constraint exists on a specified column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint exists. - public static async Task DoesUniqueConstraintExistOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesUniqueConstraintExistOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Checks if a unique constraint exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint exists. - public static async Task DoesUniqueConstraintExistAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesUniqueConstraintExistAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Creates a unique constraint if it does not exist. - /// - /// The database connection. - /// The unique constraint. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint was created. - public static async Task CreateUniqueConstraintIfNotExistsAsync( - this IDbConnection db, - DxUniqueConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateUniqueConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a unique constraint if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The columns. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint was created. - public static async Task CreateUniqueConstraintIfNotExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - DxOrderedColumn[] columns, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateUniqueConstraintIfNotExistsAsync( - db, - schemaName, - tableName, - constraintName, - columns, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the unique constraint on a specified column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the unique constraint. - public static async Task GetUniqueConstraintOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetUniqueConstraintOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the unique constraint. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the unique constraint. - public static async Task GetUniqueConstraintAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetUniqueConstraintAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the unique constraints. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the list of unique constraints. - public static async Task> GetUniqueConstraintsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetUniqueConstraintsAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the unique constraint name on a specified column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the unique constraint name. - public static async Task GetUniqueConstraintNameOnColumnAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetUniqueConstraintNameOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets the unique constraint names. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the list of unique constraint names. - public static async Task> GetUniqueConstraintNamesAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetUniqueConstraintNamesAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops the unique constraint on a specified column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint was dropped. - public static async Task DropUniqueConstraintOnColumnIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropUniqueConstraintOnColumnIfExistsAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops the unique constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint was dropped. - public static async Task DropUniqueConstraintIfExistsAsync( - this IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropUniqueConstraintIfExistsAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - #endregion // IDatabaseUniqueConstraintMethods -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic; + +public static partial class DbConnectionExtensions +{ + #region IDatabaseUniqueConstraintMethods + + /// + /// Checks if a unique constraint exists on a specified column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint exists. + public static async Task DoesUniqueConstraintExistOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesUniqueConstraintExistOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Checks if a unique constraint exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint exists. + public static async Task DoesUniqueConstraintExistAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesUniqueConstraintExistAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Creates a unique constraint if it does not exist. + /// + /// The database connection. + /// The unique constraint. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint was created. + public static async Task CreateUniqueConstraintIfNotExistsAsync( + this IDbConnection db, + DmUniqueConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateUniqueConstraintIfNotExistsAsync(db, constraint, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a unique constraint if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The columns. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint was created. + public static async Task CreateUniqueConstraintIfNotExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + DmOrderedColumn[] columns, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateUniqueConstraintIfNotExistsAsync( + db, + schemaName, + tableName, + constraintName, + columns, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the unique constraint on a specified column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the unique constraint. + public static async Task GetUniqueConstraintOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetUniqueConstraintOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the unique constraint. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the unique constraint. + public static async Task GetUniqueConstraintAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetUniqueConstraintAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the unique constraints. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the list of unique constraints. + public static async Task> GetUniqueConstraintsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetUniqueConstraintsAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the unique constraint name on a specified column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the unique constraint name. + public static async Task GetUniqueConstraintNameOnColumnAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetUniqueConstraintNameOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets the unique constraint names. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the list of unique constraint names. + public static async Task> GetUniqueConstraintNamesAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetUniqueConstraintNamesAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops the unique constraint on a specified column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint was dropped. + public static async Task DropUniqueConstraintOnColumnIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropUniqueConstraintOnColumnIfExistsAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops the unique constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the unique constraint was dropped. + public static async Task DropUniqueConstraintIfExistsAsync( + this IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropUniqueConstraintIfExistsAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + #endregion // IDatabaseUniqueConstraintMethods +} diff --git a/src/DapperMatic/DbConnectionExtensions_ViewMethods.cs b/src/MJCZone.DapperMatic/DbConnectionExtensions_ViewMethods.cs similarity index 95% rename from src/DapperMatic/DbConnectionExtensions_ViewMethods.cs rename to src/MJCZone.DapperMatic/DbConnectionExtensions_ViewMethods.cs index 909b677..20ec051 100644 --- a/src/DapperMatic/DbConnectionExtensions_ViewMethods.cs +++ b/src/MJCZone.DapperMatic/DbConnectionExtensions_ViewMethods.cs @@ -1,232 +1,232 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic; - -public static partial class DbConnectionExtensions -{ - #region IDatabaseViewMethods - - /// - /// Checks if a view exists in the database. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The transaction to use. - /// The cancellation token. - /// True if the view exists, otherwise false. - public static async Task DoesViewExistAsync( - this IDbConnection db, - string? schemaName, - string viewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DoesViewExistAsync(db, schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a view if it does not exist. - /// - /// The database connection. - /// The view definition. - /// The transaction to use. - /// The cancellation token. - /// True if the view was created, otherwise false. - public static async Task CreateViewIfNotExistsAsync( - this IDbConnection db, - DxView view, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateViewIfNotExistsAsync(db, view, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Creates a view if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The view definition. - /// The transaction to use. - /// The cancellation token. - /// True if the view was created, otherwise false. - public static async Task CreateViewIfNotExistsAsync( - this IDbConnection db, - string? schemaName, - string viewName, - string viewDefinition, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .CreateViewIfNotExistsAsync( - db, - schemaName, - viewName, - viewDefinition, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Updates a view if it exists. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The view definition. - /// The transaction to use. - /// The cancellation token. - /// True if the view was updated, otherwise false. - public static async Task UpdateViewIfExistsAsync( - this IDbConnection db, - string? schemaName, - string viewName, - string viewDefinition, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if ( - !await db.DropViewIfExistsAsync(schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false) - ) - { - return false; - } - - return await db.CreateViewIfNotExistsAsync( - schemaName, - viewName, - viewDefinition, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets a view from the database. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The transaction to use. - /// The cancellation token. - /// The view if found, otherwise null. - public static async Task GetViewAsync( - this IDbConnection db, - string? schemaName, - string viewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetViewAsync(db, schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Gets a list of views from the database. - /// - /// The database connection. - /// The schema name. - /// The view name filter. - /// The transaction to use. - /// The cancellation token. - /// A list of views. - public static async Task> GetViewsAsync( - this IDbConnection db, - string? schemaName, - string? viewNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetViewsAsync(db, schemaName, viewNameFilter, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Gets a list of view names from the database. - /// - /// The database connection. - /// The schema name. - /// The view name filter. - /// The transaction to use. - /// The cancellation token. - /// A list of view names. - public static async Task> GetViewNamesAsync( - this IDbConnection db, - string? schemaName, - string? viewNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .GetViewNamesAsync(db, schemaName, viewNameFilter, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Drops a view if it exists. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The transaction to use. - /// The cancellation token. - /// True if the view was dropped, otherwise false. - public static async Task DropViewIfExistsAsync( - this IDbConnection db, - string? schemaName, - string viewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .DropViewIfExistsAsync(db, schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false); - } - - /// - /// Renames a view if it exists. - /// - /// The database connection. - /// The schema name. - /// The current view name. - /// The new view name. - /// The transaction to use. - /// The cancellation token. - /// True if the view was renamed, otherwise false. - public static async Task RenameViewIfExistsAsync( - this IDbConnection db, - string? schemaName, - string viewName, - string newViewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await Database(db) - .RenameViewIfExistsAsync(db, schemaName, viewName, newViewName, tx, cancellationToken) - .ConfigureAwait(false); - } - #endregion // IDatabaseViewMethods -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic; + +public static partial class DbConnectionExtensions +{ + #region IDatabaseViewMethods + + /// + /// Checks if a view exists in the database. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The transaction to use. + /// The cancellation token. + /// True if the view exists, otherwise false. + public static async Task DoesViewExistAsync( + this IDbConnection db, + string? schemaName, + string viewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DoesViewExistAsync(db, schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a view if it does not exist. + /// + /// The database connection. + /// The view definition. + /// The transaction to use. + /// The cancellation token. + /// True if the view was created, otherwise false. + public static async Task CreateViewIfNotExistsAsync( + this IDbConnection db, + DmView view, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateViewIfNotExistsAsync(db, view, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Creates a view if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The view definition. + /// The transaction to use. + /// The cancellation token. + /// True if the view was created, otherwise false. + public static async Task CreateViewIfNotExistsAsync( + this IDbConnection db, + string? schemaName, + string viewName, + string viewDefinition, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .CreateViewIfNotExistsAsync( + db, + schemaName, + viewName, + viewDefinition, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Updates a view if it exists. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The view definition. + /// The transaction to use. + /// The cancellation token. + /// True if the view was updated, otherwise false. + public static async Task UpdateViewIfExistsAsync( + this IDbConnection db, + string? schemaName, + string viewName, + string viewDefinition, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if ( + !await db.DropViewIfExistsAsync(schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false) + ) + { + return false; + } + + return await db.CreateViewIfNotExistsAsync( + schemaName, + viewName, + viewDefinition, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets a view from the database. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The transaction to use. + /// The cancellation token. + /// The view if found, otherwise null. + public static async Task GetViewAsync( + this IDbConnection db, + string? schemaName, + string viewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetViewAsync(db, schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets a list of views from the database. + /// + /// The database connection. + /// The schema name. + /// The view name filter. + /// The transaction to use. + /// The cancellation token. + /// A list of views. + public static async Task> GetViewsAsync( + this IDbConnection db, + string? schemaName, + string? viewNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetViewsAsync(db, schemaName, viewNameFilter, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Gets a list of view names from the database. + /// + /// The database connection. + /// The schema name. + /// The view name filter. + /// The transaction to use. + /// The cancellation token. + /// A list of view names. + public static async Task> GetViewNamesAsync( + this IDbConnection db, + string? schemaName, + string? viewNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .GetViewNamesAsync(db, schemaName, viewNameFilter, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Drops a view if it exists. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The transaction to use. + /// The cancellation token. + /// True if the view was dropped, otherwise false. + public static async Task DropViewIfExistsAsync( + this IDbConnection db, + string? schemaName, + string viewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .DropViewIfExistsAsync(db, schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Renames a view if it exists. + /// + /// The database connection. + /// The schema name. + /// The current view name. + /// The new view name. + /// The transaction to use. + /// The cancellation token. + /// True if the view was renamed, otherwise false. + public static async Task RenameViewIfExistsAsync( + this IDbConnection db, + string? schemaName, + string viewName, + string newViewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await Database(db) + .RenameViewIfExistsAsync(db, schemaName, viewName, newViewName, tx, cancellationToken) + .ConfigureAwait(false); + } + #endregion // IDatabaseViewMethods +} diff --git a/src/DapperMatic/DbProviderType.cs b/src/MJCZone.DapperMatic/DbProviderType.cs similarity index 91% rename from src/DapperMatic/DbProviderType.cs rename to src/MJCZone.DapperMatic/DbProviderType.cs index aec0c47..f2c0311 100644 --- a/src/DapperMatic/DbProviderType.cs +++ b/src/MJCZone.DapperMatic/DbProviderType.cs @@ -1,33 +1,33 @@ -namespace DapperMatic -{ - /// - /// Specifies the type of database provider. - /// - public enum DbProviderType - { - /// - /// SQLite database provider. - /// - Sqlite, - - /// - /// SQL Server database provider. - /// - SqlServer, - - /// - /// MySQL database provider. - /// - MySql, - - /// - /// PostgreSQL database provider. - /// - PostgreSql, - - /// - /// Other database provider. - /// - Other, - } -} +namespace MJCZone.DapperMatic +{ + /// + /// Specifies the type of database provider. + /// + public enum DbProviderType + { + /// + /// SQLite database provider. + /// + Sqlite, + + /// + /// SQL Server database provider. + /// + SqlServer, + + /// + /// MySQL database provider. + /// + MySql, + + /// + /// PostgreSQL database provider. + /// + PostgreSql, + + /// + /// Other database provider. + /// + Other, + } +} diff --git a/src/MJCZone.DapperMatic/DotnetTypeDescriptor.cs b/src/MJCZone.DapperMatic/DotnetTypeDescriptor.cs new file mode 100644 index 0000000..776babc --- /dev/null +++ b/src/MJCZone.DapperMatic/DotnetTypeDescriptor.cs @@ -0,0 +1,113 @@ +using System.Text; + +namespace MJCZone.DapperMatic; + +/// +/// Describes a .NET type with its SQL type properties. +/// +public class DotnetTypeDescriptor +{ + /// + /// Initializes a new instance of the class. + /// + /// The .NET type. + /// The length of the type. + /// The precision of the type. + /// The scale of the type. + /// Indicates if the type is auto-incrementing. + /// Indicates if the type is Unicode. + /// Indicates if the type has a fixed length. + public DotnetTypeDescriptor( + Type dotnetType, + int? length = null, + int? precision = null, + int? scale = null, + bool? isAutoIncrementing = null, + bool? isUnicode = null, + bool? isFixedLength = null + ) + { + DotnetType = + dotnetType?.OrUnderlyingTypeIfNullable() + ?? throw new ArgumentNullException(nameof(dotnetType)); + Length = length; + Precision = precision; + Scale = scale; + IsAutoIncrementing = isAutoIncrementing; + IsUnicode = isUnicode; + IsFixedLength = isFixedLength; + } + + /// + /// Gets or sets the .NET type. + /// + public Type DotnetType { get; set; } + + /// + /// Gets or sets the length of the type. + /// + public int? Length { get; set; } + + /// + /// Gets or sets the precision of the type. + /// + public int? Precision { get; set; } + + /// + /// Gets or sets the scale of the type. + /// + public int? Scale { get; set; } + + /// + /// Gets or sets a value indicating whether the type is auto-incrementing. + /// + public bool? IsAutoIncrementing { get; set; } + + /// + /// Gets or sets a value indicating whether the type is Unicode. + /// + public bool? IsUnicode { get; set; } + + /// + /// Gets or sets a value indicating whether the type has a fixed length. + /// + public bool? IsFixedLength { get; set; } + + /// + /// Describes the object as a string. + /// + /// The string representation of the object. + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append(DotnetType.GetFriendlyName()); + if (Length.GetValueOrDefault(0) > 0) + { + sb.Append($" length({Length})"); + } + + if (Precision.GetValueOrDefault(0) > 0) + { + if (Scale.GetValueOrDefault(0) > 0) + { + sb.Append($" precision({Precision},{Scale})"); + } + else + { + sb.Append($" precision({Precision})"); + } + } + + if (IsAutoIncrementing.GetValueOrDefault(false)) + { + sb.Append(" auto_increment"); + } + + if (IsUnicode.GetValueOrDefault(false)) + { + sb.Append(" unicode"); + } + + return sb.ToString(); + } +} diff --git a/src/DapperMatic/ExtensionMethods.cs b/src/MJCZone.DapperMatic/ExtensionMethods.cs similarity index 95% rename from src/DapperMatic/ExtensionMethods.cs rename to src/MJCZone.DapperMatic/ExtensionMethods.cs index 47b36c7..70d1b0c 100644 --- a/src/DapperMatic/ExtensionMethods.cs +++ b/src/MJCZone.DapperMatic/ExtensionMethods.cs @@ -3,7 +3,7 @@ using System.Text; using System.Text.RegularExpressions; -namespace DapperMatic; +namespace MJCZone.DapperMatic; [SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "Utility methods.")] [SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = "Utility methods.")] @@ -306,7 +306,9 @@ public static string ToAlphaNumeric(this string text, string additionalAllowedCh return string.Concat( Array.FindAll( text.ToCharArray(), - c => c.IsAlphaNumeric() || additionalAllowedCharacters.Contains(c, StringComparison.OrdinalIgnoreCase) + c => + c.IsAlphaNumeric() + || additionalAllowedCharacters.Contains(c, StringComparison.OrdinalIgnoreCase) ) ); } @@ -322,7 +324,9 @@ public static string ToAlpha(this string text, string additionalAllowedCharacter return string.Concat( Array.FindAll( text.ToCharArray(), - c => c.IsAlpha() || additionalAllowedCharacters.Contains(c, StringComparison.OrdinalIgnoreCase) + c => + c.IsAlpha() + || additionalAllowedCharacters.Contains(c, StringComparison.OrdinalIgnoreCase) ) ); } diff --git a/src/DapperMatic/Interfaces/IDatabaseCheckConstraintMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseCheckConstraintMethods.cs similarity index 94% rename from src/DapperMatic/Interfaces/IDatabaseCheckConstraintMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseCheckConstraintMethods.cs index c415d18..465a01c 100644 --- a/src/DapperMatic/Interfaces/IDatabaseCheckConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseCheckConstraintMethods.cs @@ -1,219 +1,219 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Interfaces; - -/// -/// Provides database check constraint methods for database operations. -/// -public interface IDatabaseCheckConstraintMethods -{ - /// - /// Creates a check constraint if it does not already exist. - /// - /// The database connection. - /// The check constraint to create. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint was created, false otherwise. - Task CreateCheckConstraintIfNotExistsAsync( - IDbConnection db, - DxCheckConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a check constraint if it does not already exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The constraint name. - /// The constraint expression. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint was created, false otherwise. - Task CreateCheckConstraintIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? columnName, - string constraintName, - string expression, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a check constraint exists on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint exists, false otherwise. - Task DoesCheckConstraintExistOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a check constraint exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint exists, false otherwise. - Task DoesCheckConstraintExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the check constraint on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// The check constraint, or null if it does not exist. - Task GetCheckConstraintOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the check constraint. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction to use, or null. - /// The cancellation token. - /// The check constraint, or null if it does not exist. - Task GetCheckConstraintAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a list of check constraints. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction to use, or null. - /// The cancellation token. - /// A list of check constraints. - Task> GetCheckConstraintsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the name of the check constraint on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// The name of the check constraint, or null if it does not exist. - Task GetCheckConstraintNameOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a list of check constraint names. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction to use, or null. - /// The cancellation token. - /// A list of check constraint names. - Task> GetCheckConstraintNamesAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops a check constraint on a column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint was dropped, false otherwise. - Task DropCheckConstraintOnColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops a check constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint was dropped, false otherwise. - Task DropCheckConstraintIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Provides database check constraint methods for database operations. +/// +public interface IDatabaseCheckConstraintMethods +{ + /// + /// Creates a check constraint if it does not already exist. + /// + /// The database connection. + /// The check constraint to create. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint was created, false otherwise. + Task CreateCheckConstraintIfNotExistsAsync( + IDbConnection db, + DmCheckConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a check constraint if it does not already exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The constraint name. + /// The constraint expression. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint was created, false otherwise. + Task CreateCheckConstraintIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? columnName, + string constraintName, + string expression, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a check constraint exists on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint exists, false otherwise. + Task DoesCheckConstraintExistOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a check constraint exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint exists, false otherwise. + Task DoesCheckConstraintExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the check constraint on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// The check constraint, or null if it does not exist. + Task GetCheckConstraintOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the check constraint. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction to use, or null. + /// The cancellation token. + /// The check constraint, or null if it does not exist. + Task GetCheckConstraintAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a list of check constraints. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction to use, or null. + /// The cancellation token. + /// A list of check constraints. + Task> GetCheckConstraintsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the name of the check constraint on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// The name of the check constraint, or null if it does not exist. + Task GetCheckConstraintNameOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a list of check constraint names. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction to use, or null. + /// The cancellation token. + /// A list of check constraint names. + Task> GetCheckConstraintNamesAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops a check constraint on a column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint was dropped, false otherwise. + Task DropCheckConstraintOnColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops a check constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint was dropped, false otherwise. + Task DropCheckConstraintIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); +} diff --git a/src/DapperMatic/Interfaces/IDatabaseColumnMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseColumnMethods.cs similarity index 94% rename from src/DapperMatic/Interfaces/IDatabaseColumnMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseColumnMethods.cs index c592d46..e0b7821 100644 --- a/src/DapperMatic/Interfaces/IDatabaseColumnMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseColumnMethods.cs @@ -1,194 +1,194 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Interfaces; - -/// -/// Provides database column methods for database operations. -/// -public interface IDatabaseColumnMethods -{ - /// - /// Creates a column if it does not exist. - /// - /// The database connection. - /// The column definition. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column was created, false otherwise. - Task CreateColumnIfNotExistsAsync( - IDbConnection db, - DxColumn column, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a column if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The .NET type of the column. - /// The provider-specific data type. - /// The length of the column. - /// The precision of the column. - /// The scale of the column. - /// The check expression for the column. - /// The default expression for the column. - /// Whether the column is nullable. - /// Whether the column is a primary key. - /// Whether the column is auto-incremented. - /// Whether the column is unique. - /// Whether the column is indexed. - /// Whether the column is a foreign key. - /// The referenced table name for the foreign key. - /// The referenced column name for the foreign key. - /// The action to take on delete. - /// The action to take on update. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column was created, false otherwise. - Task CreateColumnIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - Type dotnetType, - string? providerDataType = null, - int? length = null, - int? precision = null, - int? scale = null, - string? checkExpression = null, - string? defaultExpression = null, - bool isNullable = true, - bool isPrimaryKey = false, - bool isAutoIncrement = false, - bool isUnique = false, - bool isIndexed = false, - bool isForeignKey = false, - string? referencedTableName = null, - string? referencedColumnName = null, - DxForeignKeyAction? onDelete = null, - DxForeignKeyAction? onUpdate = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a column exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column exists, false otherwise. - Task DoesColumnExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a column definition. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// The column definition, or null if the column does not exist. - Task GetColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a list of column definitions. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name filter. - /// The transaction to use, or null. - /// The cancellation token. - /// A list of column definitions. - Task> GetColumnsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? columnNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a list of column names. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name filter. - /// The transaction to use, or null. - /// The cancellation token. - /// A list of column names. - Task> GetColumnNamesAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? columnNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops a column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column was dropped, false otherwise. - Task DropColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Renames a column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The new column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the column was renamed, false otherwise. - Task RenameColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - string newColumnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Provides database column methods for database operations. +/// +public interface IDatabaseColumnMethods +{ + /// + /// Creates a column if it does not exist. + /// + /// The database connection. + /// The column definition. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column was created, false otherwise. + Task CreateColumnIfNotExistsAsync( + IDbConnection db, + DmColumn column, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a column if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The .NET type of the column. + /// The provider-specific data type. + /// The length of the column. + /// The precision of the column. + /// The scale of the column. + /// The check expression for the column. + /// The default expression for the column. + /// Whether the column is nullable. + /// Whether the column is a primary key. + /// Whether the column is auto-incremented. + /// Whether the column is unique. + /// Whether the column is indexed. + /// Whether the column is a foreign key. + /// The referenced table name for the foreign key. + /// The referenced column name for the foreign key. + /// The action to take on delete. + /// The action to take on update. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column was created, false otherwise. + Task CreateColumnIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + Type dotnetType, + string? providerDataType = null, + int? length = null, + int? precision = null, + int? scale = null, + string? checkExpression = null, + string? defaultExpression = null, + bool isNullable = true, + bool isPrimaryKey = false, + bool isAutoIncrement = false, + bool isUnique = false, + bool isIndexed = false, + bool isForeignKey = false, + string? referencedTableName = null, + string? referencedColumnName = null, + DmForeignKeyAction? onDelete = null, + DmForeignKeyAction? onUpdate = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a column exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column exists, false otherwise. + Task DoesColumnExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a column definition. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// The column definition, or null if the column does not exist. + Task GetColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a list of column definitions. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name filter. + /// The transaction to use, or null. + /// The cancellation token. + /// A list of column definitions. + Task> GetColumnsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? columnNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a list of column names. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name filter. + /// The transaction to use, or null. + /// The cancellation token. + /// A list of column names. + Task> GetColumnNamesAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? columnNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops a column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column was dropped, false otherwise. + Task DropColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Renames a column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The new column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the column was renamed, false otherwise. + Task RenameColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + string newColumnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); +} diff --git a/src/DapperMatic/Interfaces/IDatabaseDefaultConstraintMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseDefaultConstraintMethods.cs similarity index 94% rename from src/DapperMatic/Interfaces/IDatabaseDefaultConstraintMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseDefaultConstraintMethods.cs index 28c9f46..a018125 100644 --- a/src/DapperMatic/Interfaces/IDatabaseDefaultConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseDefaultConstraintMethods.cs @@ -1,219 +1,219 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Interfaces; - -/// -/// Provides database default constraint methods for database operations. -/// -public interface IDatabaseDefaultConstraintMethods -{ - /// - /// Creates a default constraint if it does not already exist. - /// - /// The database connection. - /// The default constraint to create. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint was created, false otherwise. - Task CreateDefaultConstraintIfNotExistsAsync( - IDbConnection db, - DxDefaultConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a default constraint if it does not already exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The constraint name. - /// The constraint expression. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint was created, false otherwise. - Task CreateDefaultConstraintIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - string constraintName, - string expression, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a default constraint exists on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint exists, false otherwise. - Task DoesDefaultConstraintExistOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a default constraint exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint exists, false otherwise. - Task DoesDefaultConstraintExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the default constraint on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// The default constraint, or null if it does not exist. - Task GetDefaultConstraintOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a default constraint. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction to use, or null. - /// The cancellation token. - /// The default constraint, or null if it does not exist. - Task GetDefaultConstraintAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a list of default constraints. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction to use, or null. - /// The cancellation token. - /// A list of default constraints. - Task> GetDefaultConstraintsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the name of the default constraint on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// The name of the default constraint, or null if it does not exist. - Task GetDefaultConstraintNameOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a list of default constraint names. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction to use, or null. - /// The cancellation token. - /// A list of default constraint names. - Task> GetDefaultConstraintNamesAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops the default constraint on a column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint was dropped, false otherwise. - Task DropDefaultConstraintOnColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops a default constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction to use, or null. - /// The cancellation token. - /// True if the constraint was dropped, false otherwise. - Task DropDefaultConstraintIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Provides database default constraint methods for database operations. +/// +public interface IDatabaseDefaultConstraintMethods +{ + /// + /// Creates a default constraint if it does not already exist. + /// + /// The database connection. + /// The default constraint to create. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint was created, false otherwise. + Task CreateDefaultConstraintIfNotExistsAsync( + IDbConnection db, + DmDefaultConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a default constraint if it does not already exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The constraint name. + /// The constraint expression. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint was created, false otherwise. + Task CreateDefaultConstraintIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + string constraintName, + string expression, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a default constraint exists on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint exists, false otherwise. + Task DoesDefaultConstraintExistOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a default constraint exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint exists, false otherwise. + Task DoesDefaultConstraintExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the default constraint on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// The default constraint, or null if it does not exist. + Task GetDefaultConstraintOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a default constraint. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction to use, or null. + /// The cancellation token. + /// The default constraint, or null if it does not exist. + Task GetDefaultConstraintAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a list of default constraints. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction to use, or null. + /// The cancellation token. + /// A list of default constraints. + Task> GetDefaultConstraintsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the name of the default constraint on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// The name of the default constraint, or null if it does not exist. + Task GetDefaultConstraintNameOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a list of default constraint names. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction to use, or null. + /// The cancellation token. + /// A list of default constraint names. + Task> GetDefaultConstraintNamesAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops the default constraint on a column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint was dropped, false otherwise. + Task DropDefaultConstraintOnColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops a default constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction to use, or null. + /// The cancellation token. + /// True if the constraint was dropped, false otherwise. + Task DropDefaultConstraintIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); +} diff --git a/src/DapperMatic/Interfaces/IDatabaseForeignKeyConstraintMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseForeignKeyConstraintMethods.cs similarity index 92% rename from src/DapperMatic/Interfaces/IDatabaseForeignKeyConstraintMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseForeignKeyConstraintMethods.cs index bd77350..74915f3 100644 --- a/src/DapperMatic/Interfaces/IDatabaseForeignKeyConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseForeignKeyConstraintMethods.cs @@ -1,225 +1,225 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Interfaces; - -/// -/// Provides database default constraint methods for database operations. -/// -public interface IDatabaseForeignKeyConstraintMethods -{ - /// - /// Creates a foreign key constraint if it does not already exist. - /// - /// The database connection. - /// The foreign key constraint to create. - /// The database transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - Task CreateForeignKeyConstraintIfNotExistsAsync( - IDbConnection db, - DxForeignKeyConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a foreign key constraint if it does not already exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The source columns. - /// The referenced table name. - /// The referenced columns. - /// The action on delete. - /// The action on update. - /// The database transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - Task CreateForeignKeyConstraintIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - DxOrderedColumn[] sourceColumns, - string referencedTableName, - DxOrderedColumn[] referencedColumns, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a foreign key constraint exists on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// True if the constraint exists, otherwise false. - Task DoesForeignKeyConstraintExistOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a foreign key constraint exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The database transaction. - /// The cancellation token. - /// True if the constraint exists, otherwise false. - Task DoesForeignKeyConstraintExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the foreign key constraint on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// The foreign key constraint if it exists, otherwise null. - Task GetForeignKeyConstraintOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the foreign key constraint. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The database transaction. - /// The cancellation token. - /// The foreign key constraint if it exists, otherwise null. - Task GetForeignKeyConstraintAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the foreign key constraints. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The database transaction. - /// The cancellation token. - /// A list of foreign key constraints. - Task> GetForeignKeyConstraintsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the foreign key constraint name on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// The foreign key constraint name if it exists, otherwise null. - Task GetForeignKeyConstraintNameOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the foreign key constraint names. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The database transaction. - /// The cancellation token. - /// A list of foreign key constraint names. - Task> GetForeignKeyConstraintNamesAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops a foreign key constraint on a column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - Task DropForeignKeyConstraintOnColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops a foreign key constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The database transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - Task DropForeignKeyConstraintIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Provides database default constraint methods for database operations. +/// +public interface IDatabaseForeignKeyConstraintMethods +{ + /// + /// Creates a foreign key constraint if it does not already exist. + /// + /// The database connection. + /// The foreign key constraint to create. + /// The database transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + Task CreateForeignKeyConstraintIfNotExistsAsync( + IDbConnection db, + DmForeignKeyConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a foreign key constraint if it does not already exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The source columns. + /// The referenced table name. + /// The referenced columns. + /// The action on delete. + /// The action on update. + /// The database transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + Task CreateForeignKeyConstraintIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + DmOrderedColumn[] sourceColumns, + string referencedTableName, + DmOrderedColumn[] referencedColumns, + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a foreign key constraint exists on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// True if the constraint exists, otherwise false. + Task DoesForeignKeyConstraintExistOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a foreign key constraint exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The database transaction. + /// The cancellation token. + /// True if the constraint exists, otherwise false. + Task DoesForeignKeyConstraintExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the foreign key constraint on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// The foreign key constraint if it exists, otherwise null. + Task GetForeignKeyConstraintOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the foreign key constraint. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The database transaction. + /// The cancellation token. + /// The foreign key constraint if it exists, otherwise null. + Task GetForeignKeyConstraintAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the foreign key constraints. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The database transaction. + /// The cancellation token. + /// A list of foreign key constraints. + Task> GetForeignKeyConstraintsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the foreign key constraint name on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// The foreign key constraint name if it exists, otherwise null. + Task GetForeignKeyConstraintNameOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the foreign key constraint names. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The database transaction. + /// The cancellation token. + /// A list of foreign key constraint names. + Task> GetForeignKeyConstraintNamesAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops a foreign key constraint on a column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + Task DropForeignKeyConstraintOnColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops a foreign key constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The database transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + Task DropForeignKeyConstraintIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); +} diff --git a/src/DapperMatic/Interfaces/IDatabaseIndexMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseIndexMethods.cs similarity index 94% rename from src/DapperMatic/Interfaces/IDatabaseIndexMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseIndexMethods.cs index 6f110d8..e058bef 100644 --- a/src/DapperMatic/Interfaces/IDatabaseIndexMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseIndexMethods.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Interfaces; +namespace MJCZone.DapperMatic.Interfaces; /// /// Provides database index methods for database operations. @@ -18,7 +18,7 @@ public interface IDatabaseIndexMethods /// A task that represents the asynchronous operation. The task result contains a boolean indicating success. Task CreateIndexIfNotExistsAsync( IDbConnection db, - DxIndex index, + DmIndex index, IDbTransaction? tx = null, CancellationToken cancellationToken = default ); @@ -40,7 +40,7 @@ Task CreateIndexIfNotExistsAsync( string? schemaName, string tableName, string indexName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, bool isUnique = false, IDbTransaction? tx = null, CancellationToken cancellationToken = default @@ -94,7 +94,7 @@ Task DoesIndexExistAsync( /// The database transaction. /// The cancellation token. /// A task that represents the asynchronous operation. The task result contains a list of indexes. - Task> GetIndexesOnColumnAsync( + Task> GetIndexesOnColumnAsync( IDbConnection db, string? schemaName, string tableName, @@ -113,7 +113,7 @@ Task> GetIndexesOnColumnAsync( /// The database transaction. /// The cancellation token. /// A task that represents the asynchronous operation. The task result contains the index. - Task GetIndexAsync( + Task GetIndexAsync( IDbConnection db, string? schemaName, string tableName, @@ -132,7 +132,7 @@ Task> GetIndexesOnColumnAsync( /// The database transaction. /// The cancellation token. /// A task that represents the asynchronous operation. The task result contains a list of indexes. - Task> GetIndexesAsync( + Task> GetIndexesAsync( IDbConnection db, string? schemaName, string tableName, diff --git a/src/DapperMatic/Interfaces/IDatabaseMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseMethods.cs similarity index 92% rename from src/DapperMatic/Interfaces/IDatabaseMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseMethods.cs index fbc98b7..b335bbb 100644 --- a/src/DapperMatic/Interfaces/IDatabaseMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseMethods.cs @@ -1,95 +1,88 @@ -using System.Data; -using DapperMatic.Providers; - -namespace DapperMatic.Interfaces; - -/// -/// Defines methods for interacting with a database. -/// -public interface IDatabaseMethods - : IDatabaseTableMethods, - IDatabaseColumnMethods, - IDatabaseIndexMethods, - IDatabaseCheckConstraintMethods, - IDatabaseDefaultConstraintMethods, - IDatabasePrimaryKeyConstraintMethods, - IDatabaseUniqueConstraintMethods, - IDatabaseForeignKeyConstraintMethods, - IDatabaseSchemaMethods, - IDatabaseViewMethods -{ - /// - /// Gets the type of the database provider. - /// - DbProviderType ProviderType { get; } - - /// - /// Gets the provider type map. - /// - IDbProviderTypeMap ProviderTypeMap { get; } - - /// - /// Gets a value indicating whether the database supports schemas. - /// - bool SupportsSchemas { get; } - - /// - /// Determines whether the database supports check constraints. - /// - /// The database connection. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating support for check constraints. - Task SupportsCheckConstraintsAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Determines whether the database supports ordered keys in constraints. - /// - /// The database connection. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating support for ordered keys in constraints. - Task SupportsOrderedKeysInConstraintsAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the version of the database. - /// - /// The database connection. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the database version. - Task GetDatabaseVersionAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the .NET type descriptor from the SQL type. - /// - /// The SQL type. - /// The .NET type descriptor. - DotnetTypeDescriptor GetDotnetTypeFromSqlType(string sqlType); - - /// - /// Gets the SQL type from the .NET type descriptor. - /// - /// The .NET type descriptor. - /// The SQL type. - string GetSqlTypeFromDotnetType(DotnetTypeDescriptor descriptor); - - /// - /// Normalizes the name. - /// - /// The name to normalize. - /// The normalized name. - string NormalizeName(string name); -} +using System.Data; +using MJCZone.DapperMatic.Providers; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Defines methods for interacting with a database. +/// +public interface IDatabaseMethods + : IDatabaseTableMethods, + IDatabaseColumnMethods, + IDatabaseIndexMethods, + IDatabaseCheckConstraintMethods, + IDatabaseDefaultConstraintMethods, + IDatabasePrimaryKeyConstraintMethods, + IDatabaseUniqueConstraintMethods, + IDatabaseForeignKeyConstraintMethods, + IDatabaseSchemaMethods, + IDatabaseViewMethods +{ + /// + /// Gets the type of the database provider. + /// + DbProviderType ProviderType { get; } + + /// + /// Gets the provider type map. + /// + IDbProviderTypeMap ProviderTypeMap { get; } + + /// + /// Gets a value indicating whether the database supports schemas. + /// + bool SupportsSchemas { get; } + + /// + /// Determines whether the database supports check constraints. + /// + /// The database connection. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating support for check constraints. + Task SupportsCheckConstraintsAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Determines whether the database supports ordered keys in constraints. + /// + /// The database connection. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating support for ordered keys in constraints. + Task SupportsOrderedKeysInConstraintsAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the version of the database. + /// + /// The database connection. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the database version. + Task GetDatabaseVersionAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the .NET type descriptor from the SQL type. + /// + /// The SQL type. + /// The .NET type descriptor. + DotnetTypeDescriptor GetDotnetTypeFromSqlType(string sqlType); + + /// + /// Gets the SQL type from the .NET type descriptor. + /// + /// The .NET type descriptor. + /// The SQL type. + string GetSqlTypeFromDotnetType(DotnetTypeDescriptor descriptor); +} diff --git a/src/DapperMatic/Interfaces/IDatabaseMethodsFactory.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseMethodsFactory.cs similarity index 92% rename from src/DapperMatic/Interfaces/IDatabaseMethodsFactory.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseMethodsFactory.cs index 9b8abd2..cc882d9 100644 --- a/src/DapperMatic/Interfaces/IDatabaseMethodsFactory.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseMethodsFactory.cs @@ -1,23 +1,23 @@ -using System.Data; - -namespace DapperMatic.Interfaces; - -/// -/// Factory interface for creating database methods. -/// -public interface IDatabaseMethodsFactory -{ - /// - /// Determines whether the factory supports the specified database connection. - /// - /// The database connection. - /// true if the factory supports the specified database connection; otherwise, false. - bool SupportsConnection(IDbConnection db); - - /// - /// Gets the database methods for the specified database connection. - /// - /// The database connection. - /// An instance of for the specified database connection. - IDatabaseMethods GetMethods(IDbConnection db); -} \ No newline at end of file +using System.Data; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Factory interface for creating database methods. +/// +public interface IDatabaseMethodsFactory +{ + /// + /// Determines whether the factory supports the specified database connection. + /// + /// The database connection. + /// true if the factory supports the specified database connection; otherwise, false. + bool SupportsConnection(IDbConnection db); + + /// + /// Gets the database methods for the specified database connection. + /// + /// The database connection. + /// An instance of for the specified database connection. + IDatabaseMethods GetMethods(IDbConnection db); +} diff --git a/src/DapperMatic/Interfaces/IDatabasePrimaryKeyConstraintMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabasePrimaryKeyConstraintMethods.cs similarity index 92% rename from src/DapperMatic/Interfaces/IDatabasePrimaryKeyConstraintMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabasePrimaryKeyConstraintMethods.cs index f4e4010..19f1e1b 100644 --- a/src/DapperMatic/Interfaces/IDatabasePrimaryKeyConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabasePrimaryKeyConstraintMethods.cs @@ -1,97 +1,97 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Interfaces; - -/// -/// Provides database primary key constraint methods for database operations. -/// -public interface IDatabasePrimaryKeyConstraintMethods -{ - /// - /// Creates a primary key constraint if it does not already exist. - /// - /// The database connection. - /// The primary key constraint to create. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the constraint was created. - Task CreatePrimaryKeyConstraintIfNotExistsAsync( - IDbConnection db, - DxPrimaryKeyConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a primary key constraint if it does not already exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The columns that make up the primary key. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the constraint was created. - Task CreatePrimaryKeyConstraintIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - DxOrderedColumn[] columns, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a primary key constraint exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the constraint exists. - Task DoesPrimaryKeyConstraintExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the primary key constraint. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the primary key constraint. - Task GetPrimaryKeyConstraintAsync( - IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops a primary key constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the constraint was dropped. - Task DropPrimaryKeyConstraintIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Provides database primary key constraint methods for database operations. +/// +public interface IDatabasePrimaryKeyConstraintMethods +{ + /// + /// Creates a primary key constraint if it does not already exist. + /// + /// The database connection. + /// The primary key constraint to create. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the constraint was created. + Task CreatePrimaryKeyConstraintIfNotExistsAsync( + IDbConnection db, + DmPrimaryKeyConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a primary key constraint if it does not already exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The columns that make up the primary key. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the constraint was created. + Task CreatePrimaryKeyConstraintIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + DmOrderedColumn[] columns, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a primary key constraint exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the constraint exists. + Task DoesPrimaryKeyConstraintExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the primary key constraint. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the primary key constraint. + Task GetPrimaryKeyConstraintAsync( + IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops a primary key constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the constraint was dropped. + Task DropPrimaryKeyConstraintIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); +} diff --git a/src/DapperMatic/Interfaces/IDatabaseSchemaMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseSchemaMethods.cs similarity index 96% rename from src/DapperMatic/Interfaces/IDatabaseSchemaMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseSchemaMethods.cs index e23882a..17f5153 100644 --- a/src/DapperMatic/Interfaces/IDatabaseSchemaMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseSchemaMethods.cs @@ -1,77 +1,77 @@ -using System.Data; - -namespace DapperMatic.Interfaces; - -/// -/// Provides database methods for database operations. -/// -public interface IDatabaseSchemaMethods -{ - /// - /// Gets the schema-qualified identifier name. - /// - /// The schema name. - /// The table name. - /// The schema-qualified identifier name. - string GetSchemaQualifiedIdentifierName(string? schemaName, string tableName); - - /// - /// Creates the schema if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating success. - Task CreateSchemaIfNotExistsAsync( - IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if the schema exists. - /// - /// The database connection. - /// The schema name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating existence. - Task DoesSchemaExistAsync( - IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the schema names. - /// - /// The database connection. - /// The schema name filter. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of schema names. - Task> GetSchemaNamesAsync( - IDbConnection db, - string? schemaNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops the schema if it exists. - /// - /// The database connection. - /// The schema name. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating success. - Task DropSchemaIfExistsAsync( - IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); -} +using System.Data; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Provides database methods for database operations. +/// +public interface IDatabaseSchemaMethods +{ + /// + /// Gets the schema-qualified identifier name. + /// + /// The schema name. + /// The table name. + /// The schema-qualified identifier name. + string GetSchemaQualifiedIdentifierName(string? schemaName, string tableName); + + /// + /// Creates the schema if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating success. + Task CreateSchemaIfNotExistsAsync( + IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if the schema exists. + /// + /// The database connection. + /// The schema name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating existence. + Task DoesSchemaExistAsync( + IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the schema names. + /// + /// The database connection. + /// The schema name filter. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a list of schema names. + Task> GetSchemaNamesAsync( + IDbConnection db, + string? schemaNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops the schema if it exists. + /// + /// The database connection. + /// The schema name. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating success. + Task DropSchemaIfExistsAsync( + IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); +} diff --git a/src/DapperMatic/Interfaces/IDatabaseTableMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseTableMethods.cs similarity index 91% rename from src/DapperMatic/Interfaces/IDatabaseTableMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseTableMethods.cs index 9ab92b1..20aeeda 100644 --- a/src/DapperMatic/Interfaces/IDatabaseTableMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseTableMethods.cs @@ -1,177 +1,177 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Interfaces; - -/// -/// Provides database table methods for database operations. -/// -public interface IDatabaseTableMethods -{ - /// - /// Checks if a table exists in the database. - /// - /// The database connection. - /// The schema name of the table. - /// The name of the table. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table exists. - Task DoesTableExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a table if it does not exist. - /// - /// The database connection. - /// The table definition. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was created. - Task CreateTableIfNotExistsAsync( - IDbConnection db, - DxTable table, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a table with specified columns and constraints if it does not exist. - /// - /// The database connection. - /// The schema name of the table. - /// The name of the table. - /// The columns of the table. - /// The primary key constraint. - /// The check constraints. - /// The default constraints. - /// The unique constraints. - /// The foreign key constraints. - /// The indexes. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was created. - Task CreateTableIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - DxColumn[] columns, - DxPrimaryKeyConstraint? primaryKey = null, - DxCheckConstraint[]? checkConstraints = null, - DxDefaultConstraint[]? defaultConstraints = null, - DxUniqueConstraint[]? uniqueConstraints = null, - DxForeignKeyConstraint[]? foreignKeyConstraints = null, - DxIndex[]? indexes = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieves a table definition from the database. - /// - /// The database connection. - /// The schema name of the table. - /// The name of the table. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the table definition. - Task GetTableAsync( - IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieves a list of table definitions from the database. - /// - /// The database connection. - /// The schema name of the tables. - /// The table name filter. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of table definitions. - Task> GetTablesAsync( - IDbConnection db, - string? schemaName, - string? tableNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Retrieves a list of table names from the database. - /// - /// The database connection. - /// The schema name of the tables. - /// The table name filter. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a list of table names. - Task> GetTableNamesAsync( - IDbConnection db, - string? schemaName, - string? tableNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops a table if it exists in the database. - /// - /// The database connection. - /// The schema name of the table. - /// The name of the table. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was dropped. - Task DropTableIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Renames a table if it exists in the database. - /// - /// The database connection. - /// The schema name of the table. - /// The name of the table. - /// The new name of the table. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was renamed. - Task RenameTableIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string newTableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Truncates a table if it exists in the database. - /// - /// The database connection. - /// The schema name of the table. - /// The name of the table. - /// The database transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was truncated. - Task TruncateTableIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Provides database table methods for database operations. +/// +public interface IDatabaseTableMethods +{ + /// + /// Checks if a table exists in the database. + /// + /// The database connection. + /// The schema name of the table. + /// The name of the table. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table exists. + Task DoesTableExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a table if it does not exist. + /// + /// The database connection. + /// The table definition. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was created. + Task CreateTableIfNotExistsAsync( + IDbConnection db, + DmTable table, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a table with specified columns and constraints if it does not exist. + /// + /// The database connection. + /// The schema name of the table. + /// The name of the table. + /// The columns of the table. + /// The primary key constraint. + /// The check constraints. + /// The default constraints. + /// The unique constraints. + /// The foreign key constraints. + /// The indexes. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was created. + Task CreateTableIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + DmColumn[] columns, + DmPrimaryKeyConstraint? primaryKey = null, + DmCheckConstraint[]? checkConstraints = null, + DmDefaultConstraint[]? defaultConstraints = null, + DmUniqueConstraint[]? uniqueConstraints = null, + DmForeignKeyConstraint[]? foreignKeyConstraints = null, + DmIndex[]? indexes = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieves a table definition from the database. + /// + /// The database connection. + /// The schema name of the table. + /// The name of the table. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the table definition. + Task GetTableAsync( + IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieves a list of table definitions from the database. + /// + /// The database connection. + /// The schema name of the tables. + /// The table name filter. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a list of table definitions. + Task> GetTablesAsync( + IDbConnection db, + string? schemaName, + string? tableNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieves a list of table names from the database. + /// + /// The database connection. + /// The schema name of the tables. + /// The table name filter. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a list of table names. + Task> GetTableNamesAsync( + IDbConnection db, + string? schemaName, + string? tableNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops a table if it exists in the database. + /// + /// The database connection. + /// The schema name of the table. + /// The name of the table. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was dropped. + Task DropTableIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Renames a table if it exists in the database. + /// + /// The database connection. + /// The schema name of the table. + /// The name of the table. + /// The new name of the table. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was renamed. + Task RenameTableIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string newTableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Truncates a table if it exists in the database. + /// + /// The database connection. + /// The schema name of the table. + /// The name of the table. + /// The database transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the table was truncated. + Task TruncateTableIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); +} diff --git a/src/DapperMatic/Interfaces/IDatabaseUniqueConstraintMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseUniqueConstraintMethods.cs similarity index 94% rename from src/DapperMatic/Interfaces/IDatabaseUniqueConstraintMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseUniqueConstraintMethods.cs index 5ac0636..a645b37 100644 --- a/src/DapperMatic/Interfaces/IDatabaseUniqueConstraintMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseUniqueConstraintMethods.cs @@ -1,217 +1,217 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Interfaces; - -/// -/// Provides database primary key constraint methods for database operations. -/// -public interface IDatabaseUniqueConstraintMethods -{ - /// - /// Creates a unique constraint if it does not already exist. - /// - /// The database connection. - /// The unique constraint to create. - /// The database transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - Task CreateUniqueConstraintIfNotExistsAsync( - IDbConnection db, - DxUniqueConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a unique constraint if it does not already exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The columns included in the constraint. - /// The database transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - Task CreateUniqueConstraintIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - DxOrderedColumn[] columns, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a unique constraint exists on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// True if the constraint exists, otherwise false. - Task DoesUniqueConstraintExistOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Checks if a unique constraint exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The database transaction. - /// The cancellation token. - /// True if the constraint exists, otherwise false. - Task DoesUniqueConstraintExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the unique constraint on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// The unique constraint if it exists, otherwise null. - Task GetUniqueConstraintOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the unique constraint. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The database transaction. - /// The cancellation token. - /// The unique constraint if it exists, otherwise null. - Task GetUniqueConstraintAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the unique constraints. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The database transaction. - /// The cancellation token. - /// A list of unique constraints. - Task> GetUniqueConstraintsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the unique constraint name on a column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// The unique constraint name if it exists, otherwise null. - Task GetUniqueConstraintNameOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets the unique constraint names. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The database transaction. - /// The cancellation token. - /// A list of unique constraint names. - Task> GetUniqueConstraintNamesAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops the unique constraint on a column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - Task DropUniqueConstraintOnColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops the unique constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The database transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - Task DropUniqueConstraintIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Provides database primary key constraint methods for database operations. +/// +public interface IDatabaseUniqueConstraintMethods +{ + /// + /// Creates a unique constraint if it does not already exist. + /// + /// The database connection. + /// The unique constraint to create. + /// The database transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + Task CreateUniqueConstraintIfNotExistsAsync( + IDbConnection db, + DmUniqueConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a unique constraint if it does not already exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The columns included in the constraint. + /// The database transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + Task CreateUniqueConstraintIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + DmOrderedColumn[] columns, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a unique constraint exists on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// True if the constraint exists, otherwise false. + Task DoesUniqueConstraintExistOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Checks if a unique constraint exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The database transaction. + /// The cancellation token. + /// True if the constraint exists, otherwise false. + Task DoesUniqueConstraintExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the unique constraint on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// The unique constraint if it exists, otherwise null. + Task GetUniqueConstraintOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the unique constraint. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The database transaction. + /// The cancellation token. + /// The unique constraint if it exists, otherwise null. + Task GetUniqueConstraintAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the unique constraints. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The database transaction. + /// The cancellation token. + /// A list of unique constraints. + Task> GetUniqueConstraintsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the unique constraint name on a column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// The unique constraint name if it exists, otherwise null. + Task GetUniqueConstraintNameOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets the unique constraint names. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The database transaction. + /// The cancellation token. + /// A list of unique constraint names. + Task> GetUniqueConstraintNamesAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops the unique constraint on a column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + Task DropUniqueConstraintOnColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops the unique constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The database transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + Task DropUniqueConstraintIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); +} diff --git a/src/DapperMatic/Interfaces/IDatabaseViewMethods.cs b/src/MJCZone.DapperMatic/Interfaces/IDatabaseViewMethods.cs similarity index 94% rename from src/DapperMatic/Interfaces/IDatabaseViewMethods.cs rename to src/MJCZone.DapperMatic/Interfaces/IDatabaseViewMethods.cs index 82b51f2..219666b 100644 --- a/src/DapperMatic/Interfaces/IDatabaseViewMethods.cs +++ b/src/MJCZone.DapperMatic/Interfaces/IDatabaseViewMethods.cs @@ -1,148 +1,148 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Interfaces; - -/// -/// Provides database view methods for database operations. -/// -public interface IDatabaseViewMethods -{ - /// - /// Checks if a view exists in the database. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The database transaction. - /// The cancellation token. - /// True if the view exists, otherwise false. - Task DoesViewExistAsync( - IDbConnection db, - string? schemaName, - string viewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a view if it does not exist. - /// - /// The database connection. - /// The view definition. - /// The database transaction. - /// The cancellation token. - /// True if the view was created, otherwise false. - Task CreateViewIfNotExistsAsync( - IDbConnection db, - DxView view, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Creates a view if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The view definition. - /// The database transaction. - /// The cancellation token. - /// True if the view was created, otherwise false. - Task CreateViewIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string viewName, - string definition, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a view from the database. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The database transaction. - /// The cancellation token. - /// The view if found, otherwise null. - Task GetViewAsync( - IDbConnection db, - string? schemaName, - string viewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a list of views from the database. - /// - /// The database connection. - /// The schema name. - /// The view name filter. - /// The database transaction. - /// The cancellation token. - /// A list of views. - Task> GetViewsAsync( - IDbConnection db, - string? schemaName, - string? viewNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Gets a list of view names from the database. - /// - /// The database connection. - /// The schema name. - /// The view name filter. - /// The database transaction. - /// The cancellation token. - /// A list of view names. - Task> GetViewNamesAsync( - IDbConnection db, - string? schemaName, - string? viewNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Drops a view if it exists. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The database transaction. - /// The cancellation token. - /// True if the view was dropped, otherwise false. - Task DropViewIfExistsAsync( - IDbConnection db, - string? schemaName, - string viewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); - - /// - /// Renames a view if it exists. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The new view name. - /// The database transaction. - /// The cancellation token. - /// True if the view was renamed, otherwise false. - Task RenameViewIfExistsAsync( - IDbConnection db, - string? schemaName, - string viewName, - string newViewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ); -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Interfaces; + +/// +/// Provides database view methods for database operations. +/// +public interface IDatabaseViewMethods +{ + /// + /// Checks if a view exists in the database. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The database transaction. + /// The cancellation token. + /// True if the view exists, otherwise false. + Task DoesViewExistAsync( + IDbConnection db, + string? schemaName, + string viewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a view if it does not exist. + /// + /// The database connection. + /// The view definition. + /// The database transaction. + /// The cancellation token. + /// True if the view was created, otherwise false. + Task CreateViewIfNotExistsAsync( + IDbConnection db, + DmView view, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Creates a view if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The view definition. + /// The database transaction. + /// The cancellation token. + /// True if the view was created, otherwise false. + Task CreateViewIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string viewName, + string definition, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a view from the database. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The database transaction. + /// The cancellation token. + /// The view if found, otherwise null. + Task GetViewAsync( + IDbConnection db, + string? schemaName, + string viewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a list of views from the database. + /// + /// The database connection. + /// The schema name. + /// The view name filter. + /// The database transaction. + /// The cancellation token. + /// A list of views. + Task> GetViewsAsync( + IDbConnection db, + string? schemaName, + string? viewNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Gets a list of view names from the database. + /// + /// The database connection. + /// The schema name. + /// The view name filter. + /// The database transaction. + /// The cancellation token. + /// A list of view names. + Task> GetViewNamesAsync( + IDbConnection db, + string? schemaName, + string? viewNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Drops a view if it exists. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The database transaction. + /// The cancellation token. + /// True if the view was dropped, otherwise false. + Task DropViewIfExistsAsync( + IDbConnection db, + string? schemaName, + string viewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); + + /// + /// Renames a view if it exists. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The new view name. + /// The database transaction. + /// The cancellation token. + /// True if the view was renamed, otherwise false. + Task RenameViewIfExistsAsync( + IDbConnection db, + string? schemaName, + string viewName, + string newViewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ); +} diff --git a/src/MJCZone.DapperMatic/MJCZone.DapperMatic.csproj b/src/MJCZone.DapperMatic/MJCZone.DapperMatic.csproj new file mode 100644 index 0000000..bc0a6a2 --- /dev/null +++ b/src/MJCZone.DapperMatic/MJCZone.DapperMatic.csproj @@ -0,0 +1,31 @@ + + + + MJCZone.DapperMatic + dotnet dapper mysql sqlserver postgresql sqlite + + + https://github.com/mjczone/MJCZone.DapperMatic/LICENSE + https://github.com/mjczone/MJCZone.DapperMatic/ + https://github.com/mjczone/MJCZone.DapperMatic/ + + 0.0.1 + + Additional database extensions (leveraging Dapper). + + + MJCZone.DapperMatic + MJCZone.DapperMatic + + + + + + + + + <_Parameter1>MJCZone.DapperMatic.Tests + + + + diff --git a/src/DapperMatic/Models/DxCheckConstraint.cs b/src/MJCZone.DapperMatic/Models/DmCheckConstraint.cs similarity index 84% rename from src/DapperMatic/Models/DxCheckConstraint.cs rename to src/MJCZone.DapperMatic/Models/DmCheckConstraint.cs index b549851..ec52ff5 100644 --- a/src/DapperMatic/Models/DxCheckConstraint.cs +++ b/src/MJCZone.DapperMatic/Models/DmCheckConstraint.cs @@ -1,84 +1,84 @@ -using System.Diagnostics.CodeAnalysis; - -namespace DapperMatic.Models; - -/// -/// Represents a check constraint in a database. -/// -[Serializable] -public class DxCheckConstraint : DxConstraint -{ - /// - /// Initializes a new instance of the class. - /// Used for deserialization. - /// - public DxCheckConstraint() - : base(string.Empty) { } - - /// - /// Initializes a new instance of the class. - /// - /// The schema name. - /// The table name. - /// The column name. - /// The constraint name. - /// The expression. - [SetsRequiredMembers] - public DxCheckConstraint( - string? schemaName, - string tableName, - string? columnName, - string constraintName, - string expression - ) - : base(constraintName) - { - SchemaName = schemaName; - TableName = string.IsNullOrWhiteSpace(tableName) - ? throw new ArgumentException("Table name is required") - : tableName; - ColumnName = columnName; - Expression = string.IsNullOrWhiteSpace(expression) - ? throw new ArgumentException("Expression is required") - : expression; - } - - /// - /// Gets or sets the schema name. - /// - public string? SchemaName { get; set; } - - /// - /// Gets the table name. - /// - public required string TableName { get; init; } - - /// - /// Gets or sets the column name. - /// - public string? ColumnName { get; set; } - - /// - /// Gets the expression. - /// - public required string Expression { get; init; } - - /// - /// Gets the constraint type. - /// - public override DxConstraintType ConstraintType => DxConstraintType.Check; - - /// - /// Returns a string representation of the constraint. - /// - /// A string representation of the constraint. - public override string ToString() - { - if (string.IsNullOrWhiteSpace(ColumnName)) - { - return $"{ConstraintType} Constraint on {TableName} with expression: {Expression}"; - } - - return $"{ConstraintType} Constraint on {TableName}.{ColumnName} with expression: {Expression}"; - } -} +using System.Diagnostics.CodeAnalysis; + +namespace MJCZone.DapperMatic.Models; + +/// +/// Represents a check constraint in a database. +/// +[Serializable] +public class DmCheckConstraint : DmConstraint +{ + /// + /// Initializes a new instance of the class. + /// Used for deserialization. + /// + public DmCheckConstraint() + : base(string.Empty) { } + + /// + /// Initializes a new instance of the class. + /// + /// The schema name. + /// The table name. + /// The column name. + /// The constraint name. + /// The expression. + [SetsRequiredMembers] + public DmCheckConstraint( + string? schemaName, + string tableName, + string? columnName, + string constraintName, + string expression + ) + : base(constraintName) + { + SchemaName = schemaName; + TableName = string.IsNullOrWhiteSpace(tableName) + ? throw new ArgumentException("Table name is required") + : tableName; + ColumnName = columnName; + Expression = string.IsNullOrWhiteSpace(expression) + ? throw new ArgumentException("Expression is required") + : expression; + } + + /// + /// Gets or sets the schema name. + /// + public string? SchemaName { get; set; } + + /// + /// Gets the table name. + /// + public required string TableName { get; init; } + + /// + /// Gets or sets the column name. + /// + public string? ColumnName { get; set; } + + /// + /// Gets the expression. + /// + public required string Expression { get; init; } + + /// + /// Gets the constraint type. + /// + public override DmConstraintType ConstraintType => DmConstraintType.Check; + + /// + /// Returns a string representation of the constraint. + /// + /// A string representation of the constraint. + public override string ToString() + { + if (string.IsNullOrWhiteSpace(ColumnName)) + { + return $"{ConstraintType} Constraint on {TableName} with expression: {Expression}"; + } + + return $"{ConstraintType} Constraint on {TableName}.{ColumnName} with expression: {Expression}"; + } +} diff --git a/src/DapperMatic/Models/DxColumn.cs b/src/MJCZone.DapperMatic/Models/DmColumn.cs similarity index 92% rename from src/DapperMatic/Models/DxColumn.cs rename to src/MJCZone.DapperMatic/Models/DmColumn.cs index 0687c94..021c101 100644 --- a/src/DapperMatic/Models/DxColumn.cs +++ b/src/MJCZone.DapperMatic/Models/DmColumn.cs @@ -2,21 +2,21 @@ using System.Runtime.CompilerServices; using System.Text.Json; -namespace DapperMatic.Models; +namespace MJCZone.DapperMatic.Models; /// /// Represents a database column with various properties and methods to determine its characteristics. /// [Serializable] -public class DxColumn +public class DmColumn { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public DxColumn() { } + public DmColumn() { } /// - /// Initializes a new instance of the class with the specified parameters. + /// Initializes a new instance of the class with the specified parameters. /// /// The schema name. /// The table name. @@ -39,7 +39,7 @@ public DxColumn() { } /// The action on delete. /// The action on update. [SetsRequiredMembers] - public DxColumn( + public DmColumn( string? schemaName, string tableName, string columnName, @@ -58,8 +58,8 @@ public DxColumn( bool isForeignKey = false, string? referencedTableName = null, string? referencedColumnName = null, - DxForeignKeyAction? onDelete = null, - DxForeignKeyAction? onUpdate = null + DmForeignKeyAction? onDelete = null, + DmForeignKeyAction? onUpdate = null ) { SchemaName = schemaName; @@ -191,12 +191,12 @@ public DxColumn( /// /// Gets or sets the action on delete. /// - public DxForeignKeyAction? OnDelete { get; set; } + public DmForeignKeyAction? OnDelete { get; set; } /// /// Gets or sets the action on update. /// - public DxForeignKeyAction? OnUpdate { get; set; } + public DmForeignKeyAction? OnUpdate { get; set; } /// /// Determines whether the column is numeric. @@ -393,8 +393,8 @@ public override string ToString() /// /// The provider type. /// The provider data type. - /// The current instance. - public DxColumn SetProviderDataType(DbProviderType providerType, string providerDataType) + /// The current instance. + public DmColumn SetProviderDataType(DbProviderType providerType, string providerDataType) { ProviderDataTypes[providerType] = providerDataType; return this; diff --git a/src/DapperMatic/Models/DxColumnOrder.cs b/src/MJCZone.DapperMatic/Models/DmColumnOrder.cs similarity index 80% rename from src/DapperMatic/Models/DxColumnOrder.cs rename to src/MJCZone.DapperMatic/Models/DmColumnOrder.cs index f2d9f5c..8c6e42f 100644 --- a/src/DapperMatic/Models/DxColumnOrder.cs +++ b/src/MJCZone.DapperMatic/Models/DmColumnOrder.cs @@ -1,18 +1,18 @@ -namespace DapperMatic.Models; - -/// -/// Specifies the order of a column in an index or constraint. -/// -[Serializable] -public enum DxColumnOrder -{ - /// - /// Specifies that the column is sorted in ascending order. - /// - Ascending, - - /// - /// Specifies that the column is sorted in descending order. - /// - Descending, -} +namespace MJCZone.DapperMatic.Models; + +/// +/// Specifies the order of a column in an index or constraint. +/// +[Serializable] +public enum DmColumnOrder +{ + /// + /// Specifies that the column is sorted in ascending order. + /// + Ascending, + + /// + /// Specifies that the column is sorted in descending order. + /// + Descending, +} diff --git a/src/DapperMatic/Models/DxCommand.cs b/src/MJCZone.DapperMatic/Models/DmCommand.cs similarity index 70% rename from src/DapperMatic/Models/DxCommand.cs rename to src/MJCZone.DapperMatic/Models/DmCommand.cs index 4a010ad..28ea1a0 100644 --- a/src/DapperMatic/Models/DxCommand.cs +++ b/src/MJCZone.DapperMatic/Models/DmCommand.cs @@ -1,33 +1,33 @@ -namespace DapperMatic.Models; - -/// -/// Represents a SQL command with its associated parameters. -/// -public class DxCommand -{ - /// - /// Initializes a new instance of the class. - /// - public DxCommand() { } - - /// - /// Initializes a new instance of the class with the specified SQL command text and parameters. - /// - /// The SQL command text. - /// The parameters for the SQL command. - public DxCommand(string sql, IDictionary? parameters = null) - { - Sql = sql; - Parameters = parameters; - } - - /// - /// Gets or sets the SQL command text. - /// - public string? Sql { get; set; } - - /// - /// Gets or sets the parameters for the SQL command. - /// - public IDictionary? Parameters { get; set; } -} +namespace MJCZone.DapperMatic.Models; + +/// +/// Represents a SQL command with its associated parameters. +/// +public class DmCommand +{ + /// + /// Initializes a new instance of the class. + /// + public DmCommand() { } + + /// + /// Initializes a new instance of the class with the specified SQL command text and parameters. + /// + /// The SQL command text. + /// The parameters for the SQL command. + public DmCommand(string sql, IDictionary? parameters = null) + { + Sql = sql; + Parameters = parameters; + } + + /// + /// Gets or sets the SQL command text. + /// + public string? Sql { get; set; } + + /// + /// Gets or sets the parameters for the SQL command. + /// + public IDictionary? Parameters { get; set; } +} diff --git a/src/DapperMatic/Models/DxConstraint.cs b/src/MJCZone.DapperMatic/Models/DmConstraint.cs similarity index 62% rename from src/DapperMatic/Models/DxConstraint.cs rename to src/MJCZone.DapperMatic/Models/DmConstraint.cs index 4298d39..46f6a9d 100644 --- a/src/DapperMatic/Models/DxConstraint.cs +++ b/src/MJCZone.DapperMatic/Models/DmConstraint.cs @@ -1,26 +1,26 @@ -namespace DapperMatic.Models; - -/// -/// Represents a constraint on a table. -/// -public abstract class DxConstraint -{ - /// - /// Initializes a new instance of the class. - /// - /// The name of the constraint. - protected DxConstraint(string constraintName) - { - ConstraintName = constraintName; - } - - /// - /// Gets the type of the constraint. - /// - public abstract DxConstraintType ConstraintType { get; } - - /// - /// Gets or sets the name of the constraint. - /// - public string ConstraintName { get; set; } -} +namespace MJCZone.DapperMatic.Models; + +/// +/// Represents a constraint on a table. +/// +public abstract class DmConstraint +{ + /// + /// Initializes a new instance of the class. + /// + /// The name of the constraint. + protected DmConstraint(string constraintName) + { + ConstraintName = constraintName; + } + + /// + /// Gets the type of the constraint. + /// + public abstract DmConstraintType ConstraintType { get; } + + /// + /// Gets or sets the name of the constraint. + /// + public string ConstraintName { get; set; } +} diff --git a/src/DapperMatic/Models/DxConstraintType.cs b/src/MJCZone.DapperMatic/Models/DmConstraintType.cs similarity index 84% rename from src/DapperMatic/Models/DxConstraintType.cs rename to src/MJCZone.DapperMatic/Models/DmConstraintType.cs index 99971f2..21f4a38 100644 --- a/src/DapperMatic/Models/DxConstraintType.cs +++ b/src/MJCZone.DapperMatic/Models/DmConstraintType.cs @@ -1,33 +1,33 @@ -namespace DapperMatic.Models; - -/// -/// Specifies the type of a database constraint. -/// -[Serializable] -public enum DxConstraintType -{ - /// - /// Represents a primary key constraint. - /// - PrimaryKey, - - /// - /// Represents a foreign key constraint. - /// - ForeignKey, - - /// - /// Represents a unique constraint. - /// - Unique, - - /// - /// Represents a check constraint. - /// - Check, - - /// - /// Represents a default constraint. - /// - Default, -} +namespace MJCZone.DapperMatic.Models; + +/// +/// Specifies the type of a database constraint. +/// +[Serializable] +public enum DmConstraintType +{ + /// + /// Represents a primary key constraint. + /// + PrimaryKey, + + /// + /// Represents a foreign key constraint. + /// + ForeignKey, + + /// + /// Represents a unique constraint. + /// + Unique, + + /// + /// Represents a check constraint. + /// + Check, + + /// + /// Represents a default constraint. + /// + Default, +} diff --git a/src/DapperMatic/Models/DxDefaultConstraint.cs b/src/MJCZone.DapperMatic/Models/DmDefaultConstraint.cs similarity index 83% rename from src/DapperMatic/Models/DxDefaultConstraint.cs rename to src/MJCZone.DapperMatic/Models/DmDefaultConstraint.cs index 4428888..13b8bb1 100644 --- a/src/DapperMatic/Models/DxDefaultConstraint.cs +++ b/src/MJCZone.DapperMatic/Models/DmDefaultConstraint.cs @@ -1,81 +1,81 @@ -using System.Diagnostics.CodeAnalysis; - -namespace DapperMatic.Models; - -/// -/// Represents a default constraint on a table. -/// -[Serializable] -public class DxDefaultConstraint : DxConstraint -{ - /// - /// Initializes a new instance of the class. - /// Used for deserialization. - /// - public DxDefaultConstraint() - : base(string.Empty) { } - - /// - /// Initializes a new instance of the class. - /// - /// The schema name. - /// The table name. - /// The column name. - /// The constraint name. - /// The expression. - [SetsRequiredMembers] - public DxDefaultConstraint( - string? schemaName, - string tableName, - string columnName, - string constraintName, - string expression - ) - : base(constraintName) - { - SchemaName = schemaName; - TableName = string.IsNullOrWhiteSpace(tableName) - ? throw new ArgumentException("Table name is required") - : tableName; - ColumnName = string.IsNullOrWhiteSpace(columnName) - ? throw new ArgumentException("Column name is required") - : columnName; - Expression = string.IsNullOrWhiteSpace(expression) - ? throw new ArgumentException("Expression is required") - : expression; - } - - /// - /// Gets or sets the schema name. - /// - public string? SchemaName { get; set; } - - /// - /// Gets the table name. - /// - public required string TableName { get; init; } - - /// - /// Gets the column name. - /// - public required string ColumnName { get; init; } - - /// - /// Gets the expression. - /// - public required string Expression { get; init; } - - /// - /// Gets the constraint type. - /// - public override DxConstraintType ConstraintType => DxConstraintType.Default; - - /// - /// Returns a string representation of the constraint. - /// - /// A string representation of the constraint. - public override string ToString() - { - return $"{ConstraintType} Constraint on {TableName}.{ColumnName} with expression: {Expression}"; - } -} +using System.Diagnostics.CodeAnalysis; + +namespace MJCZone.DapperMatic.Models; + +/// +/// Represents a default constraint on a table. +/// +[Serializable] +public class DmDefaultConstraint : DmConstraint +{ + /// + /// Initializes a new instance of the class. + /// Used for deserialization. + /// + public DmDefaultConstraint() + : base(string.Empty) { } + + /// + /// Initializes a new instance of the class. + /// + /// The schema name. + /// The table name. + /// The column name. + /// The constraint name. + /// The expression. + [SetsRequiredMembers] + public DmDefaultConstraint( + string? schemaName, + string tableName, + string columnName, + string constraintName, + string expression + ) + : base(constraintName) + { + SchemaName = schemaName; + TableName = string.IsNullOrWhiteSpace(tableName) + ? throw new ArgumentException("Table name is required") + : tableName; + ColumnName = string.IsNullOrWhiteSpace(columnName) + ? throw new ArgumentException("Column name is required") + : columnName; + Expression = string.IsNullOrWhiteSpace(expression) + ? throw new ArgumentException("Expression is required") + : expression; + } + + /// + /// Gets or sets the schema name. + /// + public string? SchemaName { get; set; } + + /// + /// Gets the table name. + /// + public required string TableName { get; init; } + + /// + /// Gets the column name. + /// + public required string ColumnName { get; init; } + + /// + /// Gets the expression. + /// + public required string Expression { get; init; } + + /// + /// Gets the constraint type. + /// + public override DmConstraintType ConstraintType => DmConstraintType.Default; + + /// + /// Returns a string representation of the constraint. + /// + /// A string representation of the constraint. + public override string ToString() + { + return $"{ConstraintType} Constraint on {TableName}.{ColumnName} with expression: {Expression}"; + } +} diff --git a/src/DapperMatic/Models/DxForeignKeyAction.cs b/src/MJCZone.DapperMatic/Models/DmForeignKeyAction.cs similarity index 56% rename from src/DapperMatic/Models/DxForeignKeyAction.cs rename to src/MJCZone.DapperMatic/Models/DmForeignKeyAction.cs index bdb0371..4f46a05 100644 --- a/src/DapperMatic/Models/DxForeignKeyAction.cs +++ b/src/MJCZone.DapperMatic/Models/DmForeignKeyAction.cs @@ -1,68 +1,68 @@ -namespace DapperMatic.Models; - -/// -/// Specifies the action to take on a foreign key constraint. -/// -[Serializable] -public enum DxForeignKeyAction -{ - /// - /// No action will be taken. - /// - NoAction, - - /// - /// Delete or update the row from the parent table and automatically delete or update the matching rows in the child table. - /// - Cascade, - - /// - /// Reject the delete or update operation for the parent table. - /// - Restrict, - - /// - /// Set the foreign key column or columns in the child table to NULL. - /// - SetNull, -} - -/// -/// Provides extension methods for . -/// -public static class DxForeignKeyActionExtensions -{ - /// - /// Converts the foreign key action to its SQL representation. - /// - /// The foreign key action. - /// The SQL representation of the foreign key action. - public static string ToSql(this DxForeignKeyAction foreignKeyAction) - { - return foreignKeyAction switch - { - DxForeignKeyAction.NoAction => "NO ACTION", - DxForeignKeyAction.Cascade => "CASCADE", - DxForeignKeyAction.Restrict => "RESTRICT", - DxForeignKeyAction.SetNull => "SET NULL", - _ => "NO ACTION" - }; - } - - /// - /// Converts a string to its corresponding . - /// - /// The string representation of the foreign key action. - /// The corresponding . - public static DxForeignKeyAction ToForeignKeyAction(this string behavior) - { - return behavior.ToAlpha().ToUpperInvariant() switch - { - "NOACTION" => DxForeignKeyAction.NoAction, - "CASCADE" => DxForeignKeyAction.Cascade, - "RESTRICT" => DxForeignKeyAction.Restrict, - "SETNULL" => DxForeignKeyAction.SetNull, - _ => DxForeignKeyAction.NoAction - }; - } -} +namespace MJCZone.DapperMatic.Models; + +/// +/// Specifies the action to take on a foreign key constraint. +/// +[Serializable] +public enum DmForeignKeyAction +{ + /// + /// No action will be taken. + /// + NoAction, + + /// + /// Delete or update the row from the parent table and automatically delete or update the matching rows in the child table. + /// + Cascade, + + /// + /// Reject the delete or update operation for the parent table. + /// + Restrict, + + /// + /// Set the foreign key column or columns in the child table to NULL. + /// + SetNull, +} + +/// +/// Provides extension methods for . +/// +public static class DmForeignKeyActionExtensions +{ + /// + /// Converts the foreign key action to its SQL representation. + /// + /// The foreign key action. + /// The SQL representation of the foreign key action. + public static string ToSql(this DmForeignKeyAction foreignKeyAction) + { + return foreignKeyAction switch + { + DmForeignKeyAction.NoAction => "NO ACTION", + DmForeignKeyAction.Cascade => "CASCADE", + DmForeignKeyAction.Restrict => "RESTRICT", + DmForeignKeyAction.SetNull => "SET NULL", + _ => "NO ACTION" + }; + } + + /// + /// Converts a string to its corresponding . + /// + /// The string representation of the foreign key action. + /// The corresponding . + public static DmForeignKeyAction ToForeignKeyAction(this string behavior) + { + return behavior.ToAlpha().ToUpperInvariant() switch + { + "NOACTION" => DmForeignKeyAction.NoAction, + "CASCADE" => DmForeignKeyAction.Cascade, + "RESTRICT" => DmForeignKeyAction.Restrict, + "SETNULL" => DmForeignKeyAction.SetNull, + _ => DmForeignKeyAction.NoAction + }; + } +} diff --git a/src/DapperMatic/Models/DxForeignKeyConstraint.cs b/src/MJCZone.DapperMatic/Models/DmForeignKeyConstraint.cs similarity index 70% rename from src/DapperMatic/Models/DxForeignKeyConstraint.cs rename to src/MJCZone.DapperMatic/Models/DmForeignKeyConstraint.cs index d4be831..c6a8663 100644 --- a/src/DapperMatic/Models/DxForeignKeyConstraint.cs +++ b/src/MJCZone.DapperMatic/Models/DmForeignKeyConstraint.cs @@ -1,45 +1,45 @@ using System.Diagnostics.CodeAnalysis; -namespace DapperMatic.Models; +namespace MJCZone.DapperMatic.Models; /// /// Represents a foreign key constraint in a database. /// [Serializable] -public class DxForeignKeyConstraint : DxConstraint +public class DmForeignKeyConstraint : DmConstraint { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Used for deserialization. /// - public DxForeignKeyConstraint() + public DmForeignKeyConstraint() : base(string.Empty) { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The name of the schema containing the table with the foreign key constraint. Can be null if not specified, indicating the default schema. /// The name of the table that contains the foreign key constraint. /// The desired name for the new foreign key constraint. - /// An array of DxOrderedColumn objects representing the columns in the source table that are part of the foreign key. + /// An array of DmOrderedColumn objects representing the columns in the source table that are part of the foreign key. /// The name of the table that is referenced by the foreign key constraint. - /// An array of DxOrderedColumn objects representing the columns in the referenced table that correspond to the source columns. + /// An array of DmOrderedColumn objects representing the columns in the referenced table that correspond to the source columns. /// - /// The action to take when a row in the referenced table is deleted. Defaults to . + /// The action to take when a row in the referenced table is deleted. Defaults to . /// /// - /// The action to take when a row in the referenced table is updated. Defaults to . + /// The action to take when a row in the referenced table is updated. Defaults to . /// [SetsRequiredMembers] - public DxForeignKeyConstraint( + public DmForeignKeyConstraint( string? schemaName, string tableName, string constraintName, - DxOrderedColumn[] sourceColumns, + DmOrderedColumn[] sourceColumns, string referencedTableName, - DxOrderedColumn[] referencedColumns, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction + DmOrderedColumn[] referencedColumns, + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction ) : base(constraintName) { @@ -72,7 +72,7 @@ public DxForeignKeyConstraint( /// /// Gets or sets the source columns. /// - public required List SourceColumns { get; set; } = []; + public required List SourceColumns { get; set; } = []; /// /// Gets or sets the referenced table name. @@ -82,20 +82,20 @@ public DxForeignKeyConstraint( /// /// Gets or sets the referenced columns. /// - public required List ReferencedColumns { get; set; } = []; + public required List ReferencedColumns { get; set; } = []; /// /// Gets or sets the action on delete. /// - public DxForeignKeyAction OnDelete { get; set; } = DxForeignKeyAction.NoAction; + public DmForeignKeyAction OnDelete { get; set; } = DmForeignKeyAction.NoAction; /// /// Gets or sets the action on update. /// - public DxForeignKeyAction OnUpdate { get; set; } = DxForeignKeyAction.NoAction; + public DmForeignKeyAction OnUpdate { get; set; } = DmForeignKeyAction.NoAction; /// /// Gets the constraint type. /// - public override DxConstraintType ConstraintType => DxConstraintType.ForeignKey; + public override DmConstraintType ConstraintType => DmConstraintType.ForeignKey; } diff --git a/src/DapperMatic/Models/DxIndex.cs b/src/MJCZone.DapperMatic/Models/DmIndex.cs similarity index 78% rename from src/DapperMatic/Models/DxIndex.cs rename to src/MJCZone.DapperMatic/Models/DmIndex.cs index cce2cda..a07697f 100644 --- a/src/DapperMatic/Models/DxIndex.cs +++ b/src/MJCZone.DapperMatic/Models/DmIndex.cs @@ -1,21 +1,21 @@ using System.Diagnostics.CodeAnalysis; -namespace DapperMatic.Models; +namespace MJCZone.DapperMatic.Models; /// /// Represents an index on a table. /// [Serializable] -public class DxIndex +public class DmIndex { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Used for deserialization. /// - public DxIndex() { } + public DmIndex() { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The schema name. /// The table name. @@ -23,11 +23,11 @@ public DxIndex() { } /// The columns in the index. /// Indicates whether the index is unique. [SetsRequiredMembers] - public DxIndex( + public DmIndex( string? schemaName, string tableName, string indexName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, bool isUnique = false ) { @@ -56,7 +56,7 @@ public DxIndex( /// /// Gets or sets the columns. /// - public required List Columns { get; set; } = []; + public required List Columns { get; set; } = []; /// /// Gets or sets a value indicating whether the index is unique. diff --git a/src/DapperMatic/Models/DxOrderedColumn.cs b/src/MJCZone.DapperMatic/Models/DmOrderedColumn.cs similarity index 72% rename from src/DapperMatic/Models/DxOrderedColumn.cs rename to src/MJCZone.DapperMatic/Models/DmOrderedColumn.cs index 9fe69e8..63b08e3 100644 --- a/src/DapperMatic/Models/DxOrderedColumn.cs +++ b/src/MJCZone.DapperMatic/Models/DmOrderedColumn.cs @@ -1,52 +1,52 @@ -using System.Diagnostics.CodeAnalysis; - -namespace DapperMatic.Models; - -/// -/// Represents a column in an ordered list of columns. -/// -[Serializable] -public class DxOrderedColumn -{ - /// - /// Initializes a new instance of the class. - /// Used for deserialization. - /// - public DxOrderedColumn() { } - - /// - /// Initializes a new instance of the class. - /// - /// Name of the column. - /// Order of the column. - [SetsRequiredMembers] - public DxOrderedColumn(string columnName, DxColumnOrder order = DxColumnOrder.Ascending) - { - ColumnName = columnName; - Order = order; - } - - /// - /// Gets or sets the name of the column. - /// - public required string ColumnName { get; set; } - - /// - /// Gets or sets the order of the column. - /// - public required DxColumnOrder Order { get; set; } - - /// - /// Returns a string that represents the current object. - /// - /// A string that represents the current object. - public override string ToString() => ToString(true); - - /// - /// Returns a string that represents the current object. - /// - /// if set to true includes the order in the string. - /// A string that represents the current object. - public string ToString(bool includeOrder) => - $"{ColumnName}{(includeOrder ? Order == DxColumnOrder.Descending ? " DESC" : string.Empty : string.Empty)}"; -} +using System.Diagnostics.CodeAnalysis; + +namespace MJCZone.DapperMatic.Models; + +/// +/// Represents a column in an ordered list of columns. +/// +[Serializable] +public class DmOrderedColumn +{ + /// + /// Initializes a new instance of the class. + /// Used for deserialization. + /// + public DmOrderedColumn() { } + + /// + /// Initializes a new instance of the class. + /// + /// Name of the column. + /// Order of the column. + [SetsRequiredMembers] + public DmOrderedColumn(string columnName, DmColumnOrder order = DmColumnOrder.Ascending) + { + ColumnName = columnName; + Order = order; + } + + /// + /// Gets or sets the name of the column. + /// + public required string ColumnName { get; set; } + + /// + /// Gets or sets the order of the column. + /// + public required DmColumnOrder Order { get; set; } + + /// + /// Returns a string that represents the current object. + /// + /// A string that represents the current object. + public override string ToString() => ToString(true); + + /// + /// Returns a string that represents the current object. + /// + /// if set to true includes the order in the string. + /// A string that represents the current object. + public string ToString(bool includeOrder) => + $"{ColumnName}{(includeOrder ? Order == DmColumnOrder.Descending ? " DESC" : string.Empty : string.Empty)}"; +} diff --git a/src/DapperMatic/Models/DxPrimaryKeyConstraint.cs b/src/MJCZone.DapperMatic/Models/DmPrimaryKeyConstraint.cs similarity index 71% rename from src/DapperMatic/Models/DxPrimaryKeyConstraint.cs rename to src/MJCZone.DapperMatic/Models/DmPrimaryKeyConstraint.cs index d4f9b5d..df5f7b6 100644 --- a/src/DapperMatic/Models/DxPrimaryKeyConstraint.cs +++ b/src/MJCZone.DapperMatic/Models/DmPrimaryKeyConstraint.cs @@ -1,33 +1,33 @@ using System.Diagnostics.CodeAnalysis; -namespace DapperMatic.Models; +namespace MJCZone.DapperMatic.Models; /// /// Represents a primary key constraint on a table. /// [Serializable] -public class DxPrimaryKeyConstraint : DxConstraint +public class DmPrimaryKeyConstraint : DmConstraint { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Used for deserialization. /// - public DxPrimaryKeyConstraint() + public DmPrimaryKeyConstraint() : base(string.Empty) { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The schema name. /// The table name. /// The constraint name. /// The columns that make up the primary key. [SetsRequiredMembers] - public DxPrimaryKeyConstraint( + public DmPrimaryKeyConstraint( string? schemaName, string tableName, string constraintName, - DxOrderedColumn[] columns + DmOrderedColumn[] columns ) : base(constraintName) { @@ -49,10 +49,10 @@ DxOrderedColumn[] columns /// /// Gets or sets the columns. /// - public required List Columns { get; set; } = []; + public required List Columns { get; set; } = []; /// /// Gets the type of the constraint. /// - public override DxConstraintType ConstraintType => DxConstraintType.PrimaryKey; + public override DmConstraintType ConstraintType => DmConstraintType.PrimaryKey; } diff --git a/src/DapperMatic/Models/DxTable.cs b/src/MJCZone.DapperMatic/Models/DmTable.cs similarity index 70% rename from src/DapperMatic/Models/DxTable.cs rename to src/MJCZone.DapperMatic/Models/DmTable.cs index e576820..411569a 100644 --- a/src/DapperMatic/Models/DxTable.cs +++ b/src/MJCZone.DapperMatic/Models/DmTable.cs @@ -1,97 +1,97 @@ -using System.Diagnostics.CodeAnalysis; - -namespace DapperMatic.Models; - -/// -/// Represents a table in a database. -/// -[Serializable] -public class DxTable -{ - /// - /// Initializes a new instance of the class. - /// Used for deserialization. - /// - public DxTable() { } - - /// - /// Initializes a new instance of the class. - /// - /// The schema name of the table. - /// The name of the table. - /// The columns of the table. - /// The primary key constraint of the table. - /// The check constraints of the table. - /// The default constraints of the table. - /// The unique constraints of the table. - /// The foreign key constraints of the table. - /// The indexes of the table. - [SetsRequiredMembers] - public DxTable( - string? schemaName, - string tableName, - DxColumn[]? columns = null, - DxPrimaryKeyConstraint? primaryKey = null, - DxCheckConstraint[]? checkConstraints = null, - DxDefaultConstraint[]? defaultConstraints = null, - DxUniqueConstraint[]? uniqueConstraints = null, - DxForeignKeyConstraint[]? foreignKeyConstraints = null, - DxIndex[]? indexes = null - ) - { - SchemaName = schemaName; - TableName = tableName; - Columns = columns == null ? [] : [.. columns]; - PrimaryKeyConstraint = primaryKey; - CheckConstraints = checkConstraints == null ? [] : [.. checkConstraints]; - DefaultConstraints = defaultConstraints == null ? [] : [.. defaultConstraints]; - UniqueConstraints = uniqueConstraints == null ? [] : [.. uniqueConstraints]; - ForeignKeyConstraints = foreignKeyConstraints == null ? [] : [.. foreignKeyConstraints]; - Indexes = indexes == null ? [] : [.. indexes]; - } - - /// - /// Gets or sets the schema name of the table. - /// - public string? SchemaName { get; set; } - - /// - /// Gets or sets the name of the table. - /// - public required string TableName { get; set; } - - /// - /// Gets or sets the columns of the table. - /// - public List Columns { get; set; } = []; - - /// - /// Gets or sets the primary key constraint of the table. - /// - public DxPrimaryKeyConstraint? PrimaryKeyConstraint { get; set; } - - /// - /// Gets or sets the check constraints of the table. - /// - public List CheckConstraints { get; set; } = []; - - /// - /// Gets or sets the default constraints of the table. - /// - public List DefaultConstraints { get; set; } = []; - - /// - /// Gets or sets the unique constraints of the table. - /// - public List UniqueConstraints { get; set; } = []; - - /// - /// Gets or sets the foreign key constraints of the table. - /// - public List ForeignKeyConstraints { get; set; } = []; - - /// - /// Gets or sets the indexes of the table. - /// - public List Indexes { get; set; } = []; -} +using System.Diagnostics.CodeAnalysis; + +namespace MJCZone.DapperMatic.Models; + +/// +/// Represents a table in a database. +/// +[Serializable] +public class DmTable +{ + /// + /// Initializes a new instance of the class. + /// Used for deserialization. + /// + public DmTable() { } + + /// + /// Initializes a new instance of the class. + /// + /// The schema name of the table. + /// The name of the table. + /// The columns of the table. + /// The primary key constraint of the table. + /// The check constraints of the table. + /// The default constraints of the table. + /// The unique constraints of the table. + /// The foreign key constraints of the table. + /// The indexes of the table. + [SetsRequiredMembers] + public DmTable( + string? schemaName, + string tableName, + DmColumn[]? columns = null, + DmPrimaryKeyConstraint? primaryKey = null, + DmCheckConstraint[]? checkConstraints = null, + DmDefaultConstraint[]? defaultConstraints = null, + DmUniqueConstraint[]? uniqueConstraints = null, + DmForeignKeyConstraint[]? foreignKeyConstraints = null, + DmIndex[]? indexes = null + ) + { + SchemaName = schemaName; + TableName = tableName; + Columns = columns == null ? [] : [.. columns]; + PrimaryKeyConstraint = primaryKey; + CheckConstraints = checkConstraints == null ? [] : [.. checkConstraints]; + DefaultConstraints = defaultConstraints == null ? [] : [.. defaultConstraints]; + UniqueConstraints = uniqueConstraints == null ? [] : [.. uniqueConstraints]; + ForeignKeyConstraints = foreignKeyConstraints == null ? [] : [.. foreignKeyConstraints]; + Indexes = indexes == null ? [] : [.. indexes]; + } + + /// + /// Gets or sets the schema name of the table. + /// + public string? SchemaName { get; set; } + + /// + /// Gets or sets the name of the table. + /// + public required string TableName { get; set; } + + /// + /// Gets or sets the columns of the table. + /// + public List Columns { get; set; } = []; + + /// + /// Gets or sets the primary key constraint of the table. + /// + public DmPrimaryKeyConstraint? PrimaryKeyConstraint { get; set; } + + /// + /// Gets or sets the check constraints of the table. + /// + public List CheckConstraints { get; set; } = []; + + /// + /// Gets or sets the default constraints of the table. + /// + public List DefaultConstraints { get; set; } = []; + + /// + /// Gets or sets the unique constraints of the table. + /// + public List UniqueConstraints { get; set; } = []; + + /// + /// Gets or sets the foreign key constraints of the table. + /// + public List ForeignKeyConstraints { get; set; } = []; + + /// + /// Gets or sets the indexes of the table. + /// + public List Indexes { get; set; } = []; +} diff --git a/src/DapperMatic/Models/DxTableFactory.cs b/src/MJCZone.DapperMatic/Models/DmTableFactory.cs similarity index 83% rename from src/DapperMatic/Models/DxTableFactory.cs rename to src/MJCZone.DapperMatic/Models/DmTableFactory.cs index 2c7f1c9..b913358 100644 --- a/src/DapperMatic/Models/DxTableFactory.cs +++ b/src/MJCZone.DapperMatic/Models/DmTableFactory.cs @@ -1,51 +1,51 @@ using System.Collections.Concurrent; using System.Data; using System.Reflection; -using DapperMatic.DataAnnotations; -using DapperMatic.Providers; +using MJCZone.DapperMatic.DataAnnotations; +using MJCZone.DapperMatic.Providers; -namespace DapperMatic.Models; +namespace MJCZone.DapperMatic.Models; /// -/// Factory for creating DxTable instances for types. +/// Factory for creating DmTable instances for types. /// -public static class DxTableFactory +public static class DmTableFactory { - private static readonly ConcurrentDictionary _cache = new(); + private static readonly ConcurrentDictionary _cache = new(); private static readonly ConcurrentDictionary< Type, - Dictionary + Dictionary > _propertyCache = new(); - private static Action? _customMappingAction; + private static Action? _customMappingAction; /// - /// Configure ahead of time any custom configuration for mapping types to DxTable instances. Call this - /// before the application attempts to map types to DxTable instances, as the mappings are cached once generated + /// Configure ahead of time any custom configuration for mapping types to DmTable instances. Call this + /// before the application attempts to map types to DmTable instances, as the mappings are cached once generated /// the very first time. /// - /// A delegate that receives the Type that is currently being mapped to a DxTable, and an initial DxTable that represents the default mapping before any customizations are applied. The delegate will run when the GetTable method is run for the first time each particular type. - public static void Configure(Action configure) + /// A delegate that receives the Type that is currently being mapped to a DmTable, and an initial DmTable that represents the default mapping before any customizations are applied. The delegate will run when the GetTable method is run for the first time each particular type. + public static void Configure(Action configure) { _customMappingAction = configure; } /// - /// Configure a specific type to your liking. This method can be used to customize the behavior of DxTable generation. + /// Configure a specific type to your liking. This method can be used to customize the behavior of DmTable generation. /// - /// A delegate that receives an initial DxTable that represents the default mapping before any customizations are applied. The type mapping is created immediately and the delegate is run immediately as well. - /// Type that should be mapped to a DxTable instance. - public static void Configure(Action configure) + /// A delegate that receives an initial DmTable that represents the default mapping before any customizations are applied. The type mapping is created immediately and the delegate is run immediately as well. + /// Type that should be mapped to a DmTable instance. + public static void Configure(Action configure) { Configure(typeof(T), configure); } /// - /// Configure a specific type to your liking. This method can be used to customize the behavior of DxTable generation. + /// Configure a specific type to your liking. This method can be used to customize the behavior of DmTable generation. /// - /// Type that should be mapped to a DxTable instance. - /// A delegate that receives an initial DxTable that represents the default mapping before any customizations are applied. The type mapping is created immediately and the delegate is run immediately as well. - public static void Configure(Type type, Action configure) + /// Type that should be mapped to a DmTable instance. + /// A delegate that receives an initial DmTable that represents the default mapping before any customizations are applied. The type mapping is created immediately and the delegate is run immediately as well. + public static void Configure(Type type, Action configure) { var table = GetTable(type); configure(table); @@ -53,12 +53,12 @@ public static void Configure(Type type, Action configure) } /// - /// Returns an instance of a DxTable for the given type. If the type is not a valid DxTable, - /// denoted by the use of a DxTableAAttribute on the class, this method returns null. + /// Returns an instance of a DmTable for the given type. If the type is not a valid DmTable, + /// denoted by the use of a DmTableAAttribute on the class, this method returns null. /// - /// The type to map to a DxTable instance. - /// A DxTable instance representing the type. - public static DxTable GetTable(Type type) + /// The type to map to a DmTable instance. + /// A DmTable instance representing the type. + public static DmTable GetTable(Type type) { ArgumentNullException.ThrowIfNull(type, nameof(type)); @@ -67,7 +67,7 @@ public static DxTable GetTable(Type type) return table; } - var propertyNameToColumnMap = new Dictionary(); + var propertyNameToColumnMap = new Dictionary(); table = GetTableInternal(type, propertyNameToColumnMap); _customMappingAction?.Invoke(type, table); @@ -78,27 +78,27 @@ public static DxTable GetTable(Type type) } /// - /// Generates a DxTable instance for the given type, including all column mappings and constraints. + /// Generates a DmTable instance for the given type, including all column mappings and constraints. /// - /// The type to map to a DxTable instance. + /// The type to map to a DmTable instance. /// A dictionary to store property to column mappings. - /// A DxTable instance representing the type. - private static DxTable GetTableInternal( + /// A DmTable instance representing the type. + private static DmTable GetTableInternal( Type type, - Dictionary propertyMappings + Dictionary propertyMappings ) { var classAttributes = type.GetCustomAttributes().ToArray(); var tableAttribute = - type.GetCustomAttribute() ?? new DxTableAttribute(null, type.Name); + type.GetCustomAttribute() ?? new DmTableAttribute(null, type.Name); var schemaName = classAttributes .Select(ca => { var paType = ca.GetType(); - if (ca is DxTableAttribute dca && !string.IsNullOrWhiteSpace(dca.SchemaName)) + if (ca is DmTableAttribute dca && !string.IsNullOrWhiteSpace(dca.SchemaName)) { return dca.SchemaName; } @@ -130,7 +130,7 @@ ca is System.ComponentModel.DataAnnotations.Schema.TableAttribute ta .Select(ca => { var paType = ca.GetType(); - if (ca is DxTableAttribute dca && !string.IsNullOrWhiteSpace(dca.TableName)) + if (ca is DmTableAttribute dca && !string.IsNullOrWhiteSpace(dca.TableName)) { return dca.TableName; } @@ -161,13 +161,13 @@ ca is System.ComponentModel.DataAnnotations.Schema.TableAttribute ta var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanRead && p.CanWrite); - DxPrimaryKeyConstraint? primaryKey = null; - var columns = new List(); - var checkConstraints = new List(); - var defaultConstraints = new List(); - var uniqueConstraints = new List(); - var foreignKeyConstraints = new List(); - var indexes = new List(); + DmPrimaryKeyConstraint? primaryKey = null; + var columns = new List(); + var checkConstraints = new List(); + var defaultConstraints = new List(); + var uniqueConstraints = new List(); + var foreignKeyConstraints = new List(); + var indexes = new List(); foreach (var property in properties) { @@ -176,7 +176,7 @@ ca is System.ComponentModel.DataAnnotations.Schema.TableAttribute ta var hasIgnoreAttribute = propertyAttributes.Any(pa => { var paType = pa.GetType(); - return pa is DxIgnoreAttribute + return pa is DmIgnoreAttribute // EF Core || pa is System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute // ServiceStack.OrmLite @@ -188,13 +188,13 @@ ca is System.ComponentModel.DataAnnotations.Schema.TableAttribute ta continue; } - var columnAttribute = property.GetCustomAttribute(); + var columnAttribute = property.GetCustomAttribute(); var columnName = propertyAttributes .Select(pa => { var paType = pa.GetType(); - if (pa is DxColumnAttribute dca) + if (pa is DmColumnAttribute dca) { return dca.ColumnName; } @@ -223,7 +223,7 @@ ca is System.ComponentModel.DataAnnotations.Schema.TableAttribute ta || propertyAttributes.Any(pa => { var paType = pa.GetType(); - return pa is DxPrimaryKeyConstraintAttribute + return pa is DmPrimaryKeyConstraintAttribute // EF Core || pa is System.ComponentModel.DataAnnotations.KeyAttribute // ServiceStack.OrmLite @@ -285,7 +285,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute } } - var column = new DxColumn( + var column = new DmColumn( schemaName, tableName, columnName, @@ -339,13 +339,13 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute // set primary key if present var columnPrimaryKeyAttribute = - property.GetCustomAttribute(); + property.GetCustomAttribute(); if (columnPrimaryKeyAttribute != null) { column.IsPrimaryKey = true; if (primaryKey == null) { - primaryKey = new DxPrimaryKeyConstraint( + primaryKey = new DmPrimaryKeyConstraint( schemaName, tableName, !string.IsNullOrWhiteSpace(columnPrimaryKeyAttribute.ConstraintName) @@ -358,7 +358,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute { primaryKey.Columns = [ - .. new List(primaryKey.Columns) { new(columnName) } + .. new List(primaryKey.Columns) { new(columnName) } ]; if (!string.IsNullOrWhiteSpace(columnPrimaryKeyAttribute.ConstraintName)) { @@ -371,7 +371,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute column.IsPrimaryKey = true; if (primaryKey == null) { - primaryKey = new DxPrimaryKeyConstraint( + primaryKey = new DmPrimaryKeyConstraint( schemaName, tableName, string.Empty, @@ -382,17 +382,17 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute { primaryKey.Columns = [ - .. new List(primaryKey.Columns) { new(columnName) } + .. new List(primaryKey.Columns) { new(columnName) } ]; } } // set check expression if present var columnCheckConstraintAttribute = - property.GetCustomAttribute(); + property.GetCustomAttribute(); if (columnCheckConstraintAttribute != null) { - var checkConstraint = new DxCheckConstraint( + var checkConstraint = new DmCheckConstraint( schemaName, tableName, columnName, @@ -408,10 +408,10 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute // set default expression if present var columnDefaultConstraintAttribute = - property.GetCustomAttribute(); + property.GetCustomAttribute(); if (columnDefaultConstraintAttribute != null) { - var defaultConstraint = new DxDefaultConstraint( + var defaultConstraint = new DmDefaultConstraint( schemaName, tableName, columnName, @@ -427,10 +427,10 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute // set unique constraint if present var columnUniqueConstraintAttribute = - property.GetCustomAttribute(); + property.GetCustomAttribute(); if (columnUniqueConstraintAttribute != null) { - var uniqueConstraint = new DxUniqueConstraint( + var uniqueConstraint = new DmUniqueConstraint( schemaName, tableName, !string.IsNullOrWhiteSpace(columnUniqueConstraintAttribute.ConstraintName) @@ -444,10 +444,10 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute } // set index if present - var columnIndexAttribute = property.GetCustomAttribute(); + var columnIndexAttribute = property.GetCustomAttribute(); if (columnIndexAttribute != null) { - var index = new DxIndex( + var index = new DmIndex( schemaName, tableName, !string.IsNullOrWhiteSpace(columnIndexAttribute.IndexName) @@ -480,7 +480,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute ) ? n : DbProviderUtils.GenerateIndexName(tableName, columnName); - var index = new DxIndex( + var index = new DmIndex( schemaName, tableName, indexName, @@ -499,7 +499,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute // set foreign key constraint if present var columnForeignKeyConstraintAttribute = - property.GetCustomAttribute(); + property.GetCustomAttribute(); if (columnForeignKeyConstraintAttribute != null) { var referencedTableName = columnForeignKeyConstraintAttribute.ReferencedTableName; @@ -524,15 +524,15 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute referencedTableName, referencedColumnNames[0] ); - var foreignKeyConstraint = new DxForeignKeyConstraint( + var foreignKeyConstraint = new DmForeignKeyConstraint( schemaName, tableName, constraintName, [new(columnName)], referencedTableName, [new(referencedColumnNames[0])], - onDelete ?? DxForeignKeyAction.NoAction, - onUpdate ?? DxForeignKeyAction.NoAction + onDelete ?? DmForeignKeyAction.NoAction, + onUpdate ?? DmForeignKeyAction.NoAction ); foreignKeyConstraints.Add(foreignKeyConstraint); @@ -557,15 +557,15 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute { inversePropertyAttribute?.Property ?? "id", }; - var onDelete = DxForeignKeyAction.NoAction; - var onUpdate = DxForeignKeyAction.NoAction; + var onDelete = DmForeignKeyAction.NoAction; + var onUpdate = DmForeignKeyAction.NoAction; var constraintName = DbProviderUtils.GenerateForeignKeyConstraintName( tableName, columnName, referencedTableName, referencedColumnNames[0] ); - var foreignKeyConstraint = new DxForeignKeyConstraint( + var foreignKeyConstraint = new DmForeignKeyConstraint( schemaName, tableName, constraintName, @@ -596,14 +596,14 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute // TRUST that the developer knows what they are doing and not creating double the amount of attributes then // necessary. Class level attributes get used without questioning. - var cpa = type.GetCustomAttribute(); + var cpa = type.GetCustomAttribute(); if (cpa != null && cpa.Columns != null) { var constraintName = !string.IsNullOrWhiteSpace(cpa.ConstraintName) ? cpa.ConstraintName : string.Empty; - primaryKey = new DxPrimaryKeyConstraint( + primaryKey = new DmPrimaryKeyConstraint( schemaName, tableName, constraintName, @@ -631,7 +631,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute ); } - var ccas = type.GetCustomAttributes(); + var ccas = type.GetCustomAttributes(); var ccaId = 1; foreach (var cca in ccas) { @@ -645,11 +645,11 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute : DbProviderUtils.GenerateCheckConstraintName(tableName, $"{ccaId++}"); checkConstraints.Add( - new DxCheckConstraint(schemaName, tableName, null, constraintName, cca.Expression) + new DmCheckConstraint(schemaName, tableName, null, constraintName, cca.Expression) ); } - var ucas = type.GetCustomAttributes(); + var ucas = type.GetCustomAttributes(); foreach (var uca in ucas) { if (uca.Columns == null) @@ -665,7 +665,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute ); uniqueConstraints.Add( - new DxUniqueConstraint(schemaName, tableName, constraintName, uca.Columns) + new DmUniqueConstraint(schemaName, tableName, constraintName, uca.Columns) ); if (uca.Columns.Length == 1) @@ -683,7 +683,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute } } - var cias = type.GetCustomAttributes(); + var cias = type.GetCustomAttributes(); foreach (var cia in cias) { if (cia.Columns == null) @@ -699,7 +699,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute ); indexes.Add( - new DxIndex(schemaName, tableName, indexName, cia.Columns, isUnique: cia.IsUnique) + new DmIndex(schemaName, tableName, indexName, cia.Columns, isUnique: cia.IsUnique) ); if (cia.Columns.Length == 1) @@ -721,7 +721,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute } } - var cfkas = type.GetCustomAttributes(); + var cfkas = type.GetCustomAttributes(); foreach (var cfk in cfkas) { if ( @@ -745,15 +745,15 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute cfk.ReferencedColumnNames ); - var foreignKeyConstraint = new DxForeignKeyConstraint( + var foreignKeyConstraint = new DmForeignKeyConstraint( schemaName, tableName, constraintName, - [.. cfk.SourceColumnNames.Select(c => new DxOrderedColumn(c))], + [.. cfk.SourceColumnNames.Select(c => new DmOrderedColumn(c))], cfk.ReferencedTableName, - [.. cfk.ReferencedColumnNames.Select(c => new DxOrderedColumn(c))], - cfk.OnDelete ?? DxForeignKeyAction.NoAction, - cfk.OnUpdate ?? DxForeignKeyAction.NoAction + [.. cfk.ReferencedColumnNames.Select(c => new DmOrderedColumn(c))], + cfk.OnDelete ?? DmForeignKeyAction.NoAction, + cfk.OnUpdate ?? DmForeignKeyAction.NoAction ); foreignKeyConstraints.Add(foreignKeyConstraint); @@ -775,7 +775,7 @@ pa is System.ComponentModel.DataAnnotations.RequiredAttribute } } - var table = new DxTable( + var table = new DmTable( schemaName, tableName, [.. columns], diff --git a/src/DapperMatic/Models/DxUniqueConstraint.cs b/src/MJCZone.DapperMatic/Models/DmUniqueConstraint.cs similarity index 71% rename from src/DapperMatic/Models/DxUniqueConstraint.cs rename to src/MJCZone.DapperMatic/Models/DmUniqueConstraint.cs index 820024f..985bddd 100644 --- a/src/DapperMatic/Models/DxUniqueConstraint.cs +++ b/src/MJCZone.DapperMatic/Models/DmUniqueConstraint.cs @@ -1,33 +1,33 @@ using System.Diagnostics.CodeAnalysis; -namespace DapperMatic.Models; +namespace MJCZone.DapperMatic.Models; /// /// Represents a unique constraint on a table. /// [Serializable] -public class DxUniqueConstraint : DxConstraint +public class DmUniqueConstraint : DmConstraint { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// Used for deserialization. /// - public DxUniqueConstraint() + public DmUniqueConstraint() : base(string.Empty) { } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The schema name. /// The table name. /// The constraint name. /// The columns. [SetsRequiredMembers] - public DxUniqueConstraint( + public DmUniqueConstraint( string? schemaName, string tableName, string constraintName, - DxOrderedColumn[] columns + DmOrderedColumn[] columns ) : base(constraintName) { @@ -49,10 +49,10 @@ DxOrderedColumn[] columns /// /// Gets or sets the columns. /// - public required List Columns { get; set; } = []; + public required List Columns { get; set; } = []; /// /// Gets the type of the constraint. /// - public override DxConstraintType ConstraintType => DxConstraintType.Unique; + public override DmConstraintType ConstraintType => DmConstraintType.Unique; } diff --git a/src/DapperMatic/Models/DxView.cs b/src/MJCZone.DapperMatic/Models/DmView.cs similarity index 75% rename from src/DapperMatic/Models/DxView.cs rename to src/MJCZone.DapperMatic/Models/DmView.cs index af25a80..52a6c35 100644 --- a/src/DapperMatic/Models/DxView.cs +++ b/src/MJCZone.DapperMatic/Models/DmView.cs @@ -1,45 +1,45 @@ -using System.Diagnostics.CodeAnalysis; - -namespace DapperMatic.Models; - -/// -/// Represents a view in a database. -/// -[Serializable] -public class DxView -{ - /// - /// Initializes a new instance of the class. - /// Used for deserialization. - /// - public DxView() { } - - /// - /// Initializes a new instance of the class. - /// - /// The schema name of the view. - /// The name of the view. - /// The definition of the view. - [SetsRequiredMembers] - public DxView(string? schemaName, string viewName, string definition) - { - SchemaName = schemaName; - ViewName = viewName; - Definition = definition; - } - - /// - /// Gets or sets the schema name of the view. - /// - public string? SchemaName { get; set; } - - /// - /// Gets or sets the name of the view. - /// - public required string ViewName { get; set; } - - /// - /// Gets or sets the definition of the view. - /// - public required string Definition { get; set; } -} +using System.Diagnostics.CodeAnalysis; + +namespace MJCZone.DapperMatic.Models; + +/// +/// Represents a view in a database. +/// +[Serializable] +public class DmView +{ + /// + /// Initializes a new instance of the class. + /// Used for deserialization. + /// + public DmView() { } + + /// + /// Initializes a new instance of the class. + /// + /// The schema name of the view. + /// The name of the view. + /// The definition of the view. + [SetsRequiredMembers] + public DmView(string? schemaName, string viewName, string definition) + { + SchemaName = schemaName; + ViewName = viewName; + Definition = definition; + } + + /// + /// Gets or sets the schema name of the view. + /// + public string? SchemaName { get; set; } + + /// + /// Gets or sets the name of the view. + /// + public required string ViewName { get; set; } + + /// + /// Gets or sets the definition of the view. + /// + public required string Definition { get; set; } +} diff --git a/src/DapperMatic/Models/DxViewFactory.cs b/src/MJCZone.DapperMatic/Models/DmViewFactory.cs similarity index 62% rename from src/DapperMatic/Models/DxViewFactory.cs rename to src/MJCZone.DapperMatic/Models/DmViewFactory.cs index 4385ce1..46e6e8e 100644 --- a/src/DapperMatic/Models/DxViewFactory.cs +++ b/src/MJCZone.DapperMatic/Models/DmViewFactory.cs @@ -1,34 +1,34 @@ using System.Collections.Concurrent; using System.Reflection; -using DapperMatic.DataAnnotations; +using MJCZone.DapperMatic.DataAnnotations; -namespace DapperMatic.Models; +namespace MJCZone.DapperMatic.Models; /// -/// Factory class for creating and caching instances of . +/// Factory class for creating and caching instances of . /// -public static class DxViewFactory +public static class DmViewFactory { /// - /// Cache for storing created instances. + /// Cache for storing created instances. /// - private static readonly ConcurrentDictionary Cache = new(); + private static readonly ConcurrentDictionary Cache = new(); /// - /// Returns an instance of a for the given type. If the type is not a valid , - /// denoted by the use of a on the class, this method returns null. + /// Returns an instance of a for the given type. If the type is not a valid , + /// denoted by the use of a on the class, this method returns null. /// - /// The type for which to get the . - /// An instance of if the type is valid; otherwise, null. + /// The type for which to get the . + /// An instance of if the type is valid; otherwise, null. /// Thrown when the type is missing a view definition. - public static DxView? GetView(Type type) + public static DmView? GetView(Type type) { if (Cache.TryGetValue(type, out var view)) { return view; } - var viewAttribute = type.GetCustomAttribute(); + var viewAttribute = type.GetCustomAttribute(); if (viewAttribute == null) { return null; @@ -39,7 +39,7 @@ public static class DxViewFactory throw new InvalidOperationException("Type is missing a view definition."); } - view = new DxView( + view = new DmView( string.IsNullOrWhiteSpace(viewAttribute.SchemaName) ? null : viewAttribute.SchemaName, string.IsNullOrWhiteSpace(viewAttribute.ViewName) ? type.Name : viewAttribute.ViewName, viewAttribute.Definition.Trim() diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.CheckConstraints.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.CheckConstraints.cs similarity index 94% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.CheckConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.CheckConstraints.cs index 4628442..e2eab19 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.CheckConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.CheckConstraints.cs @@ -1,492 +1,493 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Providers.Base; - -public abstract partial class DatabaseMethodsBase -{ - /// - /// Checks if a check constraint exists in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the check constraint exists, otherwise false. - public virtual async Task DoesCheckConstraintExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) - { - return false; - } - - return await GetCheckConstraintAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false) != null; - } - - /// - /// Checks if a check constraint exists on a specific column in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the check constraint exists on the column, otherwise false. - public virtual async Task DoesCheckConstraintExistOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) - { - return false; - } - - return await GetCheckConstraintOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false) != null; - } - - /// - /// Creates a check constraint if it does not already exist. - /// - /// The database connection. - /// The check constraint details. - /// The transaction. - /// The cancellation token. - /// True if the check constraint was created, otherwise false. - public virtual async Task CreateCheckConstraintIfNotExistsAsync( - IDbConnection db, - DxCheckConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) - { - return false; - } - - return await CreateCheckConstraintIfNotExistsAsync( - db, - constraint.SchemaName, - constraint.TableName, - constraint.ColumnName, - constraint.ConstraintName, - constraint.Expression, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Creates a check constraint if it does not already exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The constraint name. - /// The check constraint expression. - /// The transaction. - /// The cancellation token. - /// True if the check constraint was created, otherwise false. - public virtual async Task CreateCheckConstraintIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? columnName, - string constraintName, - string expression, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - if (string.IsNullOrWhiteSpace(constraintName)) - { - throw new ArgumentException("Constraint name is required.", nameof(constraintName)); - } - - if (string.IsNullOrWhiteSpace(expression)) - { - throw new ArgumentException("Expression is required.", nameof(expression)); - } - - if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) - { - return false; - } - - if ( - await DoesCheckConstraintExistAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false) - ) - { - return false; - } - - var sql = SqlAlterTableAddCheckConstraint( - schemaName, - tableName, - constraintName, - expression - ); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } - - /// - /// Gets the details of a check constraint. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// The check constraint details, or null if not found. - public virtual async Task GetCheckConstraintAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(constraintName)) - { - throw new ArgumentException("Constraint name is required.", nameof(constraintName)); - } - - var checkConstraints = await GetCheckConstraintsAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - return checkConstraints.SingleOrDefault(); - } - - /// - /// Gets the name of a check constraint on a specific column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The check constraint name, or null if not found. - public virtual async Task GetCheckConstraintNameOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(columnName)) - { - throw new ArgumentException("Column name is required.", nameof(columnName)); - } - - var checkConstraints = await GetCheckConstraintsAsync( - db, - schemaName, - tableName, - null, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - return checkConstraints - .FirstOrDefault(c => - !string.IsNullOrWhiteSpace(c.ColumnName) - && c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) - ) - ?.ConstraintName; - } - - /// - /// Gets the names of all check constraints in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of check constraint names. - public virtual async Task> GetCheckConstraintNamesAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var checkConstraints = await GetCheckConstraintsAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - return checkConstraints.Select(c => c.ConstraintName).ToList(); - } - - /// - /// Gets the details of a check constraint on a specific column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The check constraint details, or null if not found. - public virtual async Task GetCheckConstraintOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(columnName)) - { - throw new ArgumentException("Column name is required.", nameof(columnName)); - } - - var checkConstraints = await GetCheckConstraintsAsync( - db, - schemaName, - tableName, - null, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - return checkConstraints.FirstOrDefault(c => - !string.IsNullOrWhiteSpace(c.ColumnName) - && c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) - ); - } - - /// - /// Gets the details of all check constraints in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of check constraint details. - public virtual async Task> GetCheckConstraintsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) - { - return []; - } - - var table = await GetTableAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - - if (table == null) - { - return []; - } - - var filter = string.IsNullOrWhiteSpace(constraintNameFilter) - ? null - : ToSafeString(constraintNameFilter); - - return string.IsNullOrWhiteSpace(filter) - ? table.CheckConstraints - : table - .CheckConstraints.Where(c => c.ConstraintName.IsWildcardPatternMatch(filter)) - .ToList(); - } - - /// - /// Drops a check constraint on a specific column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the check constraint was dropped, otherwise false. - public virtual async Task DropCheckConstraintOnColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - if (string.IsNullOrWhiteSpace(columnName)) - { - throw new ArgumentException("Column name is required.", nameof(columnName)); - } - - if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) - { - return false; - } - - var constraintName = await GetCheckConstraintNameOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ).ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(constraintName)) - { - return false; - } - - var sql = SqlDropCheckConstraint(schemaName, tableName, constraintName); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } - - /// - /// Drops a check constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the check constraint was dropped, otherwise false. - public virtual async Task DropCheckConstraintIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - if (string.IsNullOrWhiteSpace(constraintName)) - { - throw new ArgumentException("Constraint name is required.", nameof(constraintName)); - } - - if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) - { - return false; - } - - if ( - !await DoesCheckConstraintExistAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false) - ) - { - return false; - } - - var sql = SqlDropCheckConstraint(schemaName, tableName, constraintName); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Providers.Base; + +public abstract partial class DatabaseMethodsBase +{ + /// + /// Checks if a check constraint exists in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the check constraint exists, otherwise false. + public virtual async Task DoesCheckConstraintExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) + { + return false; + } + + return await GetCheckConstraintAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false) != null; + } + + /// + /// Checks if a check constraint exists on a specific column in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the check constraint exists on the column, otherwise false. + public virtual async Task DoesCheckConstraintExistOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) + { + return false; + } + + return await GetCheckConstraintOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false) != null; + } + + /// + /// Creates a check constraint if it does not already exist. + /// + /// The database connection. + /// The check constraint details. + /// The transaction. + /// The cancellation token. + /// True if the check constraint was created, otherwise false. + public virtual async Task CreateCheckConstraintIfNotExistsAsync( + IDbConnection db, + DmCheckConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) + { + return false; + } + + return await CreateCheckConstraintIfNotExistsAsync( + db, + constraint.SchemaName, + constraint.TableName, + constraint.ColumnName, + constraint.ConstraintName, + constraint.Expression, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Creates a check constraint if it does not already exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The constraint name. + /// The check constraint expression. + /// The transaction. + /// The cancellation token. + /// True if the check constraint was created, otherwise false. + public virtual async Task CreateCheckConstraintIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? columnName, + string constraintName, + string expression, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + if (string.IsNullOrWhiteSpace(constraintName)) + { + throw new ArgumentException("Constraint name is required.", nameof(constraintName)); + } + + if (string.IsNullOrWhiteSpace(expression)) + { + throw new ArgumentException("Expression is required.", nameof(expression)); + } + + if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) + { + return false; + } + + if ( + await DoesCheckConstraintExistAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false) + ) + { + return false; + } + + var sql = SqlAlterTableAddCheckConstraint( + schemaName, + tableName, + constraintName, + expression + ); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } + + /// + /// Gets the details of a check constraint. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// The check constraint details, or null if not found. + public virtual async Task GetCheckConstraintAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(constraintName)) + { + throw new ArgumentException("Constraint name is required.", nameof(constraintName)); + } + + var checkConstraints = await GetCheckConstraintsAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + return checkConstraints.SingleOrDefault(); + } + + /// + /// Gets the name of a check constraint on a specific column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The check constraint name, or null if not found. + public virtual async Task GetCheckConstraintNameOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(columnName)) + { + throw new ArgumentException("Column name is required.", nameof(columnName)); + } + + var checkConstraints = await GetCheckConstraintsAsync( + db, + schemaName, + tableName, + null, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + return checkConstraints + .FirstOrDefault(c => + !string.IsNullOrWhiteSpace(c.ColumnName) + && c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) + ) + ?.ConstraintName; + } + + /// + /// Gets the names of all check constraints in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of check constraint names. + public virtual async Task> GetCheckConstraintNamesAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var checkConstraints = await GetCheckConstraintsAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + return checkConstraints.Select(c => c.ConstraintName).ToList(); + } + + /// + /// Gets the details of a check constraint on a specific column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The check constraint details, or null if not found. + public virtual async Task GetCheckConstraintOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(columnName)) + { + throw new ArgumentException("Column name is required.", nameof(columnName)); + } + + var checkConstraints = await GetCheckConstraintsAsync( + db, + schemaName, + tableName, + null, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + return checkConstraints.FirstOrDefault(c => + !string.IsNullOrWhiteSpace(c.ColumnName) + && c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) + ); + } + + /// + /// Gets the details of all check constraints in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of check constraint details. + public virtual async Task> GetCheckConstraintsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) + { + return []; + } + + var table = await GetTableAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + + if (table == null) + { + return []; + } + + var filter = string.IsNullOrWhiteSpace(constraintNameFilter) + ? null + : ToSafeString(constraintNameFilter); + + return string.IsNullOrWhiteSpace(filter) + ? table.CheckConstraints + : table + .CheckConstraints.Where(c => c.ConstraintName.IsWildcardPatternMatch(filter)) + .ToList(); + } + + /// + /// Drops a check constraint on a specific column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the check constraint was dropped, otherwise false. + public virtual async Task DropCheckConstraintOnColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + if (string.IsNullOrWhiteSpace(columnName)) + { + throw new ArgumentException("Column name is required.", nameof(columnName)); + } + + if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) + { + return false; + } + + var constraintName = await GetCheckConstraintNameOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(constraintName)) + { + return false; + } + + var sql = SqlDropCheckConstraint(schemaName, tableName, constraintName); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } + + /// + /// Drops a check constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the check constraint was dropped, otherwise false. + public virtual async Task DropCheckConstraintIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + if (string.IsNullOrWhiteSpace(constraintName)) + { + throw new ArgumentException("Constraint name is required.", nameof(constraintName)); + } + + if (!await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) + { + return false; + } + + if ( + !await DoesCheckConstraintExistAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false) + ) + { + return false; + } + + var sql = SqlDropCheckConstraint(schemaName, tableName, constraintName); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } +} diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Columns.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Columns.cs similarity index 95% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.Columns.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Columns.cs index c98033e..68acba0 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Columns.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Columns.cs @@ -1,551 +1,551 @@ -using System.Data; -using System.Text; -using DapperMatic.Models; - -namespace DapperMatic.Providers.Base; - -public abstract partial class DatabaseMethodsBase -{ - /// - /// Checks if a column exists in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// True if the column exists, otherwise false. - public virtual async Task DoesColumnExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await GetColumnAsync(db, schemaName, tableName, columnName, tx, cancellationToken) - .ConfigureAwait(false) != null; - } - - /// - /// Creates a column if it does not already exist in the specified table. - /// - /// The database connection. - /// The column definition. - /// The database transaction. - /// The cancellation token. - /// True if the column was created, otherwise false. - public virtual async Task CreateColumnIfNotExistsAsync( - IDbConnection db, - DxColumn column, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(column.TableName)) - { - throw new ArgumentException("Table name is required", nameof(column)); - } - - if (string.IsNullOrWhiteSpace(column.ColumnName)) - { - throw new ArgumentException("Column name is required", nameof(column)); - } - - var table = await GetTableAsync( - db, - column.SchemaName, - column.TableName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - if (string.IsNullOrWhiteSpace(table?.TableName)) - { - return false; - } - - if ( - table.Columns.Any(c => - c.ColumnName.Equals(column.ColumnName, StringComparison.OrdinalIgnoreCase) - ) - ) - { - return false; - } - - var dbVersion = await GetDatabaseVersionAsync(db, tx, cancellationToken) - .ConfigureAwait(false); - - var tableConstraints = new DxTable(table.SchemaName, table.TableName); - - // attach the existing primary key constraint if it exists to ensure that it doesn't get recreated - if (table.PrimaryKeyConstraint != null) - { - tableConstraints.PrimaryKeyConstraint = table.PrimaryKeyConstraint; - } - - var columnDefinitionSql = SqlInlineColumnDefinition( - table, - column, - tableConstraints, - dbVersion - ); - - var sql = new StringBuilder(); - sql.Append( - $"ALTER TABLE {GetSchemaQualifiedIdentifierName(column.SchemaName, column.TableName)} ADD {columnDefinitionSql}" - ); - - await ExecuteAsync(db, sql.ToString(), tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - // ONLY add the primary key constraint if it didn't exist before and if it wasn't - // already added as part of the column definition (in which case that tableConstraints.PrimaryKeyConstraint will be null) - // will be null. - if (tableConstraints.PrimaryKeyConstraint != null) - { - await CreatePrimaryKeyConstraintIfNotExistsAsync( - db, - tableConstraints.PrimaryKeyConstraint, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } - - foreach (var checkConstraint in tableConstraints.CheckConstraints) - { - await CreateCheckConstraintIfNotExistsAsync( - db, - checkConstraint, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } - - foreach (var defaultConstraint in tableConstraints.DefaultConstraints) - { - await CreateDefaultConstraintIfNotExistsAsync( - db, - defaultConstraint, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } - - foreach (var uniqueConstraint in tableConstraints.UniqueConstraints) - { - await CreateUniqueConstraintIfNotExistsAsync( - db, - uniqueConstraint, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } - - foreach (var foreignKeyConstraint in tableConstraints.ForeignKeyConstraints) - { - await CreateForeignKeyConstraintIfNotExistsAsync( - db, - foreignKeyConstraint, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } - - foreach (var index in tableConstraints.Indexes) - { - await CreateIndexIfNotExistsAsync( - db, - index, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } - - return true; - } - - /// - /// Creates a column with the specified properties if it does not already exist in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The .NET type of the column. - /// The provider-specific data type. - /// The length of the column. - /// The precision of the column. - /// The scale of the column. - /// The check constraint expression. - /// The default value expression. - /// Indicates if the column is nullable. - /// Indicates if the column is a primary key. - /// Indicates if the column is auto-incremented. - /// Indicates if the column is unique. - /// Indicates if the column is indexed. - /// Indicates if the column is a foreign key. - /// The referenced table name for foreign key. - /// The referenced column name for foreign key. - /// The action on delete for foreign key. - /// The action on update for foreign key. - /// The database transaction. - /// The cancellation token. - /// True if the column was created, otherwise false. - public virtual async Task CreateColumnIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - Type dotnetType, - string? providerDataType = null, - int? length = null, - int? precision = null, - int? scale = null, - string? checkExpression = null, - string? defaultExpression = null, - bool isNullable = true, - bool isPrimaryKey = false, - bool isAutoIncrement = false, - bool isUnique = false, - bool isIndexed = false, - bool isForeignKey = false, - string? referencedTableName = null, - string? referencedColumnName = null, - DxForeignKeyAction? onDelete = null, - DxForeignKeyAction? onUpdate = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await CreateColumnIfNotExistsAsync( - db, - new DxColumn( - schemaName, - tableName, - columnName, - dotnetType, - providerDataType == null - ? null - : new Dictionary - { - { ProviderType, providerDataType }, - }, - length, - precision, - scale, - checkExpression, - defaultExpression, - isNullable, - isPrimaryKey, - isAutoIncrement, - isUnique, - isIndexed, - isForeignKey, - referencedTableName, - referencedColumnName, - onDelete, - onUpdate - ), - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Retrieves a column from the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// The column definition if found, otherwise null. - public virtual async Task GetColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return ( - await GetColumnsAsync(db, schemaName, tableName, columnName, tx, cancellationToken) - .ConfigureAwait(false) - ).FirstOrDefault(); - } - - /// - /// Retrieves the names of columns from the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name filter. - /// The database transaction. - /// The cancellation token. - /// A list of column names. - public virtual async Task> GetColumnNamesAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? columnNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var columns = await GetColumnsAsync( - db, - schemaName, - tableName, - columnNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - return columns.Select(x => x.ColumnName).ToList(); - } - - /// - /// Retrieves columns from the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name filter. - /// The database transaction. - /// The cancellation token. - /// A list of column definitions. - public virtual async Task> GetColumnsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? columnNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - var table = await GetTableAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - - if (table == null) - { - return []; - } - - var filter = string.IsNullOrWhiteSpace(columnNameFilter) - ? null - : ToSafeString(columnNameFilter); - - return string.IsNullOrWhiteSpace(filter) - ? table.Columns - : table.Columns.Where(c => c.ColumnName.IsWildcardPatternMatch(filter)).ToList(); - } - - /// - /// Drops a column if it exists in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The database transaction. - /// The cancellation token. - /// True if the column was dropped, otherwise false. - public virtual async Task DropColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var table = await GetTableAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - - if (table == null) - { - return false; - } - - (schemaName, tableName, columnName) = NormalizeNames(schemaName, tableName, columnName); - - var column = table.Columns.FirstOrDefault(c => - c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) - ); - - if (column == null) - { - return false; - } - - // drop any related constraints - if (column.IsPrimaryKey) - { - await DropPrimaryKeyConstraintIfExistsAsync( - db, - schemaName, - tableName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - if (column.IsForeignKey) - { - await DropForeignKeyConstraintOnColumnIfExistsAsync( - db, - schemaName, - tableName, - column.ColumnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - if (column.IsUnique) - { - await DropUniqueConstraintOnColumnIfExistsAsync( - db, - schemaName, - tableName, - column.ColumnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - if (column.IsIndexed) - { - await DropIndexesOnColumnIfExistsAsync( - db, - schemaName, - tableName, - column.ColumnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - await DropCheckConstraintOnColumnIfExistsAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - await DropDefaultConstraintOnColumnIfExistsAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - var sql = SqlDropColumn(schemaName, tableName, columnName); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } - - /// - /// Renames a column if it exists in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The new column name. - /// The database transaction. - /// The cancellation token. - /// True if the column was renamed, otherwise false. - public virtual async Task RenameColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - string newColumnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if ( - !await DoesColumnExistAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false) - ) - { - return false; - } - - if ( - await DoesColumnExistAsync( - db, - schemaName, - tableName, - newColumnName, - tx, - cancellationToken - ) - .ConfigureAwait(false) - ) - { - return false; - } - - (schemaName, tableName, columnName) = NormalizeNames(schemaName, tableName, columnName); - - var schemaQualifiedTableName = GetSchemaQualifiedIdentifierName(schemaName, tableName); - - // As of version 3.25.0 released September 2018, SQLite supports renaming columns - await ExecuteAsync( - db, - $""" - ALTER TABLE {schemaQualifiedTableName} - RENAME COLUMN {columnName} - TO {newColumnName} - """, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - - return true; - } -} +using System.Data; +using System.Text; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Providers.Base; + +public abstract partial class DatabaseMethodsBase +{ + /// + /// Checks if a column exists in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// True if the column exists, otherwise false. + public virtual async Task DoesColumnExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await GetColumnAsync(db, schemaName, tableName, columnName, tx, cancellationToken) + .ConfigureAwait(false) != null; + } + + /// + /// Creates a column if it does not already exist in the specified table. + /// + /// The database connection. + /// The column definition. + /// The database transaction. + /// The cancellation token. + /// True if the column was created, otherwise false. + public virtual async Task CreateColumnIfNotExistsAsync( + IDbConnection db, + DmColumn column, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(column.TableName)) + { + throw new ArgumentException("Table name is required", nameof(column)); + } + + if (string.IsNullOrWhiteSpace(column.ColumnName)) + { + throw new ArgumentException("Column name is required", nameof(column)); + } + + var table = await GetTableAsync( + db, + column.SchemaName, + column.TableName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + if (string.IsNullOrWhiteSpace(table?.TableName)) + { + return false; + } + + if ( + table.Columns.Any(c => + c.ColumnName.Equals(column.ColumnName, StringComparison.OrdinalIgnoreCase) + ) + ) + { + return false; + } + + var dbVersion = await GetDatabaseVersionAsync(db, tx, cancellationToken) + .ConfigureAwait(false); + + var tableConstraints = new DmTable(table.SchemaName, table.TableName); + + // attach the existing primary key constraint if it exists to ensure that it doesn't get recreated + if (table.PrimaryKeyConstraint != null) + { + tableConstraints.PrimaryKeyConstraint = table.PrimaryKeyConstraint; + } + + var columnDefinitionSql = SqlInlineColumnDefinition( + table, + column, + tableConstraints, + dbVersion + ); + + var sql = new StringBuilder(); + sql.Append( + $"ALTER TABLE {GetSchemaQualifiedIdentifierName(column.SchemaName, column.TableName)} ADD {columnDefinitionSql}" + ); + + await ExecuteAsync(db, sql.ToString(), tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + // ONLY add the primary key constraint if it didn't exist before and if it wasn't + // already added as part of the column definition (in which case that tableConstraints.PrimaryKeyConstraint will be null) + // will be null. + if (tableConstraints.PrimaryKeyConstraint != null) + { + await CreatePrimaryKeyConstraintIfNotExistsAsync( + db, + tableConstraints.PrimaryKeyConstraint, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } + + foreach (var checkConstraint in tableConstraints.CheckConstraints) + { + await CreateCheckConstraintIfNotExistsAsync( + db, + checkConstraint, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } + + foreach (var defaultConstraint in tableConstraints.DefaultConstraints) + { + await CreateDefaultConstraintIfNotExistsAsync( + db, + defaultConstraint, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } + + foreach (var uniqueConstraint in tableConstraints.UniqueConstraints) + { + await CreateUniqueConstraintIfNotExistsAsync( + db, + uniqueConstraint, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } + + foreach (var foreignKeyConstraint in tableConstraints.ForeignKeyConstraints) + { + await CreateForeignKeyConstraintIfNotExistsAsync( + db, + foreignKeyConstraint, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } + + foreach (var index in tableConstraints.Indexes) + { + await CreateIndexIfNotExistsAsync( + db, + index, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } + + return true; + } + + /// + /// Creates a column with the specified properties if it does not already exist in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The .NET type of the column. + /// The provider-specific data type. + /// The length of the column. + /// The precision of the column. + /// The scale of the column. + /// The check constraint expression. + /// The default value expression. + /// Indicates if the column is nullable. + /// Indicates if the column is a primary key. + /// Indicates if the column is auto-incremented. + /// Indicates if the column is unique. + /// Indicates if the column is indexed. + /// Indicates if the column is a foreign key. + /// The referenced table name for foreign key. + /// The referenced column name for foreign key. + /// The action on delete for foreign key. + /// The action on update for foreign key. + /// The database transaction. + /// The cancellation token. + /// True if the column was created, otherwise false. + public virtual async Task CreateColumnIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + Type dotnetType, + string? providerDataType = null, + int? length = null, + int? precision = null, + int? scale = null, + string? checkExpression = null, + string? defaultExpression = null, + bool isNullable = true, + bool isPrimaryKey = false, + bool isAutoIncrement = false, + bool isUnique = false, + bool isIndexed = false, + bool isForeignKey = false, + string? referencedTableName = null, + string? referencedColumnName = null, + DmForeignKeyAction? onDelete = null, + DmForeignKeyAction? onUpdate = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await CreateColumnIfNotExistsAsync( + db, + new DmColumn( + schemaName, + tableName, + columnName, + dotnetType, + providerDataType == null + ? null + : new Dictionary + { + { ProviderType, providerDataType }, + }, + length, + precision, + scale, + checkExpression, + defaultExpression, + isNullable, + isPrimaryKey, + isAutoIncrement, + isUnique, + isIndexed, + isForeignKey, + referencedTableName, + referencedColumnName, + onDelete, + onUpdate + ), + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Retrieves a column from the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// The column definition if found, otherwise null. + public virtual async Task GetColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return ( + await GetColumnsAsync(db, schemaName, tableName, columnName, tx, cancellationToken) + .ConfigureAwait(false) + ).FirstOrDefault(); + } + + /// + /// Retrieves the names of columns from the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name filter. + /// The database transaction. + /// The cancellation token. + /// A list of column names. + public virtual async Task> GetColumnNamesAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? columnNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var columns = await GetColumnsAsync( + db, + schemaName, + tableName, + columnNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + return columns.Select(x => x.ColumnName).ToList(); + } + + /// + /// Retrieves columns from the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name filter. + /// The database transaction. + /// The cancellation token. + /// A list of column definitions. + public virtual async Task> GetColumnsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? columnNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + var table = await GetTableAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + + if (table == null) + { + return []; + } + + var filter = string.IsNullOrWhiteSpace(columnNameFilter) + ? null + : ToSafeString(columnNameFilter); + + return string.IsNullOrWhiteSpace(filter) + ? table.Columns + : table.Columns.Where(c => c.ColumnName.IsWildcardPatternMatch(filter)).ToList(); + } + + /// + /// Drops a column if it exists in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The database transaction. + /// The cancellation token. + /// True if the column was dropped, otherwise false. + public virtual async Task DropColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var table = await GetTableAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + + if (table == null) + { + return false; + } + + (schemaName, tableName, columnName) = NormalizeNames(schemaName, tableName, columnName); + + var column = table.Columns.FirstOrDefault(c => + c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) + ); + + if (column == null) + { + return false; + } + + // drop any related constraints + if (column.IsPrimaryKey) + { + await DropPrimaryKeyConstraintIfExistsAsync( + db, + schemaName, + tableName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + if (column.IsForeignKey) + { + await DropForeignKeyConstraintOnColumnIfExistsAsync( + db, + schemaName, + tableName, + column.ColumnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + if (column.IsUnique) + { + await DropUniqueConstraintOnColumnIfExistsAsync( + db, + schemaName, + tableName, + column.ColumnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + if (column.IsIndexed) + { + await DropIndexesOnColumnIfExistsAsync( + db, + schemaName, + tableName, + column.ColumnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + await DropCheckConstraintOnColumnIfExistsAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + await DropDefaultConstraintOnColumnIfExistsAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + var sql = SqlDropColumn(schemaName, tableName, columnName); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } + + /// + /// Renames a column if it exists in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The new column name. + /// The database transaction. + /// The cancellation token. + /// True if the column was renamed, otherwise false. + public virtual async Task RenameColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + string newColumnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if ( + !await DoesColumnExistAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false) + ) + { + return false; + } + + if ( + await DoesColumnExistAsync( + db, + schemaName, + tableName, + newColumnName, + tx, + cancellationToken + ) + .ConfigureAwait(false) + ) + { + return false; + } + + (schemaName, tableName, columnName) = NormalizeNames(schemaName, tableName, columnName); + + var schemaQualifiedTableName = GetSchemaQualifiedIdentifierName(schemaName, tableName); + + // As of version 3.25.0 released September 2018, SQLite supports renaming columns + await ExecuteAsync( + db, + $""" + ALTER TABLE {schemaQualifiedTableName} + RENAME COLUMN {columnName} + TO {newColumnName} + """, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + + return true; + } +} diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.DefaultConstraints.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.DefaultConstraints.cs similarity index 94% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.DefaultConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.DefaultConstraints.cs index c09f7eb..3ee26f3 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.DefaultConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.DefaultConstraints.cs @@ -1,443 +1,444 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Providers.Base; - -public abstract partial class DatabaseMethodsBase -{ - /// - /// Checks if a default constraint exists in the database. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the constraint exists, otherwise false. - public virtual async Task DoesDefaultConstraintExistAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await GetDefaultConstraintAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false) != null; - } - - /// - /// Checks if a default constraint exists on a specific column in the database. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the constraint exists, otherwise false. - public virtual async Task DoesDefaultConstraintExistOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await GetDefaultConstraintOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ) - .ConfigureAwait(false) != null; - } - - /// - /// Creates a default constraint if it does not exist. - /// - /// The database connection. - /// The default constraint. - /// The transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - public virtual async Task CreateDefaultConstraintIfNotExistsAsync( - IDbConnection db, - DxDefaultConstraint constraint, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await CreateDefaultConstraintIfNotExistsAsync( - db, - constraint.SchemaName, - constraint.TableName, - constraint.ColumnName, - constraint.ConstraintName, - constraint.Expression, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Creates a default constraint if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The constraint name. - /// The expression. - /// The transaction. - /// The cancellation token. - /// True if the constraint was created, otherwise false. - public virtual async Task CreateDefaultConstraintIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - string constraintName, - string expression, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - if (string.IsNullOrWhiteSpace(constraintName)) - { - throw new ArgumentException("Constraint name is required.", nameof(constraintName)); - } - - if (string.IsNullOrWhiteSpace(expression)) - { - throw new ArgumentException("Expression is required.", nameof(expression)); - } - - if ( - await DoesDefaultConstraintExistAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false) - ) - { - return false; - } - - var sql = SqlAlterTableAddDefaultConstraint( - schemaName, - tableName, - columnName, - constraintName, - expression - ); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } - - /// - /// Gets a default constraint from the database. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// The default constraint if found, otherwise null. - public virtual async Task GetDefaultConstraintAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(constraintName)) - { - throw new ArgumentException("Constraint name is required.", nameof(constraintName)); - } - - var defaultConstraints = await GetDefaultConstraintsAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - return defaultConstraints.SingleOrDefault(); - } - - /// - /// Gets the name of the default constraint on a specific column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The name of the default constraint if found, otherwise null. - public virtual async Task GetDefaultConstraintNameOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(columnName)) - { - throw new ArgumentException("Column name is required.", nameof(columnName)); - } - - var defaultConstraints = await GetDefaultConstraintsAsync( - db, - schemaName, - tableName, - null, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - return defaultConstraints - .FirstOrDefault(c => - !string.IsNullOrWhiteSpace(c.ColumnName) - && c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) - ) - ?.ConstraintName; - } - - /// - /// Gets the names of all default constraints in the database. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of default constraint names. - public virtual async Task> GetDefaultConstraintNamesAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var checkConstraints = await GetDefaultConstraintsAsync( - db, - schemaName, - tableName, - constraintNameFilter, - tx, - cancellationToken - ) - .ConfigureAwait(false); - return checkConstraints.Select(c => c.ConstraintName).ToList(); - } - - /// - /// Gets the default constraint on a specific column. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// The default constraint if found, otherwise null. - public virtual async Task GetDefaultConstraintOnColumnAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(columnName)) - { - throw new ArgumentException("Column name is required.", nameof(columnName)); - } - - var defaultConstraints = await GetDefaultConstraintsAsync( - db, - schemaName, - tableName, - null, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - return defaultConstraints.FirstOrDefault(c => - !string.IsNullOrWhiteSpace(c.ColumnName) - && c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) - ); - } - - /// - /// Gets all default constraints in the database. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name filter. - /// The transaction. - /// The cancellation token. - /// A list of default constraints. - public virtual async Task> GetDefaultConstraintsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string? constraintNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - var table = await GetTableAsync(db, schemaName, tableName, tx, cancellationToken) - .ConfigureAwait(false); - - if (table == null) - { - return []; - } - - var filter = string.IsNullOrWhiteSpace(constraintNameFilter) - ? null - : ToSafeString(constraintNameFilter); - - return string.IsNullOrWhiteSpace(filter) - ? table.DefaultConstraints - : table - .DefaultConstraints.Where(c => c.ConstraintName.IsWildcardPatternMatch(filter)) - .ToList(); - } - - /// - /// Drops the default constraint on a specific column if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - public virtual async Task DropDefaultConstraintOnColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var constraintName = await GetDefaultConstraintNameOnColumnAsync( - db, - schemaName, - tableName, - columnName, - tx, - cancellationToken - ).ConfigureAwait(false); - - if (string.IsNullOrWhiteSpace(constraintName)) - { - return false; - } - - var sql = SqlDropDefaultConstraint(schemaName, tableName, columnName, constraintName); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } - - /// - /// Drops a default constraint if it exists. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The constraint name. - /// The transaction. - /// The cancellation token. - /// True if the constraint was dropped, otherwise false. - public virtual async Task DropDefaultConstraintIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var defaultConstraint = await GetDefaultConstraintAsync( - db, - schemaName, - tableName, - constraintName, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - if (string.IsNullOrWhiteSpace(defaultConstraint?.ColumnName)) - { - return false; - } - - var sql = SqlDropDefaultConstraint( - schemaName, - tableName, - defaultConstraint.ColumnName, - constraintName - ); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Providers.Base; + +public abstract partial class DatabaseMethodsBase +{ + /// + /// Checks if a default constraint exists in the database. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the constraint exists, otherwise false. + public virtual async Task DoesDefaultConstraintExistAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await GetDefaultConstraintAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false) != null; + } + + /// + /// Checks if a default constraint exists on a specific column in the database. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the constraint exists, otherwise false. + public virtual async Task DoesDefaultConstraintExistOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await GetDefaultConstraintOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false) != null; + } + + /// + /// Creates a default constraint if it does not exist. + /// + /// The database connection. + /// The default constraint. + /// The transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + public virtual async Task CreateDefaultConstraintIfNotExistsAsync( + IDbConnection db, + DmDefaultConstraint constraint, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await CreateDefaultConstraintIfNotExistsAsync( + db, + constraint.SchemaName, + constraint.TableName, + constraint.ColumnName, + constraint.ConstraintName, + constraint.Expression, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Creates a default constraint if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The constraint name. + /// The expression. + /// The transaction. + /// The cancellation token. + /// True if the constraint was created, otherwise false. + public virtual async Task CreateDefaultConstraintIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + string constraintName, + string expression, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + if (string.IsNullOrWhiteSpace(constraintName)) + { + throw new ArgumentException("Constraint name is required.", nameof(constraintName)); + } + + if (string.IsNullOrWhiteSpace(expression)) + { + throw new ArgumentException("Expression is required.", nameof(expression)); + } + + if ( + await DoesDefaultConstraintExistAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false) + ) + { + return false; + } + + var sql = SqlAlterTableAddDefaultConstraint( + schemaName, + tableName, + columnName, + constraintName, + expression + ); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } + + /// + /// Gets a default constraint from the database. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// The default constraint if found, otherwise null. + public virtual async Task GetDefaultConstraintAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(constraintName)) + { + throw new ArgumentException("Constraint name is required.", nameof(constraintName)); + } + + var defaultConstraints = await GetDefaultConstraintsAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + return defaultConstraints.SingleOrDefault(); + } + + /// + /// Gets the name of the default constraint on a specific column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The name of the default constraint if found, otherwise null. + public virtual async Task GetDefaultConstraintNameOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(columnName)) + { + throw new ArgumentException("Column name is required.", nameof(columnName)); + } + + var defaultConstraints = await GetDefaultConstraintsAsync( + db, + schemaName, + tableName, + null, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + return defaultConstraints + .FirstOrDefault(c => + !string.IsNullOrWhiteSpace(c.ColumnName) + && c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) + ) + ?.ConstraintName; + } + + /// + /// Gets the names of all default constraints in the database. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of default constraint names. + public virtual async Task> GetDefaultConstraintNamesAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var checkConstraints = await GetDefaultConstraintsAsync( + db, + schemaName, + tableName, + constraintNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); + return checkConstraints.Select(c => c.ConstraintName).ToList(); + } + + /// + /// Gets the default constraint on a specific column. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// The default constraint if found, otherwise null. + public virtual async Task GetDefaultConstraintOnColumnAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(columnName)) + { + throw new ArgumentException("Column name is required.", nameof(columnName)); + } + + var defaultConstraints = await GetDefaultConstraintsAsync( + db, + schemaName, + tableName, + null, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + return defaultConstraints.FirstOrDefault(c => + !string.IsNullOrWhiteSpace(c.ColumnName) + && c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) + ); + } + + /// + /// Gets all default constraints in the database. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name filter. + /// The transaction. + /// The cancellation token. + /// A list of default constraints. + public virtual async Task> GetDefaultConstraintsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string? constraintNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + var table = await GetTableAsync(db, schemaName, tableName, tx, cancellationToken) + .ConfigureAwait(false); + + if (table == null) + { + return []; + } + + var filter = string.IsNullOrWhiteSpace(constraintNameFilter) + ? null + : ToSafeString(constraintNameFilter); + + return string.IsNullOrWhiteSpace(filter) + ? table.DefaultConstraints + : table + .DefaultConstraints.Where(c => c.ConstraintName.IsWildcardPatternMatch(filter)) + .ToList(); + } + + /// + /// Drops the default constraint on a specific column if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + public virtual async Task DropDefaultConstraintOnColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var constraintName = await GetDefaultConstraintNameOnColumnAsync( + db, + schemaName, + tableName, + columnName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + if (string.IsNullOrWhiteSpace(constraintName)) + { + return false; + } + + var sql = SqlDropDefaultConstraint(schemaName, tableName, columnName, constraintName); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } + + /// + /// Drops a default constraint if it exists. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The constraint name. + /// The transaction. + /// The cancellation token. + /// True if the constraint was dropped, otherwise false. + public virtual async Task DropDefaultConstraintIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var defaultConstraint = await GetDefaultConstraintAsync( + db, + schemaName, + tableName, + constraintName, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + if (string.IsNullOrWhiteSpace(defaultConstraint?.ColumnName)) + { + return false; + } + + var sql = SqlDropDefaultConstraint( + schemaName, + tableName, + defaultConstraint.ColumnName, + constraintName + ); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } +} diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.ForeignKeyConstraints.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.ForeignKeyConstraints.cs similarity index 93% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.ForeignKeyConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.ForeignKeyConstraints.cs index aca9aab..15f2a0b 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.ForeignKeyConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.ForeignKeyConstraints.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Base; +namespace MJCZone.DapperMatic.Providers.Base; public abstract partial class DatabaseMethodsBase { @@ -75,7 +75,7 @@ public virtual async Task DoesForeignKeyConstraintExistOnColumnAsync( /// True if the constraint was created, otherwise false. public virtual async Task CreateForeignKeyConstraintIfNotExistsAsync( IDbConnection db, - DxForeignKeyConstraint constraint, + DmForeignKeyConstraint constraint, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -116,11 +116,11 @@ public virtual async Task CreateForeignKeyConstraintIfNotExistsAsync( string? schemaName, string tableName, string constraintName, - DxOrderedColumn[] sourceColumns, + DmOrderedColumn[] sourceColumns, string referencedTableName, - DxOrderedColumn[] referencedColumns, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction, + DmOrderedColumn[] referencedColumns, + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -209,7 +209,7 @@ await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) /// The transaction. /// The cancellation token. /// The foreign key constraint if found, otherwise null. - public virtual async Task GetForeignKeyConstraintAsync( + public virtual async Task GetForeignKeyConstraintAsync( IDbConnection db, string? schemaName, string tableName, @@ -308,7 +308,7 @@ public virtual async Task> GetForeignKeyConstraintNamesAsync( /// The transaction. /// The cancellation token. /// The foreign key constraint if found, otherwise null. - public virtual async Task GetForeignKeyConstraintOnColumnAsync( + public virtual async Task GetForeignKeyConstraintOnColumnAsync( IDbConnection db, string? schemaName, string tableName, @@ -348,7 +348,7 @@ public virtual async Task> GetForeignKeyConstraintNamesAsync( /// The transaction. /// The cancellation token. /// A list of foreign key constraints. - public virtual async Task> GetForeignKeyConstraintsAsync( + public virtual async Task> GetForeignKeyConstraintsAsync( IDbConnection db, string? schemaName, string tableName, @@ -367,7 +367,7 @@ public virtual async Task> GetForeignKeyConstraints if (table == null) { - return new List(); + return new List(); } var filter = string.IsNullOrWhiteSpace(constraintNameFilter) diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Indexes.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Indexes.cs similarity index 93% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.Indexes.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Indexes.cs index 8012671..587b631 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Indexes.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Indexes.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Base; +namespace MJCZone.DapperMatic.Providers.Base; public abstract partial class DatabaseMethodsBase { @@ -70,7 +70,7 @@ await GetIndexesOnColumnAsync( /// True if the index was created, otherwise false. public virtual async Task CreateIndexIfNotExistsAsync( IDbConnection db, - DxIndex index, + DmIndex index, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -105,7 +105,7 @@ public virtual async Task CreateIndexIfNotExistsAsync( string? schemaName, string tableName, string indexName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, bool isUnique = false, IDbTransaction? tx = null, CancellationToken cancellationToken = default @@ -142,7 +142,7 @@ await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) /// The transaction. /// The cancellation token. /// The index details, or null if the index does not exist. - public virtual async Task GetIndexAsync( + public virtual async Task GetIndexAsync( IDbConnection db, string? schemaName, string tableName, @@ -178,7 +178,7 @@ await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) /// The transaction. /// The cancellation token. /// A list of indexes. - public virtual async Task> GetIndexesAsync( + public virtual async Task> GetIndexesAsync( IDbConnection db, string? schemaName, string tableName, @@ -195,13 +195,14 @@ public virtual async Task> GetIndexesAsync( (schemaName, tableName, _) = NormalizeNames(schemaName, tableName); return await GetIndexesInternalAsync( - db, - schemaName, - tableName, - string.IsNullOrWhiteSpace(indexNameFilter) ? null : indexNameFilter, - tx, - cancellationToken - ).ConfigureAwait(false); + db, + schemaName, + tableName, + string.IsNullOrWhiteSpace(indexNameFilter) ? null : indexNameFilter, + tx, + cancellationToken + ) + .ConfigureAwait(false); } /// @@ -275,7 +276,7 @@ await GetIndexesAsync(db, schemaName, tableName, indexNameFilter, tx, cancellati /// The transaction. /// The cancellation token. /// A list of indexes. - public virtual async Task> GetIndexesOnColumnAsync( + public virtual async Task> GetIndexesOnColumnAsync( IDbConnection db, string? schemaName, string tableName, diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.PrimaryKeyConstraints.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.PrimaryKeyConstraints.cs similarity index 90% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.PrimaryKeyConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.PrimaryKeyConstraints.cs index 78914df..a433482 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.PrimaryKeyConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.PrimaryKeyConstraints.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Base; +namespace MJCZone.DapperMatic.Providers.Base; public abstract partial class DatabaseMethodsBase { @@ -36,20 +36,21 @@ public virtual async Task DoesPrimaryKeyConstraintExistAsync( /// True if the primary key constraint was created, otherwise false. public virtual async Task CreatePrimaryKeyConstraintIfNotExistsAsync( IDbConnection db, - DxPrimaryKeyConstraint constraint, + DmPrimaryKeyConstraint constraint, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) { return await CreatePrimaryKeyConstraintIfNotExistsAsync( - db, - constraint.SchemaName, - constraint.TableName, - constraint.ConstraintName, - [.. constraint.Columns], - tx, - cancellationToken - ).ConfigureAwait(false); + db, + constraint.SchemaName, + constraint.TableName, + constraint.ConstraintName, + [.. constraint.Columns], + tx, + cancellationToken + ) + .ConfigureAwait(false); } /// @@ -68,7 +69,7 @@ public virtual async Task CreatePrimaryKeyConstraintIfNotExistsAsync( string? schemaName, string tableName, string constraintName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -132,7 +133,7 @@ await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) /// The transaction to use, or null. /// The cancellation token. /// The primary key constraint, or null if it does not exist. - public virtual async Task GetPrimaryKeyConstraintAsync( + public virtual async Task GetPrimaryKeyConstraintAsync( IDbConnection db, string? schemaName, string tableName, diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Schemas.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Schemas.cs similarity index 95% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.Schemas.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Schemas.cs index 3c359a0..f5552cf 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Schemas.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Schemas.cs @@ -1,147 +1,147 @@ -using System.Data; - -namespace DapperMatic.Providers.Base; - -public abstract partial class DatabaseMethodsBase -{ - /// - /// Checks if a schema exists in the database. - /// - /// The database connection. - /// The name of the schema. - /// The database transaction. - /// The cancellation token. - /// True if the schema exists, otherwise false. - public virtual async Task DoesSchemaExistAsync( - IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (!SupportsSchemas) - { - return false; - } - - if (string.IsNullOrWhiteSpace(schemaName)) - { - throw new ArgumentException("Schema name is required.", nameof(schemaName)); - } - - return ( - await GetSchemaNamesAsync(db, schemaName, tx, cancellationToken) - .ConfigureAwait(false) - ).Count > 0; - } - - /// - /// Creates a schema if it does not exist in the database. - /// - /// The database connection. - /// The name of the schema. - /// The database transaction. - /// The cancellation token. - /// True if the schema was created, otherwise false. - public virtual async Task CreateSchemaIfNotExistsAsync( - IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (!SupportsSchemas) - { - return false; - } - - if (string.IsNullOrWhiteSpace(schemaName)) - { - throw new ArgumentException("Schema name is required.", nameof(schemaName)); - } - - if (await DoesSchemaExistAsync(db, schemaName, tx, cancellationToken).ConfigureAwait(false)) - { - return false; - } - - var sql = SqlCreateSchema(schemaName); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } - - /// - /// Retrieves the list of schema names from the database. - /// - /// The database connection. - /// The schema name filter. - /// The database transaction. - /// The cancellation token. - /// A list of schema names. - public virtual async Task> GetSchemaNamesAsync( - IDbConnection db, - string? schemaNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (!SupportsSchemas) - { - return []; - } - - var (sql, parameters) = SqlGetSchemaNames(schemaNameFilter); - - return await QueryAsync( - db, - sql, - parameters, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops a schema if it exists in the database. - /// - /// The database connection. - /// The name of the schema. - /// The database transaction. - /// The cancellation token. - /// True if the schema was dropped, otherwise false. - public virtual async Task DropSchemaIfExistsAsync( - IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (!SupportsSchemas) - { - return false; - } - - if (string.IsNullOrWhiteSpace(schemaName)) - { - throw new ArgumentException("Schema name is required.", nameof(schemaName)); - } - - if ( - !await DoesSchemaExistAsync(db, schemaName, tx, cancellationToken).ConfigureAwait(false) - ) - { - return false; - } - - var sql = SqlDropSchema(schemaName); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } -} +using System.Data; + +namespace MJCZone.DapperMatic.Providers.Base; + +public abstract partial class DatabaseMethodsBase +{ + /// + /// Checks if a schema exists in the database. + /// + /// The database connection. + /// The name of the schema. + /// The database transaction. + /// The cancellation token. + /// True if the schema exists, otherwise false. + public virtual async Task DoesSchemaExistAsync( + IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (!SupportsSchemas) + { + return false; + } + + if (string.IsNullOrWhiteSpace(schemaName)) + { + throw new ArgumentException("Schema name is required.", nameof(schemaName)); + } + + return ( + await GetSchemaNamesAsync(db, schemaName, tx, cancellationToken) + .ConfigureAwait(false) + ).Count > 0; + } + + /// + /// Creates a schema if it does not exist in the database. + /// + /// The database connection. + /// The name of the schema. + /// The database transaction. + /// The cancellation token. + /// True if the schema was created, otherwise false. + public virtual async Task CreateSchemaIfNotExistsAsync( + IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (!SupportsSchemas) + { + return false; + } + + if (string.IsNullOrWhiteSpace(schemaName)) + { + throw new ArgumentException("Schema name is required.", nameof(schemaName)); + } + + if (await DoesSchemaExistAsync(db, schemaName, tx, cancellationToken).ConfigureAwait(false)) + { + return false; + } + + var sql = SqlCreateSchema(schemaName); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } + + /// + /// Retrieves the list of schema names from the database. + /// + /// The database connection. + /// The schema name filter. + /// The database transaction. + /// The cancellation token. + /// A list of schema names. + public virtual async Task> GetSchemaNamesAsync( + IDbConnection db, + string? schemaNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (!SupportsSchemas) + { + return []; + } + + var (sql, parameters) = SqlGetSchemaNames(schemaNameFilter); + + return await QueryAsync( + db, + sql, + parameters, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops a schema if it exists in the database. + /// + /// The database connection. + /// The name of the schema. + /// The database transaction. + /// The cancellation token. + /// True if the schema was dropped, otherwise false. + public virtual async Task DropSchemaIfExistsAsync( + IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (!SupportsSchemas) + { + return false; + } + + if (string.IsNullOrWhiteSpace(schemaName)) + { + throw new ArgumentException("Schema name is required.", nameof(schemaName)); + } + + if ( + !await DoesSchemaExistAsync(db, schemaName, tx, cancellationToken).ConfigureAwait(false) + ) + { + return false; + } + + var sql = SqlDropSchema(schemaName); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } +} diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Strings.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Strings.cs similarity index 91% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.Strings.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Strings.cs index 83c67fa..4e88a9a 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Strings.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Strings.cs @@ -1,7 +1,7 @@ using System.Text; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Base; +namespace MJCZone.DapperMatic.Providers.Base; public abstract partial class DatabaseMethodsBase { @@ -167,9 +167,9 @@ protected virtual string SqlTruncateTable(string? schemaName, string tableName) /// The database version. /// A string representing the column definition for the new column. protected virtual string SqlInlineColumnDefinition( - DxTable existingTable, - DxColumn column, - DxTable tableConstraints, + DmTable existingTable, + DmColumn column, + DmTable tableConstraints, Version dbVersion ) { @@ -216,11 +216,11 @@ out var useTableConstraint if (useTableConstraint) { - tableConstraints.PrimaryKeyConstraint = new DxPrimaryKeyConstraint( + tableConstraints.PrimaryKeyConstraint = new DmPrimaryKeyConstraint( schemaName, tableName, pkConstraintName, - [new DxOrderedColumn(columnName)] + [new DmOrderedColumn(columnName)] ); } else @@ -294,7 +294,7 @@ out var useTableConstraint if (useTableConstraint) { tableConstraints.CheckConstraints.Add( - new DxCheckConstraint( + new DmCheckConstraint( schemaName, tableName, columnName, @@ -332,11 +332,11 @@ out var useTableConstraint if (useTableConstraint) { tableConstraints.UniqueConstraints.Add( - new DxUniqueConstraint( + new DmUniqueConstraint( schemaName, tableName, ucConstraintName, - [new DxOrderedColumn(columnName)] + [new DmOrderedColumn(columnName)] ) ); } @@ -363,7 +363,7 @@ [new DxOrderedColumn(columnName)] schemaName, fkConstraintName, column.ReferencedTableName, - new DxOrderedColumn(column.ReferencedColumnName), + new DmOrderedColumn(column.ReferencedColumnName), column.OnDelete, column.OnUpdate, out var useTableConstraint @@ -377,15 +377,15 @@ out var useTableConstraint if (useTableConstraint) { tableConstraints.ForeignKeyConstraints.Add( - new DxForeignKeyConstraint( + new DmForeignKeyConstraint( schemaName, tableName, fkConstraintName, - [new DxOrderedColumn(columnName)], + [new DmOrderedColumn(columnName)], column.ReferencedTableName, - [new DxOrderedColumn(column.ReferencedColumnName)], - column.OnDelete ?? DxForeignKeyAction.NoAction, - column.OnUpdate ?? DxForeignKeyAction.NoAction + [new DmOrderedColumn(column.ReferencedColumnName)], + column.OnDelete ?? DmForeignKeyAction.NoAction, + column.OnUpdate ?? DmForeignKeyAction.NoAction ) ); } @@ -402,11 +402,11 @@ [new DxOrderedColumn(column.ReferencedColumnName)], { var indexName = DbProviderUtils.GenerateIndexName(tableName, columnName); tableConstraints.Indexes.Add( - new DxIndex( + new DmIndex( schemaName, tableName, indexName, - [new DxOrderedColumn(columnName)], + [new DmOrderedColumn(columnName)], column.IsUnique ) ); @@ -418,10 +418,10 @@ [new DxOrderedColumn(columnName)], /// /// Generates a string representing a column name and its data type for use in SQL inline statements (e.g., CREATE TABLE or ALTER TABLE). /// - /// The DxColumn object containing the column details. + /// The DmColumn object containing the column details. /// The database version. Used to determine the data type syntax for compatibility with different DBMS versions. /// A string representing the column name and its data type, suitable for use in SQL inline statements. - protected virtual string SqlInlineColumnNameAndType(DxColumn column, Version dbVersion) + protected virtual string SqlInlineColumnNameAndType(DmColumn column, Version dbVersion) { var descriptor = new DotnetTypeDescriptor( column.DotnetType.OrUnderlyingTypeIfNullable(), @@ -453,9 +453,9 @@ protected virtual string SqlInlineColumnNameAndType(DxColumn column, Version dbV /// /// Generates a string representing the NULLability clause for a column (e.g., NOT NULL or NULL). /// - /// The DxColumn object containing the column details, including its Nullable property. + /// The DmColumn object containing the column details, including its Nullable property. /// A string representing the NULLability clause for use in SQL inline statements, or an empty string if not specified. - protected virtual string SqlInlineColumnNullable(DxColumn column) + protected virtual string SqlInlineColumnNullable(DmColumn column) { return column.IsNullable && !column.IsUnique && !column.IsPrimaryKey ? " NULL" @@ -465,7 +465,7 @@ protected virtual string SqlInlineColumnNullable(DxColumn column) /// /// Generates a string representing a PRIMARY KEY constraint clause for a specific column in SQL inline statements. /// - /// The DxColumn object containing the column details. + /// The DmColumn object containing the column details. /// The desired name for the PRIMARY KEY constraint. If null, a default name will be generated. /// /// Output parameter indicating whether to use TABLE CONSTRAINT syntax (true) or inline the constraint within the column definition (false). @@ -473,7 +473,7 @@ protected virtual string SqlInlineColumnNullable(DxColumn column) /// /// A string representing the PRIMARY KEY constraint clause for use in SQL inline statements. protected virtual string SqlInlinePrimaryKeyColumnConstraint( - DxColumn column, + DmColumn column, string constraintName, out bool useTableConstraint ) @@ -485,9 +485,9 @@ out bool useTableConstraint /// /// Generates a string representing both a PRIMARY KEY and AUTOINCREMENT constraint clauses for a specific column in SQL inline statements. /// - /// The DxColumn object containing the column details, which must have an Identity property set to true. + /// The DmColumn object containing the column details, which must have an Identity property set to true. /// A string representing both the PRIMARY KEY and AUTOINCREMENT constraint clauses for use in SQL inline statements. If the column does not support identity or autoincrement, an empty string is returned. - protected virtual string SqlInlinePrimaryKeyAutoIncrementColumnConstraint(DxColumn column) + protected virtual string SqlInlinePrimaryKeyAutoIncrementColumnConstraint(DmColumn column) { return "IDENTITY(1,1)"; } @@ -557,7 +557,7 @@ out bool useTableConstraint /// The name of the schema containing the referenced table, if not in the same schema as the current table. /// The desired name for the FOREIGN KEY constraint. If null, no constraint name will be included. /// The name of the referenced (parent) table. - /// The DxOrderedColumn object representing the referenced column in the parent table. + /// The DmOrderedColumn object representing the referenced column in the parent table. /// The ON DELETE action to take when a referenced row is deleted. Can be null if not specified. /// The ON UPDATE action to take when a referenced row is updated. Can be null if not specified. /// @@ -569,9 +569,9 @@ protected virtual string SqlInlineForeignKeyColumnConstraint( string? schemaName, string constraintName, string referencedTableName, - DxOrderedColumn referencedColumn, - DxForeignKeyAction? onDelete, - DxForeignKeyAction? onUpdate, + DmOrderedColumn referencedColumn, + DmForeignKeyAction? onDelete, + DmForeignKeyAction? onUpdate, out bool useTableConstraint ) { @@ -584,12 +584,12 @@ out bool useTableConstraint /// /// Generates a string representing a PRIMARY KEY constraint clause for the specified table. /// - /// The DxTable object representing the table to which the PRIMARY KEY constraint is applied. - /// The DxPrimaryKeyConstraint object containing the list of columns that form the primary key. + /// The DmTable object representing the table to which the PRIMARY KEY constraint is applied. + /// The DmPrimaryKeyConstraint object containing the list of columns that form the primary key. /// A string representing the PRIMARY KEY constraint clause for use in SQL inline statements, or an empty string if no columns are specified in the primary key constraint. protected virtual string SqlInlinePrimaryKeyTableConstraint( - DxTable table, - DxPrimaryKeyConstraint primaryKeyConstraint + DmTable table, + DmPrimaryKeyConstraint primaryKeyConstraint ) { var pkColumnNames = primaryKeyConstraint.Columns.Select(c => c.ColumnName).ToArray(); @@ -604,15 +604,15 @@ DxPrimaryKeyConstraint primaryKeyConstraint } /// - /// Generates a string representing a CHECK constraint clause for the specified table using the provided DxCheckConstraint object. + /// Generates a string representing a CHECK constraint clause for the specified table using the provided DmCheckConstraint object. /// - /// The DxTable object representing the table to which the CHECK constraint is applied. + /// The DmTable object representing the table to which the CHECK constraint is applied. /// - /// The DxCheckConstraint object containing the check condition that enforces data integrity on one or more columns in the table. + /// The DmCheckConstraint object containing the check condition that enforces data integrity on one or more columns in the table. /// The check condition should be a valid SQL expression that evaluates to TRUE or FALSE. /// /// A string representing the CHECK constraint clause for use in SQL inline statements, or an empty string if no check condition is specified. - protected virtual string SqlInlineCheckTableConstraint(DxTable table, DxCheckConstraint check) + protected virtual string SqlInlineCheckTableConstraint(DmTable table, DmCheckConstraint check) { var ckConstraintName = !string.IsNullOrWhiteSpace(check.ConstraintName) ? check.ConstraintName @@ -627,21 +627,21 @@ protected virtual string SqlInlineCheckTableConstraint(DxTable table, DxCheckCon } /// - /// Generates a string representing a UNIQUE constraint clause for the specified table using the provided DxUniqueConstraint object. + /// Generates a string representing a UNIQUE constraint clause for the specified table using the provided DmUniqueConstraint object. /// - /// The DxTable object representing the table to which the UNIQUE constraint is applied. + /// The DmTable object representing the table to which the UNIQUE constraint is applied. /// - /// The DxUniqueConstraint object containing the list of columns that form the unique key and, optionally, the constraint name. + /// The DmUniqueConstraint object containing the list of columns that form the unique key and, optionally, the constraint name. /// If no constraint name is provided, none will be included in the generated clause. /// /// /// Indicates whether the database provider supports ordered keys within constraints. This flag affects how the unique key columns are listed in the output clause. /// Set to true for providers like SQL Server that support ordered keys; set to false for providers like MySQL that treat all unique key columns as unordered. /// - /// A string representing the UNIQUE constraint clause for use in SQL inline statements, or an empty string if no columns are specified in the DxUniqueConstraint object. + /// A string representing the UNIQUE constraint clause for use in SQL inline statements, or an empty string if no columns are specified in the DmUniqueConstraint object. protected virtual string SqlInlineUniqueTableConstraint( - DxTable table, - DxUniqueConstraint uc, + DmTable table, + DmUniqueConstraint uc, bool supportsOrderedKeysInConstraints ) { @@ -654,24 +654,24 @@ bool supportsOrderedKeysInConstraints var uniqueColumns = uc.Columns.Select(c => supportsOrderedKeysInConstraints - ? new DxOrderedColumn(NormalizeName(c.ColumnName), c.Order).ToString() - : new DxOrderedColumn(NormalizeName(c.ColumnName)).ToString() + ? new DmOrderedColumn(NormalizeName(c.ColumnName), c.Order).ToString() + : new DmOrderedColumn(NormalizeName(c.ColumnName)).ToString() ); return $"CONSTRAINT {NormalizeName(ucConstraintName)} UNIQUE ({string.Join(", ", uniqueColumns)})"; } /// - /// Generates a string representing a FOREIGN KEY constraint clause for the specified table using the provided DxForeignKeyConstraint object. + /// Generates a string representing a FOREIGN KEY constraint clause for the specified table using the provided DmForeignKeyConstraint object. /// - /// The DxTable object representing the table to which the FOREIGN KEY constraint is applied. + /// The DmTable object representing the table to which the FOREIGN KEY constraint is applied. /// - /// The DxForeignKeyConstraint object containing the list of child columns, referenced table and column names, + /// The DmForeignKeyConstraint object containing the list of child columns, referenced table and column names, /// as well as the ON DELETE and ON UPDATE actions. If no constraint name is provided, none will be included in the generated clause. /// - /// A string representing the FOREIGN KEY constraint clause for use in SQL inline statements, or an empty string if no columns are specified in the DxForeignKeyConstraint object. + /// A string representing the FOREIGN KEY constraint clause for use in SQL inline statements, or an empty string if no columns are specified in the DmForeignKeyConstraint object. protected virtual string SqlInlineForeignKeyTableConstraint( - DxTable table, - DxForeignKeyConstraint fk + DmTable table, + DmForeignKeyConstraint fk ) { return $""" @@ -807,7 +807,7 @@ string constraintName /// The name of the schema containing the table. Can be null if not specified, indicating the default schema. /// The name of the table to add the PRIMARY KEY constraint to. /// The desired name for the new PRIMARY KEY constraint. - /// An array of DxOrderedColumn objects representing the columns that should serve as the primary key in the table, along with their ordering (if any). + /// An array of DmOrderedColumn objects representing the columns that should serve as the primary key in the table, along with their ordering (if any). /// /// A boolean value indicating whether the database system supports ordered keys (column ordering) in constraints. If true, column order will be included in the generated SQL statement. /// @@ -816,7 +816,7 @@ protected virtual string SqlAlterTableAddPrimaryKeyConstraint( string? schemaName, string tableName, string constraintName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, bool supportsOrderedKeysInConstraints ) { @@ -825,7 +825,7 @@ bool supportsOrderedKeysInConstraints columns.Select(c => { var columnName = NormalizeName(c.ColumnName); - return c.Order == DxColumnOrder.Ascending ? columnName : $"{columnName} DESC"; + return c.Order == DmColumnOrder.Ascending ? columnName : $"{columnName} DESC"; }) ); return $""" @@ -860,7 +860,7 @@ string constraintName /// The name of the schema containing the table. Can be null if not specified, indicating the default schema. /// The name of the table to add the UNIQUE constraint to. /// The desired name for the new UNIQUE constraint. - /// An array of DxOrderedColumn objects representing the columns that should be unique together in the table. + /// An array of DmOrderedColumn objects representing the columns that should be unique together in the table. /// /// A boolean value indicating whether the database system supports ordered keys (column ordering) in constraints. If true, column order will be included in the generated SQL statement. /// @@ -869,14 +869,14 @@ protected virtual string SqlAlterTableAddUniqueConstraint( string? schemaName, string tableName, string constraintName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, bool supportsOrderedKeysInConstraints ) { var uniqueColumns = columns.Select(c => supportsOrderedKeysInConstraints - ? new DxOrderedColumn(NormalizeName(c.ColumnName), c.Order).ToString() - : new DxOrderedColumn(NormalizeName(c.ColumnName)).ToString() + ? new DmOrderedColumn(NormalizeName(c.ColumnName), c.Order).ToString() + : new DmOrderedColumn(NormalizeName(c.ColumnName)).ToString() ); return $""" ALTER TABLE {GetSchemaQualifiedIdentifierName(schemaName, tableName)} @@ -912,23 +912,23 @@ string constraintName /// The name of the schema containing the table. Can be null if not specified, indicating the default schema. /// The desired name for the new foreign key constraint. /// The name of the table to add the foreign key constraint to. - /// An array of DxOrderedColumn objects representing the columns in the current (referencing) table that participate in the foreign key constraint. + /// An array of DmOrderedColumn objects representing the columns in the current (referencing) table that participate in the foreign key constraint. /// The name of the referenced table where the related data resides. /// - /// An array of DxOrderedColumn objects representing the columns in the referenced table that correspond to the columns in the current (referencing) table. + /// An array of DmOrderedColumn objects representing the columns in the referenced table that correspond to the columns in the current (referencing) table. /// - /// The action to take when a referenced row is deleted. Can be one of the DxForeignKeyAction enum values: Cascade, SetNull, NoAction, or SetDefault. - /// The action to take when a referenced row is updated. Can be one of the DxForeignKeyAction enum values: Cascade, SetNull, NoAction, or SetDefault. + /// The action to take when a referenced row is deleted. Can be one of the DmForeignKeyAction enum values: Cascade, SetNull, NoAction, or SetDefault. + /// The action to take when a referenced row is updated. Can be one of the DmForeignKeyAction enum values: Cascade, SetNull, NoAction, or SetDefault. /// A SQL statement that adds a new foreign key constraint with the given name, columns, referencing table, and actions to the specified table in its schema. protected virtual string SqlAlterTableAddForeignKeyConstraint( string? schemaName, string constraintName, string tableName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, string referencedTableName, - DxOrderedColumn[] referencedColumns, - DxForeignKeyAction onDelete, - DxForeignKeyAction onUpdate + DmOrderedColumn[] referencedColumns, + DmForeignKeyAction onDelete, + DmForeignKeyAction onUpdate ) { var schemaQualifiedTableName = GetSchemaQualifiedIdentifierName(schemaName, tableName); @@ -979,7 +979,7 @@ string constraintName /// The name of the schema containing the table. Can be null if not specified, indicating the default schema. /// The name of the table to create an index on. /// The desired name for the new index. - /// An array of DxOrderedColumn objects representing the columns to include in the index. + /// An array of DmOrderedColumn objects representing the columns to include in the index. /// /// A boolean value indicating whether the created index should be a UNIQUE index. The default is false. /// @@ -988,7 +988,7 @@ protected virtual string SqlCreateIndex( string? schemaName, string tableName, string indexName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, bool isUnique = false ) { diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Tables.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Tables.cs similarity index 92% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.Tables.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Tables.cs index 7d80c50..d4b724d 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Tables.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Tables.cs @@ -1,8 +1,8 @@ using System.Data; using System.Text; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Base; +namespace MJCZone.DapperMatic.Providers.Base; public abstract partial class DatabaseMethodsBase { @@ -47,12 +47,12 @@ public virtual async Task DoesTableExistAsync( /// True if all tables were created, otherwise false. public virtual async Task CreateTablesIfNotExistsAsync( IDbConnection db, - DxTable[] tables, + DmTable[] tables, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) { - var afterAllTablesConstraints = new List(); + var afterAllTablesConstraints = new List(); foreach (var table in tables) { @@ -100,7 +100,7 @@ await CreateForeignKeyConstraintIfNotExistsAsync( /// True if the table was created, otherwise false. public virtual async Task CreateTableIfNotExistsAsync( IDbConnection db, - DxTable table, + DmTable table, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -120,8 +120,8 @@ public virtual async Task CreateTableIfNotExistsAsync( /// True if the table was created, otherwise false. protected virtual async Task CreateTableIfNotExistsAsync( IDbConnection db, - DxTable table, - List? afterAllTablesConstraints, + DmTable table, + List? afterAllTablesConstraints, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -159,7 +159,7 @@ await DoesTableExistAsync(db, table.SchemaName, table.TableName, tx, cancellatio $"CREATE TABLE {GetSchemaQualifiedIdentifierName(table.SchemaName, table.TableName)} (" ); - var tableConstraints = new DxTable( + var tableConstraints = new DmTable( schemaName, tableName, [], @@ -186,11 +186,11 @@ [.. table.Indexes] // The column definition builder will detect the primary key constraint is // already added and disregard adding it again. - tableConstraints.PrimaryKeyConstraint = new DxPrimaryKeyConstraint( + tableConstraints.PrimaryKeyConstraint = new DmPrimaryKeyConstraint( table.SchemaName, table.TableName, pkConstraintName, - [.. pkColumns.Select(c => new DxOrderedColumn(c.ColumnName))] + [.. pkColumns.Select(c => new DmOrderedColumn(c.ColumnName))] ); } @@ -226,13 +226,13 @@ [.. table.Indexes] column.ReferencedColumnName ); tableConstraints.ForeignKeyConstraints.Add( - new DxForeignKeyConstraint( + new DmForeignKeyConstraint( table.SchemaName, table.TableName, NormalizeName(fkConstraintName), - [new DxOrderedColumn(column.ColumnName)], + [new DmOrderedColumn(column.ColumnName)], column.ReferencedTableName, - [new DxOrderedColumn(column.ReferencedColumnName)] + [new DmOrderedColumn(column.ReferencedColumnName)] ) ); } @@ -348,13 +348,13 @@ public virtual async Task CreateTableIfNotExistsAsync( IDbConnection db, string? schemaName, string tableName, - DxColumn[] columns, - DxPrimaryKeyConstraint? primaryKey = null, - DxCheckConstraint[]? checkConstraints = null, - DxDefaultConstraint[]? defaultConstraints = null, - DxUniqueConstraint[]? uniqueConstraints = null, - DxForeignKeyConstraint[]? foreignKeyConstraints = null, - DxIndex[]? indexes = null, + DmColumn[] columns, + DmPrimaryKeyConstraint? primaryKey = null, + DmCheckConstraint[]? checkConstraints = null, + DmDefaultConstraint[]? defaultConstraints = null, + DmUniqueConstraint[]? uniqueConstraints = null, + DmForeignKeyConstraint[]? foreignKeyConstraints = null, + DmIndex[]? indexes = null, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -371,7 +371,7 @@ public virtual async Task CreateTableIfNotExistsAsync( return await CreateTableIfNotExistsAsync( db, - new DxTable( + new DmTable( schemaName, tableName, columns, @@ -397,7 +397,7 @@ public virtual async Task CreateTableIfNotExistsAsync( /// The transaction. /// The cancellation token. /// The table if found, otherwise null. - public virtual async Task GetTableAsync( + public virtual async Task GetTableAsync( IDbConnection db, string? schemaName, string tableName, @@ -453,7 +453,7 @@ public virtual async Task> GetTableNamesAsync( /// The transaction. /// The cancellation token. /// A list of tables. - public abstract Task> GetTablesAsync( + public abstract Task> GetTablesAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, @@ -669,7 +669,7 @@ await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) /// The transaction. /// The cancellation token. /// A list of indexes. - protected abstract Task> GetIndexesInternalAsync( + protected abstract Task> GetIndexesInternalAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.UniqueConstraints.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.UniqueConstraints.cs similarity index 95% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.UniqueConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.UniqueConstraints.cs index 491917a..04a796b 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.UniqueConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.UniqueConstraints.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Base; +namespace MJCZone.DapperMatic.Providers.Base; public abstract partial class DatabaseMethodsBase { @@ -75,7 +75,7 @@ public virtual async Task DoesUniqueConstraintExistOnColumnAsync( /// True if the unique constraint was created, otherwise false. public virtual async Task CreateUniqueConstraintIfNotExistsAsync( IDbConnection db, - DxUniqueConstraint constraint, + DmUniqueConstraint constraint, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -108,7 +108,7 @@ public virtual async Task CreateUniqueConstraintIfNotExistsAsync( string? schemaName, string tableName, string constraintName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -174,7 +174,7 @@ await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) /// The transaction to use. /// The cancellation token. /// The unique constraint if found, otherwise null. - public virtual async Task GetUniqueConstraintAsync( + public virtual async Task GetUniqueConstraintAsync( IDbConnection db, string? schemaName, string tableName, @@ -273,7 +273,7 @@ public virtual async Task> GetUniqueConstraintNamesAsync( /// The transaction to use. /// The cancellation token. /// The unique constraint if found, otherwise null. - public virtual async Task GetUniqueConstraintOnColumnAsync( + public virtual async Task GetUniqueConstraintOnColumnAsync( IDbConnection db, string? schemaName, string tableName, @@ -313,7 +313,7 @@ public virtual async Task> GetUniqueConstraintNamesAsync( /// The transaction to use. /// The cancellation token. /// A list of unique constraints. - public virtual async Task> GetUniqueConstraintsAsync( + public virtual async Task> GetUniqueConstraintsAsync( IDbConnection db, string? schemaName, string tableName, diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Views.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Views.cs similarity index 94% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.Views.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Views.cs index 7038bdf..daed04b 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.Views.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.Views.cs @@ -1,261 +1,261 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Providers.Base; - -public abstract partial class DatabaseMethodsBase -{ - /// - /// Checks if a view exists in the database. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The transaction. - /// The cancellation token. - /// True if the view exists, otherwise false. - public virtual async Task DoesViewExistAsync( - IDbConnection db, - string? schemaName, - string viewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return ( - await GetViewNamesAsync(db, schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false) - ).Count == 1; - } - - /// - /// Creates a view if it does not exist. - /// - /// The database connection. - /// The view details. - /// The transaction. - /// The cancellation token. - /// True if the view was created, otherwise false. - public virtual async Task CreateViewIfNotExistsAsync( - IDbConnection db, - DxView view, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await CreateViewIfNotExistsAsync( - db, - view.SchemaName, - view.ViewName, - view.Definition, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Creates a view if it does not exist. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The view definition. - /// The transaction. - /// The cancellation token. - /// True if the view was created, otherwise false. - public virtual async Task CreateViewIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string viewName, - string definition, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrEmpty(definition)) - { - throw new ArgumentException("View definition is required.", nameof(definition)); - } - - if ( - await DoesViewExistAsync(db, schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false) - ) - { - return false; - } - - var sql = SqlCreateView(schemaName, viewName, definition); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } - - /// - /// Gets a view from the database. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The transaction. - /// The cancellation token. - /// The view details, or null if the view does not exist. - public virtual async Task GetViewAsync( - IDbConnection db, - string? schemaName, - string viewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrEmpty(viewName)) - { - throw new ArgumentException("View name is required.", nameof(viewName)); - } - - return ( - await GetViewsAsync(db, schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false) - ).SingleOrDefault(); - } - - /// - /// Gets the names of views from the database. - /// - /// The database connection. - /// The schema name. - /// The view name filter. - /// The transaction. - /// The cancellation token. - /// A list of view names. - public virtual async Task> GetViewNamesAsync( - IDbConnection db, - string? schemaName, - string? viewNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var (sql, parameters) = SqlGetViewNames(schemaName, viewNameFilter); - return await QueryAsync( - db, - sql, - parameters, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Gets views from the database. - /// - /// The database connection. - /// The schema name. - /// The view name filter. - /// The transaction. - /// The cancellation token. - /// A list of views. - public virtual async Task> GetViewsAsync( - IDbConnection db, - string? schemaName, - string? viewNameFilter = null, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var (sql, parameters) = SqlGetViews(schemaName, viewNameFilter); - var views = await QueryAsync( - db, - sql, - parameters, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - foreach (var view in views) - { - view.Definition = NormalizeViewDefinition(view.Definition); - } - return views; - } - - /// - /// Drops a view if it exists. - /// - /// The database connection. - /// The schema name. - /// The view name. - /// The transaction. - /// The cancellation token. - /// True if the view was dropped, otherwise false. - public virtual async Task DropViewIfExistsAsync( - IDbConnection db, - string? schemaName, - string viewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if ( - !await DoesViewExistAsync(db, schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false) - ) - { - return false; - } - - var sql = SqlDropView(schemaName, viewName); - - await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - - return true; - } - - /// - /// Renames a view if it exists. - /// - /// The database connection. - /// The schema name. - /// The current view name. - /// The new view name. - /// The transaction. - /// The cancellation token. - /// True if the view was renamed, otherwise false. - public virtual async Task RenameViewIfExistsAsync( - IDbConnection db, - string? schemaName, - string viewName, - string newViewName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var view = await GetViewAsync(db, schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false); - - if (view == null || string.IsNullOrWhiteSpace(view.Definition)) - { - return false; - } - - await DropViewIfExistsAsync(db, schemaName, viewName, tx, cancellationToken) - .ConfigureAwait(false); - - await CreateViewIfNotExistsAsync( - db, - schemaName, - newViewName, - view.Definition, - tx, - cancellationToken - ) - .ConfigureAwait(false); - - return true; - } -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Providers.Base; + +public abstract partial class DatabaseMethodsBase +{ + /// + /// Checks if a view exists in the database. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The transaction. + /// The cancellation token. + /// True if the view exists, otherwise false. + public virtual async Task DoesViewExistAsync( + IDbConnection db, + string? schemaName, + string viewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return ( + await GetViewNamesAsync(db, schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false) + ).Count == 1; + } + + /// + /// Creates a view if it does not exist. + /// + /// The database connection. + /// The view details. + /// The transaction. + /// The cancellation token. + /// True if the view was created, otherwise false. + public virtual async Task CreateViewIfNotExistsAsync( + IDbConnection db, + DmView view, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await CreateViewIfNotExistsAsync( + db, + view.SchemaName, + view.ViewName, + view.Definition, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Creates a view if it does not exist. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The view definition. + /// The transaction. + /// The cancellation token. + /// True if the view was created, otherwise false. + public virtual async Task CreateViewIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string viewName, + string definition, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrEmpty(definition)) + { + throw new ArgumentException("View definition is required.", nameof(definition)); + } + + if ( + await DoesViewExistAsync(db, schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false) + ) + { + return false; + } + + var sql = SqlCreateView(schemaName, viewName, definition); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } + + /// + /// Gets a view from the database. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The transaction. + /// The cancellation token. + /// The view details, or null if the view does not exist. + public virtual async Task GetViewAsync( + IDbConnection db, + string? schemaName, + string viewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrEmpty(viewName)) + { + throw new ArgumentException("View name is required.", nameof(viewName)); + } + + return ( + await GetViewsAsync(db, schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false) + ).SingleOrDefault(); + } + + /// + /// Gets the names of views from the database. + /// + /// The database connection. + /// The schema name. + /// The view name filter. + /// The transaction. + /// The cancellation token. + /// A list of view names. + public virtual async Task> GetViewNamesAsync( + IDbConnection db, + string? schemaName, + string? viewNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var (sql, parameters) = SqlGetViewNames(schemaName, viewNameFilter); + return await QueryAsync( + db, + sql, + parameters, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Gets views from the database. + /// + /// The database connection. + /// The schema name. + /// The view name filter. + /// The transaction. + /// The cancellation token. + /// A list of views. + public virtual async Task> GetViewsAsync( + IDbConnection db, + string? schemaName, + string? viewNameFilter = null, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var (sql, parameters) = SqlGetViews(schemaName, viewNameFilter); + var views = await QueryAsync( + db, + sql, + parameters, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + foreach (var view in views) + { + view.Definition = NormalizeViewDefinition(view.Definition); + } + return views; + } + + /// + /// Drops a view if it exists. + /// + /// The database connection. + /// The schema name. + /// The view name. + /// The transaction. + /// The cancellation token. + /// True if the view was dropped, otherwise false. + public virtual async Task DropViewIfExistsAsync( + IDbConnection db, + string? schemaName, + string viewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if ( + !await DoesViewExistAsync(db, schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false) + ) + { + return false; + } + + var sql = SqlDropView(schemaName, viewName); + + await ExecuteAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + + return true; + } + + /// + /// Renames a view if it exists. + /// + /// The database connection. + /// The schema name. + /// The current view name. + /// The new view name. + /// The transaction. + /// The cancellation token. + /// True if the view was renamed, otherwise false. + public virtual async Task RenameViewIfExistsAsync( + IDbConnection db, + string? schemaName, + string viewName, + string newViewName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var view = await GetViewAsync(db, schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false); + + if (view == null || string.IsNullOrWhiteSpace(view.Definition)) + { + return false; + } + + await DropViewIfExistsAsync(db, schemaName, viewName, tx, cancellationToken) + .ConfigureAwait(false); + + await CreateViewIfNotExistsAsync( + db, + schemaName, + newViewName, + view.Definition, + tx, + cancellationToken + ) + .ConfigureAwait(false); + + return true; + } +} diff --git a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.cs b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.cs similarity index 94% rename from src/DapperMatic/Providers/Base/DatabaseMethodsBase.cs rename to src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.cs index 424eaff..9a66ce5 100644 --- a/src/DapperMatic/Providers/Base/DatabaseMethodsBase.cs +++ b/src/MJCZone.DapperMatic/Providers/Base/DatabaseMethodsBase.cs @@ -1,8 +1,8 @@ using System.Data; using Dapper; -using DapperMatic.Interfaces; +using MJCZone.DapperMatic.Interfaces; -namespace DapperMatic.Providers.Base; +namespace MJCZone.DapperMatic.Providers.Base; /// public abstract class DatabaseMethodsBase : DatabaseMethodsBase @@ -227,7 +227,7 @@ public virtual string GetSchemaQualifiedIdentifierName(string? schemaName, strin /// /// The name. /// The normalized name. - public virtual string NormalizeName(string name) + protected virtual string NormalizeName(string name) { return name.ToAlphaNumeric("_"); } @@ -356,7 +356,10 @@ protected virtual string GetQuotedIdentifier(string identifier) /// The identifiers. /// The union string. /// The quoted compound identifier. - protected virtual string GetQuotedCompoundIdentifier(string[] identifiers, string joinCharacter = ".") + protected virtual string GetQuotedCompoundIdentifier( + string[] identifiers, + string joinCharacter = "." + ) { return string.Join( joinCharacter, @@ -383,6 +386,7 @@ protected virtual string ToSafeString(string text, string allowedSpecialChars = /// The LIKE string. protected virtual string ToLikeString(string text, string allowedSpecialChars = "-_.*") { - return text.ToAlphaNumeric(allowedSpecialChars).Replace("*", "%", StringComparison.OrdinalIgnoreCase); + return text.ToAlphaNumeric(allowedSpecialChars) + .Replace("*", "%", StringComparison.OrdinalIgnoreCase); } } diff --git a/src/DapperMatic/Providers/DatabaseMethodsFactoryBase.cs b/src/MJCZone.DapperMatic/Providers/DatabaseMethodsFactoryBase.cs similarity index 93% rename from src/DapperMatic/Providers/DatabaseMethodsFactoryBase.cs rename to src/MJCZone.DapperMatic/Providers/DatabaseMethodsFactoryBase.cs index fedf9e4..e5724ed 100644 --- a/src/DapperMatic/Providers/DatabaseMethodsFactoryBase.cs +++ b/src/MJCZone.DapperMatic/Providers/DatabaseMethodsFactoryBase.cs @@ -1,8 +1,8 @@ using System.Collections.Concurrent; using System.Data; -using DapperMatic.Interfaces; +using MJCZone.DapperMatic.Interfaces; -namespace DapperMatic.Providers; +namespace MJCZone.DapperMatic.Providers; /// /// Provides a base class for creating database methods factories. diff --git a/src/DapperMatic/Providers/DatabaseMethodsProvider.cs b/src/MJCZone.DapperMatic/Providers/DatabaseMethodsProvider.cs similarity index 94% rename from src/DapperMatic/Providers/DatabaseMethodsProvider.cs rename to src/MJCZone.DapperMatic/Providers/DatabaseMethodsProvider.cs index 080e236..fdce588 100644 --- a/src/DapperMatic/Providers/DatabaseMethodsProvider.cs +++ b/src/MJCZone.DapperMatic/Providers/DatabaseMethodsProvider.cs @@ -1,8 +1,8 @@ using System.Collections.Concurrent; using System.Data; -using DapperMatic.Interfaces; +using MJCZone.DapperMatic.Interfaces; -namespace DapperMatic.Providers; +namespace MJCZone.DapperMatic.Providers; /// /// Provides methods for registering and retrieving database method factories. diff --git a/src/DapperMatic/Providers/DbProviderTypeMapBase.cs b/src/MJCZone.DapperMatic/Providers/DbProviderTypeMapBase.cs similarity index 96% rename from src/DapperMatic/Providers/DbProviderTypeMapBase.cs rename to src/MJCZone.DapperMatic/Providers/DbProviderTypeMapBase.cs index 4e3265b..a44ca53 100644 --- a/src/DapperMatic/Providers/DbProviderTypeMapBase.cs +++ b/src/MJCZone.DapperMatic/Providers/DbProviderTypeMapBase.cs @@ -1,9 +1,9 @@ using System.Collections; using System.Collections.Concurrent; using System.Reflection; -using DapperMatic.Converters; +using MJCZone.DapperMatic.Converters; -namespace DapperMatic.Providers; +namespace MJCZone.DapperMatic.Providers; // Add RegisterSqlTypeToDotnetTypeDescriptorConverter method to allow for custom type mappings // Add RegisterDotnetTypeDescriptorToSqlTypeConverter method to allow for custom type mappings diff --git a/src/DapperMatic/Providers/DbProviderUtils.cs b/src/MJCZone.DapperMatic/Providers/DbProviderUtils.cs similarity index 96% rename from src/DapperMatic/Providers/DbProviderUtils.cs rename to src/MJCZone.DapperMatic/Providers/DbProviderUtils.cs index fedd51f..9d8bc3a 100644 --- a/src/DapperMatic/Providers/DbProviderUtils.cs +++ b/src/MJCZone.DapperMatic/Providers/DbProviderUtils.cs @@ -1,128 +1,128 @@ -using System.Text.RegularExpressions; - -namespace DapperMatic.Providers; - -/// -/// Utility class for generating database constraint and index names. -/// -public static partial class DbProviderUtils -{ - /// - /// Generates a check constraint name. - /// - /// The name of the table. - /// The name of the column. - /// The generated check constraint name. - public static string GenerateCheckConstraintName(string tableName, string columnName) - { - return "ck".ToRawIdentifier(tableName, columnName); - } - - /// - /// Generates a default constraint name. - /// - /// The name of the table. - /// The name of the column. - /// The generated default constraint name. - public static string GenerateDefaultConstraintName(string tableName, string columnName) - { - return "df".ToRawIdentifier(tableName, columnName); - } - - /// - /// Generates a unique constraint name. - /// - /// The name of the table. - /// The names of the columns. - /// The generated unique constraint name. - public static string GenerateUniqueConstraintName(string tableName, params string[] columnNames) - { - return "uc".ToRawIdentifier([tableName, .. columnNames]); - } - - /// - /// Generates a primary key constraint name. - /// - /// The name of the table. - /// The names of the columns. - /// The generated primary key constraint name. - public static string GeneratePrimaryKeyConstraintName( - string tableName, - params string[] columnNames - ) - { - return "pk".ToRawIdentifier([tableName, .. columnNames]); - } - - /// - /// Generates an index name. - /// - /// The name of the table. - /// The names of the columns. - /// The generated index name. - public static string GenerateIndexName(string tableName, params string[] columnNames) - { - return "ix".ToRawIdentifier([tableName, .. columnNames]); - } - - /// - /// Generates a foreign key constraint name. - /// - /// The name of the table. - /// The name of the column. - /// The name of the referenced table. - /// The name of the referenced column. - /// The generated foreign key constraint name. - public static string GenerateForeignKeyConstraintName( - string tableName, - string columnName, - string refTableName, - string refColumnName - ) - { - return "fk".ToRawIdentifier(tableName, columnName, refTableName, refColumnName); - } - - /// - /// Generates a foreign key constraint name. - /// - /// The name of the table. - /// The names of the columns. - /// The name of the referenced table. - /// The names of the referenced columns. - /// The generated foreign key constraint name. - public static string GenerateForeignKeyConstraintName( - string tableName, - string[] columnNames, - string refTableName, - string[] refColumnNames - ) - { - return "fk".ToRawIdentifier([tableName, .. columnNames, refTableName, .. refColumnNames]); - } - - [GeneratedRegex(@"\d+(\.\d+)+")] - private static partial Regex VersionPatternRegex(); - -#pragma warning disable SA1201 // Elements should appear in the correct order - private static readonly Regex VersionPattern = VersionPatternRegex(); -#pragma warning restore SA1201 // Elements should appear in the correct order - - /// - /// Extracts the version from a version string. - /// - /// The version string. - /// The extracted version. - /// Thrown when the version cannot be extracted. - internal static Version ExtractVersionFromVersionString(string versionString) - { - var m = VersionPattern.Match(versionString); - var version = m.Value; - return Version.TryParse(version, out var vs) - ? vs - : throw new ArgumentException( - $"Could not extract version from: {versionString}", - nameof(versionString) - ); - } -} +using System.Text.RegularExpressions; + +namespace MJCZone.DapperMatic.Providers; + +/// +/// Utility class for generating database constraint and index names. +/// +public static partial class DbProviderUtils +{ + /// + /// Generates a check constraint name. + /// + /// The name of the table. + /// The name of the column. + /// The generated check constraint name. + public static string GenerateCheckConstraintName(string tableName, string columnName) + { + return "ck".ToRawIdentifier(tableName, columnName); + } + + /// + /// Generates a default constraint name. + /// + /// The name of the table. + /// The name of the column. + /// The generated default constraint name. + public static string GenerateDefaultConstraintName(string tableName, string columnName) + { + return "df".ToRawIdentifier(tableName, columnName); + } + + /// + /// Generates a unique constraint name. + /// + /// The name of the table. + /// The names of the columns. + /// The generated unique constraint name. + public static string GenerateUniqueConstraintName(string tableName, params string[] columnNames) + { + return "uc".ToRawIdentifier([tableName, .. columnNames]); + } + + /// + /// Generates a primary key constraint name. + /// + /// The name of the table. + /// The names of the columns. + /// The generated primary key constraint name. + public static string GeneratePrimaryKeyConstraintName( + string tableName, + params string[] columnNames + ) + { + return "pk".ToRawIdentifier([tableName, .. columnNames]); + } + + /// + /// Generates an index name. + /// + /// The name of the table. + /// The names of the columns. + /// The generated index name. + public static string GenerateIndexName(string tableName, params string[] columnNames) + { + return "ix".ToRawIdentifier([tableName, .. columnNames]); + } + + /// + /// Generates a foreign key constraint name. + /// + /// The name of the table. + /// The name of the column. + /// The name of the referenced table. + /// The name of the referenced column. + /// The generated foreign key constraint name. + public static string GenerateForeignKeyConstraintName( + string tableName, + string columnName, + string refTableName, + string refColumnName + ) + { + return "fk".ToRawIdentifier(tableName, columnName, refTableName, refColumnName); + } + + /// + /// Generates a foreign key constraint name. + /// + /// The name of the table. + /// The names of the columns. + /// The name of the referenced table. + /// The names of the referenced columns. + /// The generated foreign key constraint name. + public static string GenerateForeignKeyConstraintName( + string tableName, + string[] columnNames, + string refTableName, + string[] refColumnNames + ) + { + return "fk".ToRawIdentifier([tableName, .. columnNames, refTableName, .. refColumnNames]); + } + + [GeneratedRegex(@"\d+(\.\d+)+")] + private static partial Regex VersionPatternRegex(); + +#pragma warning disable SA1201 // Elements should appear in the correct order + private static readonly Regex VersionPattern = VersionPatternRegex(); +#pragma warning restore SA1201 // Elements should appear in the correct order + + /// + /// Extracts the version from a version string. + /// + /// The version string. + /// The extracted version. + /// Thrown when the version cannot be extracted. + internal static Version ExtractVersionFromVersionString(string versionString) + { + var m = VersionPattern.Match(versionString); + var version = m.Value; + return Version.TryParse(version, out var vs) + ? vs + : throw new ArgumentException( + $"Could not extract version from: {versionString}", + nameof(versionString) + ); + } +} diff --git a/src/DapperMatic/Providers/IDbProviderTypeMap.cs b/src/MJCZone.DapperMatic/Providers/IDbProviderTypeMap.cs similarity index 96% rename from src/DapperMatic/Providers/IDbProviderTypeMap.cs rename to src/MJCZone.DapperMatic/Providers/IDbProviderTypeMap.cs index 1dfda8b..167b67d 100644 --- a/src/DapperMatic/Providers/IDbProviderTypeMap.cs +++ b/src/MJCZone.DapperMatic/Providers/IDbProviderTypeMap.cs @@ -1,55 +1,55 @@ -namespace DapperMatic.Providers; - -/// -/// Represents a mapping between .NET types and SQL types. -/// -public interface IDbProviderTypeMap -{ - /// - /// Converts the SQL type name to a .NET type with appropriate type property - /// descriptors, such as length, precision, and scale among other things. - /// - /// The sql type name including the length, precision, and/or scale (e.g., nvarchar(255), varchar(max), decimal(16,4), etc...) - /// A corresponding .NET type descriptor object, or null. - /// true/false. - bool TryGetDotnetTypeDescriptorMatchingFullSqlTypeName( - string sqlTypeName, - out DotnetTypeDescriptor? dotnetTypeDescriptor - ); - - /// - /// Converts the SQL type descriptor to a .NET type with appropriate type property - /// descriptors, such as length, precision, and scale among other things. - /// - /// The sql type descriptor including the length, precision, and/or scale among other things. - /// A corresponding .NET type descriptor object, or null. - /// true/false. - bool TryGetDotnetTypeDescriptorMatchingFullSqlTypeName( - SqlTypeDescriptor sqlTypeDescriptor, - out DotnetTypeDescriptor? dotnetTypeDescriptor - ); - - /// - /// Converts the .NET type to a SQL type with appropriate type property - /// descriptors, such as length, precision, and scale among other things. - /// - /// The .NET type to convert to a SQL type. - /// A corresponding SQL type descriptor object, or null. - /// true/false. - bool TryGetProviderSqlTypeMatchingDotnetType( - Type type, - out SqlTypeDescriptor? sqlTypeDescriptor - ); - - /// - /// Converts the .NET type descriptor to a SQL type with appropriate type property - /// descriptors, such as length, precision, and scale among other things. - /// - /// The .NET type descriptor to convert to a SQL type. - /// A corresponding SQL type descriptor object, or null. - /// true/false. - bool TryGetProviderSqlTypeMatchingDotnetType( - DotnetTypeDescriptor dotnetTypeDescriptor, - out SqlTypeDescriptor? sqlTypeDescriptor - ); -} +namespace MJCZone.DapperMatic.Providers; + +/// +/// Represents a mapping between .NET types and SQL types. +/// +public interface IDbProviderTypeMap +{ + /// + /// Converts the SQL type name to a .NET type with appropriate type property + /// descriptors, such as length, precision, and scale among other things. + /// + /// The sql type name including the length, precision, and/or scale (e.g., nvarchar(255), varchar(max), decimal(16,4), etc...) + /// A corresponding .NET type descriptor object, or null. + /// true/false. + bool TryGetDotnetTypeDescriptorMatchingFullSqlTypeName( + string sqlTypeName, + out DotnetTypeDescriptor? dotnetTypeDescriptor + ); + + /// + /// Converts the SQL type descriptor to a .NET type with appropriate type property + /// descriptors, such as length, precision, and scale among other things. + /// + /// The sql type descriptor including the length, precision, and/or scale among other things. + /// A corresponding .NET type descriptor object, or null. + /// true/false. + bool TryGetDotnetTypeDescriptorMatchingFullSqlTypeName( + SqlTypeDescriptor sqlTypeDescriptor, + out DotnetTypeDescriptor? dotnetTypeDescriptor + ); + + /// + /// Converts the .NET type to a SQL type with appropriate type property + /// descriptors, such as length, precision, and scale among other things. + /// + /// The .NET type to convert to a SQL type. + /// A corresponding SQL type descriptor object, or null. + /// true/false. + bool TryGetProviderSqlTypeMatchingDotnetType( + Type type, + out SqlTypeDescriptor? sqlTypeDescriptor + ); + + /// + /// Converts the .NET type descriptor to a SQL type with appropriate type property + /// descriptors, such as length, precision, and scale among other things. + /// + /// The .NET type descriptor to convert to a SQL type. + /// A corresponding SQL type descriptor object, or null. + /// true/false. + bool TryGetProviderSqlTypeMatchingDotnetType( + DotnetTypeDescriptor dotnetTypeDescriptor, + out SqlTypeDescriptor? sqlTypeDescriptor + ); +} diff --git a/src/DapperMatic/Providers/MySql/IMySqlMethods.cs b/src/MJCZone.DapperMatic/Providers/MySql/IMySqlMethods.cs similarity index 58% rename from src/DapperMatic/Providers/MySql/IMySqlMethods.cs rename to src/MJCZone.DapperMatic/Providers/MySql/IMySqlMethods.cs index 583d983..c8b8cd0 100644 --- a/src/DapperMatic/Providers/MySql/IMySqlMethods.cs +++ b/src/MJCZone.DapperMatic/Providers/MySql/IMySqlMethods.cs @@ -1,8 +1,8 @@ -using DapperMatic.Interfaces; - -namespace DapperMatic.Providers.MySql; - -/// -/// Provides MySQL specific database methods. -/// -public interface IMySqlMethods : IDatabaseMethods { } +using MJCZone.DapperMatic.Interfaces; + +namespace MJCZone.DapperMatic.Providers.MySql; + +/// +/// Provides MySQL specific database methods. +/// +public interface IMySqlMethods : IDatabaseMethods { } diff --git a/src/DapperMatic/Providers/MySql/MySqlMethods.Strings.cs b/src/MJCZone.DapperMatic/Providers/MySql/MySqlMethods.Strings.cs similarity index 95% rename from src/DapperMatic/Providers/MySql/MySqlMethods.Strings.cs rename to src/MJCZone.DapperMatic/Providers/MySql/MySqlMethods.Strings.cs index 62ba469..1166aee 100644 --- a/src/DapperMatic/Providers/MySql/MySqlMethods.Strings.cs +++ b/src/MJCZone.DapperMatic/Providers/MySql/MySqlMethods.Strings.cs @@ -1,7 +1,7 @@ using System.Diagnostics.CodeAnalysis; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.MySql; +namespace MJCZone.DapperMatic.Providers.MySql; public partial class MySqlMethods { @@ -16,7 +16,7 @@ public partial class MySqlMethods /// The column definition. /// The database version. /// The SQL string for inline column name and type. - protected override string SqlInlineColumnNameAndType(DxColumn column, Version dbVersion) + protected override string SqlInlineColumnNameAndType(DmColumn column, Version dbVersion) { var nameAndType = base.SqlInlineColumnNameAndType(column, dbVersion); @@ -52,7 +52,7 @@ protected override string SqlInlineColumnNameAndType(DxColumn column, Version db /// Indicates whether to use table constraint. /// The SQL string for inline primary key column constraint. protected override string SqlInlinePrimaryKeyColumnConstraint( - DxColumn column, + DmColumn column, string constraintName, out bool useTableConstraint ) @@ -69,7 +69,7 @@ out bool useTableConstraint /// /// The column definition. /// The SQL string for inline primary key auto-increment column constraint. - protected override string SqlInlinePrimaryKeyAutoIncrementColumnConstraint(DxColumn column) + protected override string SqlInlinePrimaryKeyAutoIncrementColumnConstraint(DmColumn column) { return "AUTO_INCREMENT"; } @@ -142,9 +142,9 @@ protected override string SqlInlineForeignKeyColumnConstraint( string? schemaName, string constraintName, string referencedTableName, - DxOrderedColumn referencedColumn, - DxForeignKeyAction? onDelete, - DxForeignKeyAction? onUpdate, + DmOrderedColumn referencedColumn, + DmForeignKeyAction? onDelete, + DmForeignKeyAction? onUpdate, out bool useTableConstraint ) { diff --git a/src/DapperMatic/Providers/MySql/MySqlMethods.Tables.cs b/src/MJCZone.DapperMatic/Providers/MySql/MySqlMethods.Tables.cs similarity index 92% rename from src/DapperMatic/Providers/MySql/MySqlMethods.Tables.cs rename to src/MJCZone.DapperMatic/Providers/MySql/MySqlMethods.Tables.cs index 234a057..283a53d 100644 --- a/src/DapperMatic/Providers/MySql/MySqlMethods.Tables.cs +++ b/src/MJCZone.DapperMatic/Providers/MySql/MySqlMethods.Tables.cs @@ -1,8 +1,8 @@ using System.Data; using System.Text.RegularExpressions; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.MySql; +namespace MJCZone.DapperMatic.Providers.MySql; public partial class MySqlMethods { @@ -15,7 +15,7 @@ public partial class MySqlMethods /// The database transaction. /// The cancellation token. /// A list of tables. - public override async Task> GetTablesAsync( + public override async Task> GetTablesAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, @@ -151,7 +151,7 @@ string columns_desc_csv ) .Select(c => { - return new DxDefaultConstraint( + return new DmDefaultConstraint( DefaultSchema, c.table_name, c.column_name, @@ -167,19 +167,19 @@ string columns_desc_csv { var columnNames = t.columns_csv.Split(", "); var columnDescs = t.columns_desc_csv.Split(", "); - return new DxPrimaryKeyConstraint( + return new DmPrimaryKeyConstraint( DefaultSchema, t.table_name, DbProviderUtils.GeneratePrimaryKeyConstraintName(t.table_name, columnNames), columnNames .Select( (c, i) => - new DxOrderedColumn( + new DmOrderedColumn( c, columnDescs[i] .Equals("DESC", StringComparison.OrdinalIgnoreCase) - ? DxColumnOrder.Descending - : DxColumnOrder.Ascending + ? DmColumnOrder.Descending + : DmColumnOrder.Ascending ) ) .ToArray() @@ -192,19 +192,19 @@ string columns_desc_csv { var columnNames = t.columns_csv.Split(", "); var columnDescs = t.columns_desc_csv.Split(", "); - return new DxUniqueConstraint( + return new DmUniqueConstraint( DefaultSchema, t.table_name, t.constraint_name, columnNames .Select( (c, i) => - new DxOrderedColumn( + new DmOrderedColumn( c, columnDescs[i] .Equals("DESC", StringComparison.OrdinalIgnoreCase) - ? DxColumnOrder.Descending - : DxColumnOrder.Ascending + ? DmColumnOrder.Descending + : DmColumnOrder.Ascending ) ) .ToArray() @@ -269,13 +269,13 @@ string referenced_column_name }) .Select(gb => { - return new DxForeignKeyConstraint( + return new DmForeignKeyConstraint( DefaultSchema, gb.Key.table_name, gb.Key.constraint_name, - gb.Select(c => new DxOrderedColumn(c.column_name)).ToArray(), + gb.Select(c => new DmOrderedColumn(c.column_name)).ToArray(), gb.Key.referenced_table_name, - gb.Select(c => new DxOrderedColumn(c.referenced_column_name)).ToArray(), + gb.Select(c => new DmOrderedColumn(c.referenced_column_name)).ToArray(), gb.Key.delete_rule.ToForeignKeyAction(), gb.Key.update_rule.ToForeignKeyAction() ); @@ -284,7 +284,7 @@ string referenced_column_name // the table CHECK_CONSTRAINTS only exists starting MySQL 8.0.16 and MariaDB 10.2.1 // resolve issue for MySQL 5.0.12+ - DxCheckConstraint[] allCheckConstraints = []; + DmCheckConstraint[] allCheckConstraints = []; if (await SupportsCheckConstraintsAsync(db, tx, cancellationToken).ConfigureAwait(false)) { var checkConstraintsSql = $""" @@ -359,7 +359,7 @@ string check_expression t.column_name = columnName; } } - return new DxCheckConstraint( + return new DmCheckConstraint( DefaultSchema, t.table_name, t.column_name, @@ -379,7 +379,7 @@ string check_expression ) .ConfigureAwait(false); - var tables = new List(); + var tables = new List(); foreach ( var tableColumns in columnResults.GroupBy(r => new { r.schema_name, r.table_name }) @@ -406,7 +406,7 @@ string check_expression .Where(t => t.TableName.Equals(tableName, StringComparison.OrdinalIgnoreCase)) .ToArray(); - var columns = new List(); + var columns = new List(); foreach (var tableColumn in tableColumns) { var columnIsUniqueViaUniqueConstraintOrIndex = @@ -459,7 +459,7 @@ string check_expression var dotnetTypeDescriptor = GetDotnetTypeFromSqlType(tableColumn.data_type_complete); - var column = new DxColumn( + var column = new DmColumn( tableColumn.schema_name, tableColumn.table_name, tableColumn.column_name, @@ -520,7 +520,7 @@ string check_expression columns.Add(column); } - var table = new DxTable( + var table = new DmTable( schemaName, tableName, [.. columns], @@ -547,7 +547,7 @@ string check_expression /// The database transaction. /// The cancellation token. /// A list of indexes. - protected override async Task> GetIndexesInternalAsync( + protected override async Task> GetIndexesInternalAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, @@ -618,7 +618,7 @@ string columns_desc_csv ) .ConfigureAwait(false); - var indexes = new List(); + var indexes = new List(); foreach (var indexResult in indexResults) { @@ -634,17 +634,17 @@ string columns_desc_csv var columns = columnNames .Select( (c, i) => - new DxOrderedColumn( + new DmOrderedColumn( c, columnDirections[i].Equals("desc", StringComparison.OrdinalIgnoreCase) - ? DxColumnOrder.Descending - : DxColumnOrder.Ascending + ? DmColumnOrder.Descending + : DmColumnOrder.Ascending ) ) .ToArray(); indexes.Add( - new DxIndex( + new DmIndex( DefaultSchema, indexResult.table_name, indexResult.index_name, diff --git a/src/DapperMatic/Providers/MySql/MySqlMethods.cs b/src/MJCZone.DapperMatic/Providers/MySql/MySqlMethods.cs similarity index 95% rename from src/DapperMatic/Providers/MySql/MySqlMethods.cs rename to src/MJCZone.DapperMatic/Providers/MySql/MySqlMethods.cs index 601e3d7..39f5760 100644 --- a/src/DapperMatic/Providers/MySql/MySqlMethods.cs +++ b/src/MJCZone.DapperMatic/Providers/MySql/MySqlMethods.cs @@ -1,92 +1,92 @@ -using System.Data; -using DapperMatic.Providers.Base; - -namespace DapperMatic.Providers.MySql; - -/// -/// Provides MySQL specific database methods. -/// -public partial class MySqlMethods : DatabaseMethodsBase, IMySqlMethods -{ - /// - /// Initializes a new instance of the class. - /// - internal MySqlMethods() - : base(DbProviderType.MySql) { } - - /// - /// Gets the characters used for quoting identifiers. - /// - public override char[] QuoteChars => ['`']; - - /// - /// Gets the default schema. - /// - protected override string DefaultSchema => string.Empty; - - /// - /// Checks if the database supports check constraints. - /// - /// The database connection. - /// The transaction to use, or null. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating support for check constraints. - public override async Task SupportsCheckConstraintsAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - var versionStr = - await ExecuteScalarAsync( - db, - "SELECT VERSION()", - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false) ?? string.Empty; - var version = DbProviderUtils.ExtractVersionFromVersionString(versionStr); - return ( - versionStr.Contains("MariaDB", StringComparison.OrdinalIgnoreCase) - && version > new Version(10, 2, 1) - ) - || version >= new Version(8, 0, 16); - } - - /// - /// Checks if the database supports ordered keys in constraints. - /// - /// The database connection. - /// The transaction to use, or null. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating support for ordered keys in constraints. - public override Task SupportsOrderedKeysInConstraintsAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return Task.FromResult(false); - } - - /// - /// Gets the database version. - /// - /// The database connection. - /// The transaction to use, or null. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the database version. - public override async Task GetDatabaseVersionAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - // sample output: 8.0.27, 8.4.2 - var sql = @"SELECT VERSION()"; - var versionString = - await ExecuteScalarAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false) ?? string.Empty; - return DbProviderUtils.ExtractVersionFromVersionString(versionString); - } -} +using System.Data; +using MJCZone.DapperMatic.Providers.Base; + +namespace MJCZone.DapperMatic.Providers.MySql; + +/// +/// Provides MySQL specific database methods. +/// +public partial class MySqlMethods : DatabaseMethodsBase, IMySqlMethods +{ + /// + /// Initializes a new instance of the class. + /// + internal MySqlMethods() + : base(DbProviderType.MySql) { } + + /// + /// Gets the characters used for quoting identifiers. + /// + public override char[] QuoteChars => ['`']; + + /// + /// Gets the default schema. + /// + protected override string DefaultSchema => string.Empty; + + /// + /// Checks if the database supports check constraints. + /// + /// The database connection. + /// The transaction to use, or null. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating support for check constraints. + public override async Task SupportsCheckConstraintsAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + var versionStr = + await ExecuteScalarAsync( + db, + "SELECT VERSION()", + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false) ?? string.Empty; + var version = DbProviderUtils.ExtractVersionFromVersionString(versionStr); + return ( + versionStr.Contains("MariaDB", StringComparison.OrdinalIgnoreCase) + && version > new Version(10, 2, 1) + ) + || version >= new Version(8, 0, 16); + } + + /// + /// Checks if the database supports ordered keys in constraints. + /// + /// The database connection. + /// The transaction to use, or null. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating support for ordered keys in constraints. + public override Task SupportsOrderedKeysInConstraintsAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return Task.FromResult(false); + } + + /// + /// Gets the database version. + /// + /// The database connection. + /// The transaction to use, or null. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the database version. + public override async Task GetDatabaseVersionAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + // sample output: 8.0.27, 8.4.2 + var sql = @"SELECT VERSION()"; + var versionString = + await ExecuteScalarAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false) ?? string.Empty; + return DbProviderUtils.ExtractVersionFromVersionString(versionString); + } +} diff --git a/src/DapperMatic/Providers/MySql/MySqlMethodsFactory.cs b/src/MJCZone.DapperMatic/Providers/MySql/MySqlMethodsFactory.cs similarity index 91% rename from src/DapperMatic/Providers/MySql/MySqlMethodsFactory.cs rename to src/MJCZone.DapperMatic/Providers/MySql/MySqlMethodsFactory.cs index b729f8b..88c0804 100644 --- a/src/DapperMatic/Providers/MySql/MySqlMethodsFactory.cs +++ b/src/MJCZone.DapperMatic/Providers/MySql/MySqlMethodsFactory.cs @@ -1,35 +1,35 @@ -using System.Data; -using DapperMatic.Interfaces; - -namespace DapperMatic.Providers.MySql; - -/// -/// Factory class for creating MySQL specific database methods. -/// -public class MySqlMethodsFactory : DatabaseMethodsFactoryBase -{ - /// - /// Determines whether the specified database connection supports custom connection settings. - /// - /// The database connection. - /// true if the connection supports custom settings; otherwise, false. - public virtual bool SupportsConnectionCustom(IDbConnection db) => false; - - /// - /// Determines whether the specified database connection is supported. - /// - /// The database connection. - /// true if the connection is supported; otherwise, false. - public override bool SupportsConnection(IDbConnection db) => - SupportsConnectionCustom(db) - || (db.GetType().FullName ?? string.Empty).Contains( - "mysql", - StringComparison.OrdinalIgnoreCase - ); - - /// - /// Creates the core database methods for MySQL. - /// - /// An instance of for MySQL. - protected override IDatabaseMethods CreateMethodsCore() => new MySqlMethods(); -} +using System.Data; +using MJCZone.DapperMatic.Interfaces; + +namespace MJCZone.DapperMatic.Providers.MySql; + +/// +/// Factory class for creating MySQL specific database methods. +/// +public class MySqlMethodsFactory : DatabaseMethodsFactoryBase +{ + /// + /// Determines whether the specified database connection supports custom connection settings. + /// + /// The database connection. + /// true if the connection supports custom settings; otherwise, false. + public virtual bool SupportsConnectionCustom(IDbConnection db) => false; + + /// + /// Determines whether the specified database connection is supported. + /// + /// The database connection. + /// true if the connection is supported; otherwise, false. + public override bool SupportsConnection(IDbConnection db) => + SupportsConnectionCustom(db) + || (db.GetType().FullName ?? string.Empty).Contains( + "mysql", + StringComparison.OrdinalIgnoreCase + ); + + /// + /// Creates the core database methods for MySQL. + /// + /// An instance of for MySQL. + protected override IDatabaseMethods CreateMethodsCore() => new MySqlMethods(); +} diff --git a/src/DapperMatic/Providers/MySql/MySqlProviderTypeMap.cs b/src/MJCZone.DapperMatic/Providers/MySql/MySqlProviderTypeMap.cs similarity index 97% rename from src/DapperMatic/Providers/MySql/MySqlProviderTypeMap.cs rename to src/MJCZone.DapperMatic/Providers/MySql/MySqlProviderTypeMap.cs index 91371f7..0e3cad6 100644 --- a/src/DapperMatic/Providers/MySql/MySqlProviderTypeMap.cs +++ b/src/MJCZone.DapperMatic/Providers/MySql/MySqlProviderTypeMap.cs @@ -6,9 +6,9 @@ using System.Text.Json; using System.Text.Json.Nodes; using System.Xml.Linq; -using DapperMatic.Converters; +using MJCZone.DapperMatic.Converters; -namespace DapperMatic.Providers.MySql +namespace MJCZone.DapperMatic.Providers.MySql { /// /// Provides type mapping for MySQL database provider. diff --git a/src/DapperMatic/Providers/MySql/MySqlTypes.cs b/src/MJCZone.DapperMatic/Providers/MySql/MySqlTypes.cs similarity index 96% rename from src/DapperMatic/Providers/MySql/MySqlTypes.cs rename to src/MJCZone.DapperMatic/Providers/MySql/MySqlTypes.cs index f3cd3f2..66fd8b3 100644 --- a/src/DapperMatic/Providers/MySql/MySqlTypes.cs +++ b/src/MJCZone.DapperMatic/Providers/MySql/MySqlTypes.cs @@ -1,197 +1,197 @@ -using System.Diagnostics.CodeAnalysis; - -namespace DapperMatic.Providers.MySql; - -/// -/// Provides constants for MySQL data types. -/// -[SuppressMessage( - "ReSharper", - "InconsistentNaming", - Justification = "Constants are named to match MySQL documentation." -)] -public static class MySqlTypes -{ - /// Represents the MySQL boolean type. - public const string sql_bool = "bool"; - - /// Represents the MySQL boolean type. - public const string sql_boolean = "boolean"; - - // integers - - /// Represents the MySQL bit type. - public const string sql_bit = "bit"; - - /// Represents the MySQL tinyint type. - public const string sql_tinyint = "tinyint"; - - /// Represents the MySQL unsigned tinyint type. - public const string sql_tinyint_unsigned = "tinyint unsigned"; - - /// Represents the MySQL smallint type. - public const string sql_smallint = "smallint"; - - /// Represents the MySQL unsigned smallint type. - public const string sql_smallint_unsigned = "smallint unsigned"; - - /// Represents the MySQL mediumint type. - public const string sql_mediumint = "mediumint"; - - /// Represents the MySQL unsigned mediumint type. - public const string sql_mediumint_unsigned = "mediumint unsigned"; - - /// Represents the MySQL integer type. - public const string sql_integer = "integer"; - - /// Represents the MySQL unsigned integer type. - public const string sql_integer_unsigned = "integer unsigned"; - - /// Represents the MySQL int type. - public const string sql_int = "int"; - - /// Represents the MySQL unsigned int type. - public const string sql_int_unsigned = "int unsigned"; - - /// Represents the MySQL bigint type. - public const string sql_bigint = "bigint"; - - /// Represents the MySQL unsigned bigint type. - public const string sql_bigint_unsigned = "bigint unsigned"; - - /// Represents the MySQL serial type. - public const string sql_serial = "serial"; - - // real - - /// Represents the MySQL decimal type. - public const string sql_decimal = "decimal"; - - /// Represents the MySQL decimal type. - public const string sql_dec = "dec"; - - /// Represents the MySQL fixed type. - public const string sql_fixed = "fixed"; - - /// Represents the MySQL numeric type. - public const string sql_numeric = "numeric"; - - /// Represents the MySQL float type. - public const string sql_float = "float"; - - /// Represents the MySQL real type. - public const string sql_real = "real"; - - /// Represents the MySQL double precision type. - public const string sql_double_precision = "double precision"; - - /// Represents the MySQL unsigned double precision type. - public const string sql_double_precision_unsigned = "double precision unsigned"; - - /// Represents the MySQL double type. - public const string sql_double = "double"; - - /// Represents the MySQL unsigned double type. - public const string sql_double_unsigned = "double unsigned"; - - // datetime - - /// Represents the MySQL datetime type. - public const string sql_datetime = "datetime"; - - /// Represents the MySQL timestamp type. - public const string sql_timestamp = "timestamp"; - - /// Represents the MySQL time type. - public const string sql_time = "time"; - - /// Represents the MySQL date type. - public const string sql_date = "date"; - - /// Represents the MySQL year type. - public const string sql_year = "year"; - - // text - - /// Represents the MySQL char type. - public const string sql_char = "char"; - - /// Represents the MySQL varchar type. - public const string sql_varchar = "varchar"; - - /// Represents the MySQL long varchar type. - public const string sql_long_varchar = "long varchar"; - - /// Represents the MySQL tinytext type. - public const string sql_tinytext = "tinytext"; - - /// Represents the MySQL mediumtext type. - public const string sql_mediumtext = "mediumtext"; - - /// Represents the MySQL text type. - public const string sql_text = "text"; - - /// Represents the MySQL longtext type. - public const string sql_longtext = "longtext"; - - /// Represents the MySQL enum type. - public const string sql_enum = "enum"; - - /// Represents the MySQL set type. - public const string sql_set = "set"; // csv of strings 'a,b,c' - - /// Represents the MySQL json type. - public const string sql_json = "json"; - - // binary - - /// Represents the MySQL binary type. - public const string sql_binary = "binary"; - - /// Represents the MySQL varbinary type. - public const string sql_varbinary = "varbinary"; - - /// Represents the MySQL long varbinary type. - public const string sql_long_varbinary = "long varbinary"; - - /// Represents the MySQL tinyblob type. - public const string sql_tinyblob = "tinyblob"; - - /// Represents the MySQL blob type. - public const string sql_blob = "blob"; - - /// Represents the MySQL mediumblob type. - public const string sql_mediumblob = "mediumblob"; - - /// Represents the MySQL longblob type. - public const string sql_longblob = "longblob"; - - // geometry - - /// Represents the MySQL geometry type. - public const string sql_geometry = "geometry"; - - /// Represents the MySQL point type. - public const string sql_point = "point"; - - /// Represents the MySQL linestring type. - public const string sql_linestring = "linestring"; - - /// Represents the MySQL polygon type. - public const string sql_polygon = "polygon"; - - /// Represents the MySQL multipoint type. - public const string sql_multipoint = "multipoint"; - - /// Represents the MySQL multilinestring type. - public const string sql_multilinestring = "multilinestring"; - - /// Represents the MySQL multipolygon type. - public const string sql_multipolygon = "multipolygon"; - - /// Represents the MySQL geomcollection type. - public const string sql_geomcollection = "geomcollection"; - - /// Represents the MySQL geometrycollection type. - public const string sql_geometrycollection = "geometrycollection"; -} +using System.Diagnostics.CodeAnalysis; + +namespace MJCZone.DapperMatic.Providers.MySql; + +/// +/// Provides constants for MySQL data types. +/// +[SuppressMessage( + "ReSharper", + "InconsistentNaming", + Justification = "Constants are named to match MySQL documentation." +)] +public static class MySqlTypes +{ + /// Represents the MySQL boolean type. + public const string sql_bool = "bool"; + + /// Represents the MySQL boolean type. + public const string sql_boolean = "boolean"; + + // integers + + /// Represents the MySQL bit type. + public const string sql_bit = "bit"; + + /// Represents the MySQL tinyint type. + public const string sql_tinyint = "tinyint"; + + /// Represents the MySQL unsigned tinyint type. + public const string sql_tinyint_unsigned = "tinyint unsigned"; + + /// Represents the MySQL smallint type. + public const string sql_smallint = "smallint"; + + /// Represents the MySQL unsigned smallint type. + public const string sql_smallint_unsigned = "smallint unsigned"; + + /// Represents the MySQL mediumint type. + public const string sql_mediumint = "mediumint"; + + /// Represents the MySQL unsigned mediumint type. + public const string sql_mediumint_unsigned = "mediumint unsigned"; + + /// Represents the MySQL integer type. + public const string sql_integer = "integer"; + + /// Represents the MySQL unsigned integer type. + public const string sql_integer_unsigned = "integer unsigned"; + + /// Represents the MySQL int type. + public const string sql_int = "int"; + + /// Represents the MySQL unsigned int type. + public const string sql_int_unsigned = "int unsigned"; + + /// Represents the MySQL bigint type. + public const string sql_bigint = "bigint"; + + /// Represents the MySQL unsigned bigint type. + public const string sql_bigint_unsigned = "bigint unsigned"; + + /// Represents the MySQL serial type. + public const string sql_serial = "serial"; + + // real + + /// Represents the MySQL decimal type. + public const string sql_decimal = "decimal"; + + /// Represents the MySQL decimal type. + public const string sql_dec = "dec"; + + /// Represents the MySQL fixed type. + public const string sql_fixed = "fixed"; + + /// Represents the MySQL numeric type. + public const string sql_numeric = "numeric"; + + /// Represents the MySQL float type. + public const string sql_float = "float"; + + /// Represents the MySQL real type. + public const string sql_real = "real"; + + /// Represents the MySQL double precision type. + public const string sql_double_precision = "double precision"; + + /// Represents the MySQL unsigned double precision type. + public const string sql_double_precision_unsigned = "double precision unsigned"; + + /// Represents the MySQL double type. + public const string sql_double = "double"; + + /// Represents the MySQL unsigned double type. + public const string sql_double_unsigned = "double unsigned"; + + // datetime + + /// Represents the MySQL datetime type. + public const string sql_datetime = "datetime"; + + /// Represents the MySQL timestamp type. + public const string sql_timestamp = "timestamp"; + + /// Represents the MySQL time type. + public const string sql_time = "time"; + + /// Represents the MySQL date type. + public const string sql_date = "date"; + + /// Represents the MySQL year type. + public const string sql_year = "year"; + + // text + + /// Represents the MySQL char type. + public const string sql_char = "char"; + + /// Represents the MySQL varchar type. + public const string sql_varchar = "varchar"; + + /// Represents the MySQL long varchar type. + public const string sql_long_varchar = "long varchar"; + + /// Represents the MySQL tinytext type. + public const string sql_tinytext = "tinytext"; + + /// Represents the MySQL mediumtext type. + public const string sql_mediumtext = "mediumtext"; + + /// Represents the MySQL text type. + public const string sql_text = "text"; + + /// Represents the MySQL longtext type. + public const string sql_longtext = "longtext"; + + /// Represents the MySQL enum type. + public const string sql_enum = "enum"; + + /// Represents the MySQL set type. + public const string sql_set = "set"; // csv of strings 'a,b,c' + + /// Represents the MySQL json type. + public const string sql_json = "json"; + + // binary + + /// Represents the MySQL binary type. + public const string sql_binary = "binary"; + + /// Represents the MySQL varbinary type. + public const string sql_varbinary = "varbinary"; + + /// Represents the MySQL long varbinary type. + public const string sql_long_varbinary = "long varbinary"; + + /// Represents the MySQL tinyblob type. + public const string sql_tinyblob = "tinyblob"; + + /// Represents the MySQL blob type. + public const string sql_blob = "blob"; + + /// Represents the MySQL mediumblob type. + public const string sql_mediumblob = "mediumblob"; + + /// Represents the MySQL longblob type. + public const string sql_longblob = "longblob"; + + // geometry + + /// Represents the MySQL geometry type. + public const string sql_geometry = "geometry"; + + /// Represents the MySQL point type. + public const string sql_point = "point"; + + /// Represents the MySQL linestring type. + public const string sql_linestring = "linestring"; + + /// Represents the MySQL polygon type. + public const string sql_polygon = "polygon"; + + /// Represents the MySQL multipoint type. + public const string sql_multipoint = "multipoint"; + + /// Represents the MySQL multilinestring type. + public const string sql_multilinestring = "multilinestring"; + + /// Represents the MySQL multipolygon type. + public const string sql_multipolygon = "multipolygon"; + + /// Represents the MySQL geomcollection type. + public const string sql_geomcollection = "geomcollection"; + + /// Represents the MySQL geometrycollection type. + public const string sql_geometrycollection = "geometrycollection"; +} diff --git a/src/DapperMatic/Providers/PostgreSql/IPostgreSqlMethods.cs b/src/MJCZone.DapperMatic/Providers/PostgreSql/IPostgreSqlMethods.cs similarity index 59% rename from src/DapperMatic/Providers/PostgreSql/IPostgreSqlMethods.cs rename to src/MJCZone.DapperMatic/Providers/PostgreSql/IPostgreSqlMethods.cs index da75b9d..83b53ce 100644 --- a/src/DapperMatic/Providers/PostgreSql/IPostgreSqlMethods.cs +++ b/src/MJCZone.DapperMatic/Providers/PostgreSql/IPostgreSqlMethods.cs @@ -1,8 +1,8 @@ -using DapperMatic.Interfaces; - -namespace DapperMatic.Providers.PostgreSql; - -/// -/// Interface for PostgreSQL specific database methods. -/// -public interface IPostgreSqlMethods : IDatabaseMethods { } +using MJCZone.DapperMatic.Interfaces; + +namespace MJCZone.DapperMatic.Providers.PostgreSql; + +/// +/// Interface for PostgreSQL specific database methods. +/// +public interface IPostgreSqlMethods : IDatabaseMethods { } diff --git a/src/DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Strings.cs b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Strings.cs similarity index 95% rename from src/DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Strings.cs rename to src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Strings.cs index f34c203..3ffce09 100644 --- a/src/DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Strings.cs +++ b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Strings.cs @@ -1,338 +1,338 @@ -using DapperMatic.Models; - -namespace DapperMatic.Providers.PostgreSql; - -public partial class PostgreSqlMethods -{ - #region Schema Strings - - /// - /// Generates SQL to get schema names with an optional filter. - /// - /// Optional filter for schema names. - /// SQL query and parameters. - protected override (string sql, object parameters) SqlGetSchemaNames( - string? schemaNameFilter = null - ) - { - var where = string.IsNullOrWhiteSpace(schemaNameFilter) - ? string.Empty - : ToLikeString(schemaNameFilter); - - var sql = $""" - SELECT DISTINCT nspname - FROM pg_catalog.pg_namespace - {(string.IsNullOrWhiteSpace(where) ? string.Empty : "WHERE lower(nspname) LIKE @where")} - ORDER BY nspname - """; - - return (sql, new { where }); - } - - /// - /// Generates SQL to drop a schema. - /// - /// Name of the schema to drop. - /// SQL query string. - protected override string SqlDropSchema(string schemaName) - { - return $"DROP SCHEMA IF EXISTS {NormalizeSchemaName(schemaName)} CASCADE"; - } - #endregion // Schema Strings - - #region Table Strings - - /// - /// Generates SQL to define column nullability. - /// - /// Column definition. - /// SQL fragment for column nullability. - protected override string SqlInlineColumnNullable(DxColumn column) - { - // serial columns are implicitly NOT NULL - if ( - column.IsNullable - && (column.GetProviderDataType(ProviderType) ?? string.Empty).Contains( - "serial", - StringComparison.OrdinalIgnoreCase - ) - ) - { - return string.Empty; - } - - return column.IsNullable && !column.IsUnique && !column.IsPrimaryKey - ? " NULL" - : " NOT NULL"; - } - - /// - /// Generates SQL for primary key auto-increment constraint. - /// - /// Column definition. - /// SQL fragment for primary key auto-increment constraint. - protected override string SqlInlinePrimaryKeyAutoIncrementColumnConstraint(DxColumn column) - { - if ( - (column.GetProviderDataType(ProviderType) ?? string.Empty).Contains( - "serial", - StringComparison.OrdinalIgnoreCase - ) - ) - { - return string.Empty; - } - - return "GENERATED BY DEFAULT AS IDENTITY"; - } - - /// - /// Generates SQL to check if a table exists. - /// - /// Schema name. - /// Table name. - /// SQL query and parameters. - protected override (string sql, object parameters) SqlDoesTableExist( - string? schemaName, - string tableName - ) - { - var sql = $""" - SELECT COUNT(*) - FROM pg_class pgc - JOIN pg_catalog.pg_namespace n ON n.oid = pgc.relnamespace - WHERE - pgc.relkind = 'r' - {( - string.IsNullOrWhiteSpace(schemaName) ? string.Empty : " AND lower(n.nspname) = @schemaName" - )} - AND lower(pgc.relname) = @tableName - """; - - return ( - sql, - new - { - schemaName = NormalizeSchemaName(schemaName), - tableName = NormalizeName(tableName), - } - ); - } - - /// - /// Generates SQL to get table names with optional filters. - /// - /// Schema name. - /// Optional filter for table names. - /// SQL query and parameters. - protected override (string sql, object parameters) SqlGetTableNames( - string? schemaName, - string? tableNameFilter = null - ) - { - var where = string.IsNullOrWhiteSpace(tableNameFilter) - ? string.Empty - : ToLikeString(tableNameFilter); - - var sql = $""" - SELECT TABLE_NAME - FROM INFORMATION_SCHEMA.TABLES - WHERE - TABLE_TYPE = 'BASE TABLE' - AND lower(TABLE_SCHEMA) = @schemaName - AND TABLE_NAME NOT IN ('spatial_ref_sys', 'geometry_columns', 'geography_columns', 'raster_columns', 'raster_overviews') - {( - string.IsNullOrWhiteSpace(where) ? null : " AND lower(TABLE_NAME) LIKE @where" - )} - ORDER BY TABLE_NAME - """; - - return ( - sql, - new - { - schemaName = NormalizeSchemaName(schemaName).ToLowerInvariant(), - where = where.ToLowerInvariant(), - } - ); - } - - /// - /// Generates SQL to drop a table. - /// - /// Schema name. - /// Table name. - /// SQL query string. - protected override string SqlDropTable(string? schemaName, string tableName) - { - return $"DROP TABLE IF EXISTS {GetSchemaQualifiedIdentifierName(schemaName, tableName)} CASCADE"; - } - #endregion // Table Strings - - #region Column Strings - #endregion // Column Strings - - #region Check Constraint Strings - #endregion // Check Constraint Strings - - #region Default Constraint Strings - - /// - /// Generates SQL to add a default constraint to a table. - /// - /// Schema name. - /// Table name. - /// Column name. - /// Constraint name. - /// Default expression. - /// SQL query string. - protected override string SqlAlterTableAddDefaultConstraint( - string? schemaName, - string tableName, - string columnName, - string constraintName, - string expression - ) - { - var schemaQualifiedTableName = GetSchemaQualifiedIdentifierName(schemaName, tableName); - - return $""" - - ALTER TABLE {schemaQualifiedTableName} - ALTER COLUMN {NormalizeName(columnName)} SET DEFAULT {expression} - - """; - } - - /// - /// Generates SQL to drop a default constraint from a table. - /// - /// Schema name. - /// Table name. - /// Column name. - /// Constraint name. - /// SQL query string. - protected override string SqlDropDefaultConstraint( - string? schemaName, - string tableName, - string columnName, - string constraintName - ) - { - return $"ALTER TABLE {GetSchemaQualifiedIdentifierName(schemaName, tableName)} ALTER COLUMN {NormalizeName(columnName)} DROP DEFAULT"; - } - #endregion // Default Constraint Strings - - #region Primary Key Strings - #endregion // Primary Key Strings - - #region Unique Constraint Strings - #endregion // Unique Constraint Strings - - #region Foreign Key Constraint Strings - #endregion // Foreign Key Constraint Strings - - #region Index Strings - - /// - /// Generates SQL to drop an index. - /// - /// Schema name. - /// Table name. - /// Index name. - /// SQL query string. - protected override string SqlDropIndex(string? schemaName, string tableName, string indexName) - { - return $"DROP INDEX {GetSchemaQualifiedIdentifierName(schemaName, indexName)} CASCADE"; - } - #endregion // Index Strings - - #region View Strings - - /// - /// Generates SQL to get view names with optional filters. - /// - /// Schema name. - /// Optional filter for view names. - /// SQL query and parameters. - protected override (string sql, object parameters) SqlGetViewNames( - string? schemaName, - string? viewNameFilter = null - ) - { - var where = string.IsNullOrWhiteSpace(viewNameFilter) - ? string.Empty - : ToLikeString(viewNameFilter); - - var sql = $""" - - SELECT - v.viewname as ViewName - from pg_views as v - where - v.schemaname not like 'pg_%' - and v.schemaname != 'information_schema' - and v.viewname not in ('geography_columns', 'geometry_columns', 'raster_columns', 'raster_overviews') - and lower(v.schemaname) = @schemaName - {( - string.IsNullOrWhiteSpace(where) ? string.Empty : " AND lower(v.viewname) LIKE @where" - )} - ORDER BY - v.schemaname, v.viewname - """; - - return ( - sql, - new - { - schemaName = NormalizeSchemaName(schemaName).ToLowerInvariant(), - where = where.ToLowerInvariant(), - } - ); - } - - /// - /// Generates SQL to get views with optional filters. - /// - /// Schema name. - /// Optional filter for view names. - /// SQL query and parameters. - protected override (string sql, object parameters) SqlGetViews( - string? schemaName, - string? viewNameFilter - ) - { - var where = string.IsNullOrWhiteSpace(viewNameFilter) - ? string.Empty - : ToLikeString(viewNameFilter); - - var sql = $""" - - SELECT - v.schemaname as SchemaName, - v.viewname as ViewName, - v.definition as Definition - from pg_views as v - where - v.schemaname not like 'pg_%' - and v.schemaname != 'information_schema' - and v.viewname not in ('geography_columns', 'geometry_columns', 'raster_columns', 'raster_overviews') - and lower(v.schemaname) = @schemaName - {( - string.IsNullOrWhiteSpace(where) ? string.Empty : " AND lower(v.viewname) LIKE @where" - )} - ORDER BY - v.schemaname, v.viewname - """; - - return ( - sql, - new - { - schemaName = NormalizeSchemaName(schemaName).ToLowerInvariant(), - where = where.ToLowerInvariant(), - } - ); - } - #endregion // View Strings -} +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Providers.PostgreSql; + +public partial class PostgreSqlMethods +{ + #region Schema Strings + + /// + /// Generates SQL to get schema names with an optional filter. + /// + /// Optional filter for schema names. + /// SQL query and parameters. + protected override (string sql, object parameters) SqlGetSchemaNames( + string? schemaNameFilter = null + ) + { + var where = string.IsNullOrWhiteSpace(schemaNameFilter) + ? string.Empty + : ToLikeString(schemaNameFilter); + + var sql = $""" + SELECT DISTINCT nspname + FROM pg_catalog.pg_namespace + {(string.IsNullOrWhiteSpace(where) ? string.Empty : "WHERE lower(nspname) LIKE @where")} + ORDER BY nspname + """; + + return (sql, new { where }); + } + + /// + /// Generates SQL to drop a schema. + /// + /// Name of the schema to drop. + /// SQL query string. + protected override string SqlDropSchema(string schemaName) + { + return $"DROP SCHEMA IF EXISTS {NormalizeSchemaName(schemaName)} CASCADE"; + } + #endregion // Schema Strings + + #region Table Strings + + /// + /// Generates SQL to define column nullability. + /// + /// Column definition. + /// SQL fragment for column nullability. + protected override string SqlInlineColumnNullable(DmColumn column) + { + // serial columns are implicitly NOT NULL + if ( + column.IsNullable + && (column.GetProviderDataType(ProviderType) ?? string.Empty).Contains( + "serial", + StringComparison.OrdinalIgnoreCase + ) + ) + { + return string.Empty; + } + + return column.IsNullable && !column.IsUnique && !column.IsPrimaryKey + ? " NULL" + : " NOT NULL"; + } + + /// + /// Generates SQL for primary key auto-increment constraint. + /// + /// Column definition. + /// SQL fragment for primary key auto-increment constraint. + protected override string SqlInlinePrimaryKeyAutoIncrementColumnConstraint(DmColumn column) + { + if ( + (column.GetProviderDataType(ProviderType) ?? string.Empty).Contains( + "serial", + StringComparison.OrdinalIgnoreCase + ) + ) + { + return string.Empty; + } + + return "GENERATED BY DEFAULT AS IDENTITY"; + } + + /// + /// Generates SQL to check if a table exists. + /// + /// Schema name. + /// Table name. + /// SQL query and parameters. + protected override (string sql, object parameters) SqlDoesTableExist( + string? schemaName, + string tableName + ) + { + var sql = $""" + SELECT COUNT(*) + FROM pg_class pgc + JOIN pg_catalog.pg_namespace n ON n.oid = pgc.relnamespace + WHERE + pgc.relkind = 'r' + {( + string.IsNullOrWhiteSpace(schemaName) ? string.Empty : " AND lower(n.nspname) = @schemaName" + )} + AND lower(pgc.relname) = @tableName + """; + + return ( + sql, + new + { + schemaName = NormalizeSchemaName(schemaName), + tableName = NormalizeName(tableName), + } + ); + } + + /// + /// Generates SQL to get table names with optional filters. + /// + /// Schema name. + /// Optional filter for table names. + /// SQL query and parameters. + protected override (string sql, object parameters) SqlGetTableNames( + string? schemaName, + string? tableNameFilter = null + ) + { + var where = string.IsNullOrWhiteSpace(tableNameFilter) + ? string.Empty + : ToLikeString(tableNameFilter); + + var sql = $""" + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE + TABLE_TYPE = 'BASE TABLE' + AND lower(TABLE_SCHEMA) = @schemaName + AND TABLE_NAME NOT IN ('spatial_ref_sys', 'geometry_columns', 'geography_columns', 'raster_columns', 'raster_overviews') + {( + string.IsNullOrWhiteSpace(where) ? null : " AND lower(TABLE_NAME) LIKE @where" + )} + ORDER BY TABLE_NAME + """; + + return ( + sql, + new + { + schemaName = NormalizeSchemaName(schemaName).ToLowerInvariant(), + where = where.ToLowerInvariant(), + } + ); + } + + /// + /// Generates SQL to drop a table. + /// + /// Schema name. + /// Table name. + /// SQL query string. + protected override string SqlDropTable(string? schemaName, string tableName) + { + return $"DROP TABLE IF EXISTS {GetSchemaQualifiedIdentifierName(schemaName, tableName)} CASCADE"; + } + #endregion // Table Strings + + #region Column Strings + #endregion // Column Strings + + #region Check Constraint Strings + #endregion // Check Constraint Strings + + #region Default Constraint Strings + + /// + /// Generates SQL to add a default constraint to a table. + /// + /// Schema name. + /// Table name. + /// Column name. + /// Constraint name. + /// Default expression. + /// SQL query string. + protected override string SqlAlterTableAddDefaultConstraint( + string? schemaName, + string tableName, + string columnName, + string constraintName, + string expression + ) + { + var schemaQualifiedTableName = GetSchemaQualifiedIdentifierName(schemaName, tableName); + + return $""" + + ALTER TABLE {schemaQualifiedTableName} + ALTER COLUMN {NormalizeName(columnName)} SET DEFAULT {expression} + + """; + } + + /// + /// Generates SQL to drop a default constraint from a table. + /// + /// Schema name. + /// Table name. + /// Column name. + /// Constraint name. + /// SQL query string. + protected override string SqlDropDefaultConstraint( + string? schemaName, + string tableName, + string columnName, + string constraintName + ) + { + return $"ALTER TABLE {GetSchemaQualifiedIdentifierName(schemaName, tableName)} ALTER COLUMN {NormalizeName(columnName)} DROP DEFAULT"; + } + #endregion // Default Constraint Strings + + #region Primary Key Strings + #endregion // Primary Key Strings + + #region Unique Constraint Strings + #endregion // Unique Constraint Strings + + #region Foreign Key Constraint Strings + #endregion // Foreign Key Constraint Strings + + #region Index Strings + + /// + /// Generates SQL to drop an index. + /// + /// Schema name. + /// Table name. + /// Index name. + /// SQL query string. + protected override string SqlDropIndex(string? schemaName, string tableName, string indexName) + { + return $"DROP INDEX {GetSchemaQualifiedIdentifierName(schemaName, indexName)} CASCADE"; + } + #endregion // Index Strings + + #region View Strings + + /// + /// Generates SQL to get view names with optional filters. + /// + /// Schema name. + /// Optional filter for view names. + /// SQL query and parameters. + protected override (string sql, object parameters) SqlGetViewNames( + string? schemaName, + string? viewNameFilter = null + ) + { + var where = string.IsNullOrWhiteSpace(viewNameFilter) + ? string.Empty + : ToLikeString(viewNameFilter); + + var sql = $""" + + SELECT + v.viewname as ViewName + from pg_views as v + where + v.schemaname not like 'pg_%' + and v.schemaname != 'information_schema' + and v.viewname not in ('geography_columns', 'geometry_columns', 'raster_columns', 'raster_overviews') + and lower(v.schemaname) = @schemaName + {( + string.IsNullOrWhiteSpace(where) ? string.Empty : " AND lower(v.viewname) LIKE @where" + )} + ORDER BY + v.schemaname, v.viewname + """; + + return ( + sql, + new + { + schemaName = NormalizeSchemaName(schemaName).ToLowerInvariant(), + where = where.ToLowerInvariant(), + } + ); + } + + /// + /// Generates SQL to get views with optional filters. + /// + /// Schema name. + /// Optional filter for view names. + /// SQL query and parameters. + protected override (string sql, object parameters) SqlGetViews( + string? schemaName, + string? viewNameFilter + ) + { + var where = string.IsNullOrWhiteSpace(viewNameFilter) + ? string.Empty + : ToLikeString(viewNameFilter); + + var sql = $""" + + SELECT + v.schemaname as SchemaName, + v.viewname as ViewName, + v.definition as Definition + from pg_views as v + where + v.schemaname not like 'pg_%' + and v.schemaname != 'information_schema' + and v.viewname not in ('geography_columns', 'geometry_columns', 'raster_columns', 'raster_overviews') + and lower(v.schemaname) = @schemaName + {( + string.IsNullOrWhiteSpace(where) ? string.Empty : " AND lower(v.viewname) LIKE @where" + )} + ORDER BY + v.schemaname, v.viewname + """; + + return ( + sql, + new + { + schemaName = NormalizeSchemaName(schemaName).ToLowerInvariant(), + where = where.ToLowerInvariant(), + } + ); + } + #endregion // View Strings +} diff --git a/src/DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Tables.cs b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Tables.cs similarity index 93% rename from src/DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Tables.cs rename to src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Tables.cs index 63c4076..a17816c 100644 --- a/src/DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Tables.cs +++ b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethods.Tables.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.PostgreSql; +namespace MJCZone.DapperMatic.Providers.PostgreSql; public partial class PostgreSqlMethods { @@ -13,8 +13,8 @@ public partial class PostgreSqlMethods /// The table name filter. /// The database transaction. /// The cancellation token. - /// A list of objects representing the tables and their metadata. - public override async Task> GetTablesAsync( + /// A list of objects representing the tables and their metadata. + public override async Task> GetTablesAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, @@ -192,7 +192,7 @@ int column_ordinal ) .ConfigureAwait(false); - var tables = new List(); + var tables = new List(); foreach ( var tableColumnResults in columnResults.GroupBy(r => new @@ -221,7 +221,7 @@ int column_ordinal .column_ordinals_csv.Split(',') .Select(r => { - return new DxOrderedColumn( + return new DmOrderedColumn( tableColumnResults .First(c => c.column_ordinal == int.Parse(r)) .column_name @@ -232,7 +232,7 @@ int column_ordinal .referenced_column_ordinals_csv.Split(',') .Select(r => { - return new DxOrderedColumn( + return new DmOrderedColumn( referencedColumnsResults .First(c => c.table_name.Equals( @@ -245,7 +245,7 @@ int column_ordinal ); }) .ToArray(); - return new DxForeignKeyConstraint( + return new DmForeignKeyConstraint( row.schema_name, row.table_name, row.constraint_name, @@ -277,7 +277,7 @@ int column_ordinal .column_name; }) .ToArray(); - return new DxCheckConstraint( + return new DmCheckConstraint( c.schema_name, c.table_name, columns.Length == 1 ? columns[0] : null, @@ -295,7 +295,7 @@ int column_ordinal ) .Select(c => { - return new DxDefaultConstraint( + return new DmDefaultConstraint( c.schema_name, c.table_name, c.column_name, @@ -315,14 +315,14 @@ int column_ordinal .column_ordinals_csv.Split(',') .Select(r => { - return new DxOrderedColumn( + return new DmOrderedColumn( tableColumnResults .First(c => c.column_ordinal == int.Parse(r)) .column_name ); }) .ToArray(); - return new DxPrimaryKeyConstraint( + return new DmPrimaryKeyConstraint( row.schema_name, row.table_name, row.constraint_name, @@ -339,14 +339,14 @@ int column_ordinal .column_ordinals_csv.Split(',') .Select(r => { - return new DxOrderedColumn( + return new DmOrderedColumn( tableColumnResults .First(c => c.column_ordinal == int.Parse(r)) .column_name ); }) .ToArray(); - return new DxUniqueConstraint( + return new DmUniqueConstraint( row.schema_name, row.table_name, row.constraint_name, @@ -364,7 +364,7 @@ int column_ordinal ) .ToArray(); - var columns = new List(); + var columns = new List(); foreach (var tableColumn in tableColumnResults) { var columnIsUniqueViaUniqueConstraintOrIndex = @@ -422,7 +422,7 @@ int column_ordinal : tableColumn.data_type ); - var column = new DxColumn( + var column = new DmColumn( tableColumn.schema_name, tableColumn.table_name, tableColumn.column_name, @@ -475,7 +475,7 @@ int column_ordinal columns.Add(column); } - var table = new DxTable( + var table = new DmTable( schemaName, tableName, [.. columns], @@ -501,8 +501,8 @@ int column_ordinal /// The index name filter. /// The database transaction. /// The cancellation token. - /// A list of objects representing the indexes and their metadata. - protected override async Task> GetIndexesInternalAsync( + /// A list of objects representing the indexes and their metadata. + protected override async Task> GetIndexesInternalAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, @@ -593,7 +593,7 @@ string columns_csv ) .ConfigureAwait(false); - var indexes = new List(); + var indexes = new List(); foreach (var ir in indexResults) { var columns = ir @@ -607,14 +607,14 @@ string columns_csv ) .First(); var isDescending = c.Contains("desc", StringComparison.OrdinalIgnoreCase); - return new DxOrderedColumn( + return new DmOrderedColumn( columnName, - isDescending ? DxColumnOrder.Descending : DxColumnOrder.Ascending + isDescending ? DmColumnOrder.Descending : DmColumnOrder.Ascending ); }) .ToArray(); - var index = new DxIndex( + var index = new DmIndex( ir.schema_name, ir.table_name, ir.index_name, diff --git a/src/DapperMatic/Providers/PostgreSql/PostgreSqlMethods.cs b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethods.cs similarity index 93% rename from src/DapperMatic/Providers/PostgreSql/PostgreSqlMethods.cs rename to src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethods.cs index 604f5bf..ef1a85d 100644 --- a/src/DapperMatic/Providers/PostgreSql/PostgreSqlMethods.cs +++ b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethods.cs @@ -1,97 +1,97 @@ -using System.Data; -using DapperMatic.Providers.Base; - -namespace DapperMatic.Providers.PostgreSql; - -/// -/// Provides PostgreSQL specific database methods. -/// -public partial class PostgreSqlMethods - : DatabaseMethodsBase, - IPostgreSqlMethods -{ - private static string _defaultSchema = "public"; - - /// - /// Initializes a new instance of the class. - /// - internal PostgreSqlMethods() - : base(DbProviderType.PostgreSql) { } - - /// - /// Gets the characters used for quoting identifiers. - /// - public override char[] QuoteChars => ['"']; - - /// - /// Gets the default schema. - /// - protected override string DefaultSchema => _defaultSchema; - - /// - /// Sets the default schema. - /// - /// The schema name. - public static void SetDefaultSchema(string schema) - { - _defaultSchema = schema; - } - - /// - /// Determines whether the database supports ordered keys in constraints. - /// - /// The database connection. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean value. - public override Task SupportsOrderedKeysInConstraintsAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return Task.FromResult(false); - } - - /// - /// Gets the database version. - /// - /// The database connection. - /// The transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains the database version. - public override async Task GetDatabaseVersionAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - // sample output: PostgreSQL 15.7 (Debian 15.7-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit - const string sql = "SELECT VERSION()"; - var versionString = - await ExecuteScalarAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false) ?? string.Empty; - return DbProviderUtils.ExtractVersionFromVersionString(versionString); - } - - /// - /// Normalizes the name to lowercase. - /// - /// The name to normalize. - /// The normalized name. - public override string NormalizeName(string name) - { - return base.NormalizeName(name).ToLowerInvariant(); - } - - /// - /// Converts the text to a LIKE string, normalizing to lowercase. - /// - /// The text to convert. - /// The allowed special characters. - /// The LIKE string. - protected override string ToLikeString(string text, string allowedSpecialChars = "-_.*") - { - return base.ToLikeString(text, allowedSpecialChars).ToLowerInvariant(); - } -} +using System.Data; +using MJCZone.DapperMatic.Providers.Base; + +namespace MJCZone.DapperMatic.Providers.PostgreSql; + +/// +/// Provides PostgreSQL specific database methods. +/// +public partial class PostgreSqlMethods + : DatabaseMethodsBase, + IPostgreSqlMethods +{ + private static string _defaultSchema = "public"; + + /// + /// Initializes a new instance of the class. + /// + internal PostgreSqlMethods() + : base(DbProviderType.PostgreSql) { } + + /// + /// Gets the characters used for quoting identifiers. + /// + public override char[] QuoteChars => ['"']; + + /// + /// Gets the default schema. + /// + protected override string DefaultSchema => _defaultSchema; + + /// + /// Sets the default schema. + /// + /// The schema name. + public static void SetDefaultSchema(string schema) + { + _defaultSchema = schema; + } + + /// + /// Determines whether the database supports ordered keys in constraints. + /// + /// The database connection. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean value. + public override Task SupportsOrderedKeysInConstraintsAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return Task.FromResult(false); + } + + /// + /// Gets the database version. + /// + /// The database connection. + /// The transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains the database version. + public override async Task GetDatabaseVersionAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + // sample output: PostgreSQL 15.7 (Debian 15.7-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit + const string sql = "SELECT VERSION()"; + var versionString = + await ExecuteScalarAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false) ?? string.Empty; + return DbProviderUtils.ExtractVersionFromVersionString(versionString); + } + + /// + /// Normalizes the name to lowercase. + /// + /// The name to normalize. + /// The normalized name. + protected override string NormalizeName(string name) + { + return base.NormalizeName(name).ToLowerInvariant(); + } + + /// + /// Converts the text to a LIKE string, normalizing to lowercase. + /// + /// The text to convert. + /// The allowed special characters. + /// The LIKE string. + protected override string ToLikeString(string text, string allowedSpecialChars = "-_.*") + { + return base.ToLikeString(text, allowedSpecialChars).ToLowerInvariant(); + } +} diff --git a/src/DapperMatic/Providers/PostgreSql/PostgreSqlMethodsFactory.cs b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethodsFactory.cs similarity index 92% rename from src/DapperMatic/Providers/PostgreSql/PostgreSqlMethodsFactory.cs rename to src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethodsFactory.cs index 4037585..b0b4ffc 100644 --- a/src/DapperMatic/Providers/PostgreSql/PostgreSqlMethodsFactory.cs +++ b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlMethodsFactory.cs @@ -1,39 +1,39 @@ -using System.Data; -using DapperMatic.Interfaces; - -namespace DapperMatic.Providers.PostgreSql; - -/// -/// Factory class for creating PostgreSQL specific database methods. -/// -public class PostgreSqlMethodsFactory : DatabaseMethodsFactoryBase -{ - /// - /// Determines whether the specified database connection supports custom PostgreSQL connection. - /// - /// The database connection. - /// true if the connection supports custom PostgreSQL connection; otherwise, false. - public virtual bool SupportsConnectionCustom(IDbConnection db) => false; - - /// - /// Determines whether the specified database connection is a PostgreSQL connection. - /// - /// The database connection. - /// true if the connection is a PostgreSQL connection; otherwise, false. - public override bool SupportsConnection(IDbConnection db) => - SupportsConnectionCustom(db) - || (db.GetType().FullName ?? string.Empty).Contains( - "pg", - StringComparison.OrdinalIgnoreCase - ) - || (db.GetType().FullName ?? string.Empty).Contains( - "postgres", - StringComparison.OrdinalIgnoreCase - ); - - /// - /// Creates the core PostgreSQL database methods. - /// - /// The PostgreSQL database methods. - protected override IDatabaseMethods CreateMethodsCore() => new PostgreSqlMethods(); -} +using System.Data; +using MJCZone.DapperMatic.Interfaces; + +namespace MJCZone.DapperMatic.Providers.PostgreSql; + +/// +/// Factory class for creating PostgreSQL specific database methods. +/// +public class PostgreSqlMethodsFactory : DatabaseMethodsFactoryBase +{ + /// + /// Determines whether the specified database connection supports custom PostgreSQL connection. + /// + /// The database connection. + /// true if the connection supports custom PostgreSQL connection; otherwise, false. + public virtual bool SupportsConnectionCustom(IDbConnection db) => false; + + /// + /// Determines whether the specified database connection is a PostgreSQL connection. + /// + /// The database connection. + /// true if the connection is a PostgreSQL connection; otherwise, false. + public override bool SupportsConnection(IDbConnection db) => + SupportsConnectionCustom(db) + || (db.GetType().FullName ?? string.Empty).Contains( + "pg", + StringComparison.OrdinalIgnoreCase + ) + || (db.GetType().FullName ?? string.Empty).Contains( + "postgres", + StringComparison.OrdinalIgnoreCase + ); + + /// + /// Creates the core PostgreSQL database methods. + /// + /// The PostgreSQL database methods. + protected override IDatabaseMethods CreateMethodsCore() => new PostgreSqlMethods(); +} diff --git a/src/DapperMatic/Providers/PostgreSql/PostgreSqlProviderTypeMap.cs b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlProviderTypeMap.cs similarity index 97% rename from src/DapperMatic/Providers/PostgreSql/PostgreSqlProviderTypeMap.cs rename to src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlProviderTypeMap.cs index 4df763f..5dee4a9 100644 --- a/src/DapperMatic/Providers/PostgreSql/PostgreSqlProviderTypeMap.cs +++ b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlProviderTypeMap.cs @@ -8,9 +8,9 @@ using System.Text.Json; using System.Text.Json.Nodes; using System.Xml.Linq; -using DapperMatic.Converters; +using MJCZone.DapperMatic.Converters; -namespace DapperMatic.Providers.PostgreSql; +namespace MJCZone.DapperMatic.Providers.PostgreSql; /// /// Provides a mapping of .NET types to PostgreSQL types. diff --git a/src/DapperMatic/Providers/PostgreSql/PostgreSqlTypes.cs b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlTypes.cs similarity index 96% rename from src/DapperMatic/Providers/PostgreSql/PostgreSqlTypes.cs rename to src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlTypes.cs index fe7a33c..57305cb 100644 --- a/src/DapperMatic/Providers/PostgreSql/PostgreSqlTypes.cs +++ b/src/MJCZone.DapperMatic/Providers/PostgreSql/PostgreSqlTypes.cs @@ -1,318 +1,318 @@ -using System.Diagnostics.CodeAnalysis; - -namespace DapperMatic.Providers.PostgreSql; - -/// -/// Provides constants for PostgreSQL data types. -/// -public static class PostgreSqlTypes -{ - // integers - - /// Represents the PostgreSQL smallint type. - public const string sql_smallint = "smallint"; - - /// Represents the PostgreSQL int2 type. - public const string sql_int2 = "int2"; - - /// Represents the PostgreSQL smallserial type. - public const string sql_smallserial = "smallserial"; - - /// Represents the PostgreSQL serial2 type. - public const string sql_serial2 = "serial2"; - - /// Represents the PostgreSQL integer type. - public const string sql_integer = "integer"; - - /// Represents the PostgreSQL int type. - public const string sql_int = "int"; - - /// Represents the PostgreSQL int4 type. - public const string sql_int4 = "int4"; - - /// Represents the PostgreSQL serial type. - public const string sql_serial = "serial"; - - /// Represents the PostgreSQL serial4 type. - public const string sql_serial4 = "serial4"; - - /// Represents the PostgreSQL bigint type. - public const string sql_bigint = "bigint"; - - /// Represents the PostgreSQL int8 type. - public const string sql_int8 = "int8"; - - /// Represents the PostgreSQL bigserial type. - public const string sql_bigserial = "bigserial"; - - /// Represents the PostgreSQL serial8 type. - public const string sql_serial8 = "serial8"; - - // real - - /// Represents the PostgreSQL float4 type. - public const string sql_float4 = "float4"; - - /// Represents the PostgreSQL real type. - public const string sql_real = "real"; - - /// Represents the PostgreSQL double precision type. - public const string sql_double_precision = "double precision"; - - /// Represents the PostgreSQL float8 type. - public const string sql_float8 = "float8"; - - /// Represents the PostgreSQL money type. - public const string sql_money = "money"; - - /// Represents the PostgreSQL numeric type. - public const string sql_numeric = "numeric"; - - /// Represents the PostgreSQL decimal type. - public const string sql_decimal = "decimal"; - - // bool - - /// Represents the PostgreSQL bool type. - public const string sql_bool = "bool"; - - /// Represents the PostgreSQL boolean type. - public const string sql_boolean = "boolean"; - - // datetime - - /// Represents the PostgreSQL date type. - public const string sql_date = "date"; - - /// Represents the PostgreSQL interval type. - public const string sql_interval = "interval"; - - /// Represents the PostgreSQL time without time zone type. - public const string sql_time_without_time_zone = "time without time zone"; - - /// Represents the PostgreSQL time type. - public const string sql_time = "time"; - - /// Represents the PostgreSQL time with time zone type. - public const string sql_time_with_time_zone = "time with time zone"; - - /// Represents the PostgreSQL timetz type. - public const string sql_timetz = "timetz"; - - /// Represents the PostgreSQL timestamp without time zone type. - public const string sql_timestamp_without_time_zone = "timestamp without time zone"; - - /// Represents the PostgreSQL timestamp type. - public const string sql_timestamp = "timestamp"; - - /// Represents the PostgreSQL timestamp with time zone type. - public const string sql_timestamp_with_time_zone = "timestamp with time zone"; - - /// Represents the PostgreSQL timestamptz type. - public const string sql_timestamptz = "timestamptz"; - - // text - - /// Represents the PostgreSQL bit type. - public const string sql_bit = "bit"; - - /// Represents the PostgreSQL bit varying type. - public const string sql_bit_varying = "bit varying"; - - /// Represents the PostgreSQL varbit type. - public const string sql_varbit = "varbit"; - - /// Represents the PostgreSQL character varying type. - public const string sql_character_varying = "character varying"; - - /// Represents the PostgreSQL varchar type. - public const string sql_varchar = "varchar"; - - /// Represents the PostgreSQL character type. - public const string sql_character = "character"; - - /// Represents the PostgreSQL char type. - public const string sql_char = "char"; - - /// Represents the PostgreSQL bpchar type. - public const string sql_bpchar = "bpchar"; - - /// Represents the PostgreSQL text type. - public const string sql_text = "text"; - - /// Represents the PostgreSQL name type. - public const string sql_name = "name"; - - /// Represents the PostgreSQL uuid type. - public const string sql_uuid = "uuid"; - - /// Represents the PostgreSQL json type. - public const string sql_json = "json"; - - /// Represents the PostgreSQL jsonb type. - public const string sql_jsonb = "jsonb"; - - /// Represents the PostgreSQL jsonpath type. - public const string sql_jsonpath = "jsonpath"; - - /// Represents the PostgreSQL xml type. - public const string sql_xml = "xml"; - - // binary - - /// Represents the PostgreSQL bytea type. - public const string sql_bytea = "bytea"; - - // geometry - - /// Represents the PostgreSQL box type. - public const string sql_box = "box"; - - /// Represents the PostgreSQL circle type. - public const string sql_circle = "circle"; - - /// Represents the PostgreSQL geography type. - public const string sql_geography = "geography"; - - /// Represents the PostgreSQL geometry type. - public const string sql_geometry = "geometry"; - - /// Represents the PostgreSQL line type. - public const string sql_line = "line"; - - /// Represents the PostgreSQL lseg type. - public const string sql_lseg = "lseg"; - - /// Represents the PostgreSQL path type. - public const string sql_path = "path"; - - /// Represents the PostgreSQL point type. - public const string sql_point = "point"; - - /// Represents the PostgreSQL polygon type. - public const string sql_polygon = "polygon"; - - // range types - - /// Represents the PostgreSQL datemultirange type. - public const string sql_datemultirange = "datemultirange"; - - /// Represents the PostgreSQL daterange type. - public const string sql_daterange = "daterange"; - - /// Represents the PostgreSQL int4multirange type. - public const string sql_int4multirange = "int4multirange"; - - /// Represents the PostgreSQL int4range type. - public const string sql_int4range = "int4range"; - - /// Represents the PostgreSQL int8multirange type. - public const string sql_int8multirange = "int8multirange"; - - /// Represents the PostgreSQL int8range type. - public const string sql_int8range = "int8range"; - - /// Represents the PostgreSQL nummultirange type. - public const string sql_nummultirange = "nummultirange"; - - /// Represents the PostgreSQL numrange type. - public const string sql_numrange = "numrange"; - - /// Represents the PostgreSQL tsmultirange type. - public const string sql_tsmultirange = "tsmultirange"; - - /// Represents the PostgreSQL tsrange type. - public const string sql_tsrange = "tsrange"; - - /// Represents the PostgreSQL tstzmultirange type. - public const string sql_tstzmultirange = "tstzmultirange"; - - /// Represents the PostgreSQL tstzrange type. - public const string sql_tstzrange = "tstzrange"; - - // other data types - - /// Represents the PostgreSQL cidr type. - public const string sql_cidr = "cidr"; - - /// Represents the PostgreSQL citext type. - public const string sql_citext = "citext"; - - /// Represents the PostgreSQL hstore type. - public const string sql_hstore = "hstore"; - - /// Represents the PostgreSQL inet type. - public const string sql_inet = "inet"; - - /// Represents the PostgreSQL int2vector type. - public const string sql_int2vector = "int2vector"; - - /// Represents the PostgreSQL lquery type. - public const string sql_lquery = "lquery"; - - /// Represents the PostgreSQL ltree type. - public const string sql_ltree = "ltree"; - - /// Represents the PostgreSQL ltxtquery type. - public const string sql_ltxtquery = "ltxtquery"; - - /// Represents the PostgreSQL macaddr type. - public const string sql_macaddr = "macaddr"; - - /// Represents the PostgreSQL macaddr8 type. - public const string sql_macaddr8 = "macaddr8"; - - /// Represents the PostgreSQL oid type. - public const string sql_oid = "oid"; - - /// Represents the PostgreSQL oidvector type. - public const string sql_oidvector = "oidvector"; - - /// Represents the PostgreSQL pg_lsn type. - public const string sql_pg_lsn = "pg_lsn"; - - /// Represents the PostgreSQL pg_snapshot type. - public const string sql_pg_snapshot = "pg_snapshot"; - - /// Represents the PostgreSQL refcursor type. - public const string sql_refcursor = "refcursor"; - - /// Represents the PostgreSQL regclass type. - public const string sql_regclass = "regclass"; - - /// Represents the PostgreSQL regcollation type. - public const string sql_regcollation = "regcollation"; - - /// Represents the PostgreSQL regconfig type. - public const string sql_regconfig = "regconfig"; - - /// Represents the PostgreSQL regdictionary type. - public const string sql_regdictionary = "regdictionary"; - - /// Represents the PostgreSQL regnamespace type. - public const string sql_regnamespace = "regnamespace"; - - /// Represents the PostgreSQL regrole type. - public const string sql_regrole = "regrole"; - - /// Represents the PostgreSQL regtype type. - public const string sql_regtype = "regtype"; - - /// Represents the PostgreSQL tid type. - public const string sql_tid = "tid"; - - /// Represents the PostgreSQL tsquery type. - public const string sql_tsquery = "tsquery"; - - /// Represents the PostgreSQL tsvector type. - public const string sql_tsvector = "tsvector"; - - /// Represents the PostgreSQL txid_snapshot type. - public const string sql_txid_snapshot = "txid_snapshot"; - - /// Represents the PostgreSQL xid type. - public const string sql_xid = "xid"; - - /// Represents the PostgreSQL xid8 type. - public const string sql_xid8 = "xid8"; -} +using System.Diagnostics.CodeAnalysis; + +namespace MJCZone.DapperMatic.Providers.PostgreSql; + +/// +/// Provides constants for PostgreSQL data types. +/// +public static class PostgreSqlTypes +{ + // integers + + /// Represents the PostgreSQL smallint type. + public const string sql_smallint = "smallint"; + + /// Represents the PostgreSQL int2 type. + public const string sql_int2 = "int2"; + + /// Represents the PostgreSQL smallserial type. + public const string sql_smallserial = "smallserial"; + + /// Represents the PostgreSQL serial2 type. + public const string sql_serial2 = "serial2"; + + /// Represents the PostgreSQL integer type. + public const string sql_integer = "integer"; + + /// Represents the PostgreSQL int type. + public const string sql_int = "int"; + + /// Represents the PostgreSQL int4 type. + public const string sql_int4 = "int4"; + + /// Represents the PostgreSQL serial type. + public const string sql_serial = "serial"; + + /// Represents the PostgreSQL serial4 type. + public const string sql_serial4 = "serial4"; + + /// Represents the PostgreSQL bigint type. + public const string sql_bigint = "bigint"; + + /// Represents the PostgreSQL int8 type. + public const string sql_int8 = "int8"; + + /// Represents the PostgreSQL bigserial type. + public const string sql_bigserial = "bigserial"; + + /// Represents the PostgreSQL serial8 type. + public const string sql_serial8 = "serial8"; + + // real + + /// Represents the PostgreSQL float4 type. + public const string sql_float4 = "float4"; + + /// Represents the PostgreSQL real type. + public const string sql_real = "real"; + + /// Represents the PostgreSQL double precision type. + public const string sql_double_precision = "double precision"; + + /// Represents the PostgreSQL float8 type. + public const string sql_float8 = "float8"; + + /// Represents the PostgreSQL money type. + public const string sql_money = "money"; + + /// Represents the PostgreSQL numeric type. + public const string sql_numeric = "numeric"; + + /// Represents the PostgreSQL decimal type. + public const string sql_decimal = "decimal"; + + // bool + + /// Represents the PostgreSQL bool type. + public const string sql_bool = "bool"; + + /// Represents the PostgreSQL boolean type. + public const string sql_boolean = "boolean"; + + // datetime + + /// Represents the PostgreSQL date type. + public const string sql_date = "date"; + + /// Represents the PostgreSQL interval type. + public const string sql_interval = "interval"; + + /// Represents the PostgreSQL time without time zone type. + public const string sql_time_without_time_zone = "time without time zone"; + + /// Represents the PostgreSQL time type. + public const string sql_time = "time"; + + /// Represents the PostgreSQL time with time zone type. + public const string sql_time_with_time_zone = "time with time zone"; + + /// Represents the PostgreSQL timetz type. + public const string sql_timetz = "timetz"; + + /// Represents the PostgreSQL timestamp without time zone type. + public const string sql_timestamp_without_time_zone = "timestamp without time zone"; + + /// Represents the PostgreSQL timestamp type. + public const string sql_timestamp = "timestamp"; + + /// Represents the PostgreSQL timestamp with time zone type. + public const string sql_timestamp_with_time_zone = "timestamp with time zone"; + + /// Represents the PostgreSQL timestamptz type. + public const string sql_timestamptz = "timestamptz"; + + // text + + /// Represents the PostgreSQL bit type. + public const string sql_bit = "bit"; + + /// Represents the PostgreSQL bit varying type. + public const string sql_bit_varying = "bit varying"; + + /// Represents the PostgreSQL varbit type. + public const string sql_varbit = "varbit"; + + /// Represents the PostgreSQL character varying type. + public const string sql_character_varying = "character varying"; + + /// Represents the PostgreSQL varchar type. + public const string sql_varchar = "varchar"; + + /// Represents the PostgreSQL character type. + public const string sql_character = "character"; + + /// Represents the PostgreSQL char type. + public const string sql_char = "char"; + + /// Represents the PostgreSQL bpchar type. + public const string sql_bpchar = "bpchar"; + + /// Represents the PostgreSQL text type. + public const string sql_text = "text"; + + /// Represents the PostgreSQL name type. + public const string sql_name = "name"; + + /// Represents the PostgreSQL uuid type. + public const string sql_uuid = "uuid"; + + /// Represents the PostgreSQL json type. + public const string sql_json = "json"; + + /// Represents the PostgreSQL jsonb type. + public const string sql_jsonb = "jsonb"; + + /// Represents the PostgreSQL jsonpath type. + public const string sql_jsonpath = "jsonpath"; + + /// Represents the PostgreSQL xml type. + public const string sql_xml = "xml"; + + // binary + + /// Represents the PostgreSQL bytea type. + public const string sql_bytea = "bytea"; + + // geometry + + /// Represents the PostgreSQL box type. + public const string sql_box = "box"; + + /// Represents the PostgreSQL circle type. + public const string sql_circle = "circle"; + + /// Represents the PostgreSQL geography type. + public const string sql_geography = "geography"; + + /// Represents the PostgreSQL geometry type. + public const string sql_geometry = "geometry"; + + /// Represents the PostgreSQL line type. + public const string sql_line = "line"; + + /// Represents the PostgreSQL lseg type. + public const string sql_lseg = "lseg"; + + /// Represents the PostgreSQL path type. + public const string sql_path = "path"; + + /// Represents the PostgreSQL point type. + public const string sql_point = "point"; + + /// Represents the PostgreSQL polygon type. + public const string sql_polygon = "polygon"; + + // range types + + /// Represents the PostgreSQL datemultirange type. + public const string sql_datemultirange = "datemultirange"; + + /// Represents the PostgreSQL daterange type. + public const string sql_daterange = "daterange"; + + /// Represents the PostgreSQL int4multirange type. + public const string sql_int4multirange = "int4multirange"; + + /// Represents the PostgreSQL int4range type. + public const string sql_int4range = "int4range"; + + /// Represents the PostgreSQL int8multirange type. + public const string sql_int8multirange = "int8multirange"; + + /// Represents the PostgreSQL int8range type. + public const string sql_int8range = "int8range"; + + /// Represents the PostgreSQL nummultirange type. + public const string sql_nummultirange = "nummultirange"; + + /// Represents the PostgreSQL numrange type. + public const string sql_numrange = "numrange"; + + /// Represents the PostgreSQL tsmultirange type. + public const string sql_tsmultirange = "tsmultirange"; + + /// Represents the PostgreSQL tsrange type. + public const string sql_tsrange = "tsrange"; + + /// Represents the PostgreSQL tstzmultirange type. + public const string sql_tstzmultirange = "tstzmultirange"; + + /// Represents the PostgreSQL tstzrange type. + public const string sql_tstzrange = "tstzrange"; + + // other data types + + /// Represents the PostgreSQL cidr type. + public const string sql_cidr = "cidr"; + + /// Represents the PostgreSQL citext type. + public const string sql_citext = "citext"; + + /// Represents the PostgreSQL hstore type. + public const string sql_hstore = "hstore"; + + /// Represents the PostgreSQL inet type. + public const string sql_inet = "inet"; + + /// Represents the PostgreSQL int2vector type. + public const string sql_int2vector = "int2vector"; + + /// Represents the PostgreSQL lquery type. + public const string sql_lquery = "lquery"; + + /// Represents the PostgreSQL ltree type. + public const string sql_ltree = "ltree"; + + /// Represents the PostgreSQL ltxtquery type. + public const string sql_ltxtquery = "ltxtquery"; + + /// Represents the PostgreSQL macaddr type. + public const string sql_macaddr = "macaddr"; + + /// Represents the PostgreSQL macaddr8 type. + public const string sql_macaddr8 = "macaddr8"; + + /// Represents the PostgreSQL oid type. + public const string sql_oid = "oid"; + + /// Represents the PostgreSQL oidvector type. + public const string sql_oidvector = "oidvector"; + + /// Represents the PostgreSQL pg_lsn type. + public const string sql_pg_lsn = "pg_lsn"; + + /// Represents the PostgreSQL pg_snapshot type. + public const string sql_pg_snapshot = "pg_snapshot"; + + /// Represents the PostgreSQL refcursor type. + public const string sql_refcursor = "refcursor"; + + /// Represents the PostgreSQL regclass type. + public const string sql_regclass = "regclass"; + + /// Represents the PostgreSQL regcollation type. + public const string sql_regcollation = "regcollation"; + + /// Represents the PostgreSQL regconfig type. + public const string sql_regconfig = "regconfig"; + + /// Represents the PostgreSQL regdictionary type. + public const string sql_regdictionary = "regdictionary"; + + /// Represents the PostgreSQL regnamespace type. + public const string sql_regnamespace = "regnamespace"; + + /// Represents the PostgreSQL regrole type. + public const string sql_regrole = "regrole"; + + /// Represents the PostgreSQL regtype type. + public const string sql_regtype = "regtype"; + + /// Represents the PostgreSQL tid type. + public const string sql_tid = "tid"; + + /// Represents the PostgreSQL tsquery type. + public const string sql_tsquery = "tsquery"; + + /// Represents the PostgreSQL tsvector type. + public const string sql_tsvector = "tsvector"; + + /// Represents the PostgreSQL txid_snapshot type. + public const string sql_txid_snapshot = "txid_snapshot"; + + /// Represents the PostgreSQL xid type. + public const string sql_xid = "xid"; + + /// Represents the PostgreSQL xid8 type. + public const string sql_xid8 = "xid8"; +} diff --git a/src/DapperMatic/Providers/SqlServer/ISqlServerMethods.cs b/src/MJCZone.DapperMatic/Providers/SqlServer/ISqlServerMethods.cs similarity index 61% rename from src/DapperMatic/Providers/SqlServer/ISqlServerMethods.cs rename to src/MJCZone.DapperMatic/Providers/SqlServer/ISqlServerMethods.cs index d16e1b1..680641b 100644 --- a/src/DapperMatic/Providers/SqlServer/ISqlServerMethods.cs +++ b/src/MJCZone.DapperMatic/Providers/SqlServer/ISqlServerMethods.cs @@ -1,8 +1,8 @@ -using DapperMatic.Interfaces; - -namespace DapperMatic.Providers.SqlServer; - -/// -/// Provides SQL Server specific methods for database operations. -/// -public interface ISqlServerMethods : IDatabaseMethods { } +using MJCZone.DapperMatic.Interfaces; + +namespace MJCZone.DapperMatic.Providers.SqlServer; + +/// +/// Provides SQL Server specific methods for database operations. +/// +public interface ISqlServerMethods : IDatabaseMethods { } diff --git a/src/DapperMatic/Providers/SqlServer/SqlServerMethods.Schemas.cs b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.Schemas.cs similarity index 97% rename from src/DapperMatic/Providers/SqlServer/SqlServerMethods.Schemas.cs rename to src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.Schemas.cs index 000ea1f..ce4b944 100644 --- a/src/DapperMatic/Providers/SqlServer/SqlServerMethods.Schemas.cs +++ b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.Schemas.cs @@ -1,178 +1,178 @@ -using System.Data; -using System.Data.Common; - -namespace DapperMatic.Providers.SqlServer; - -public partial class SqlServerMethods -{ - /// - /// Drops the specified schema if it exists. - /// - /// The database connection. - /// The name of the schema to drop. - /// The transaction to use, or null to create a new transaction. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the schema was dropped. - public override async Task DropSchemaIfExistsAsync( - IDbConnection db, - string schemaName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if ( - !await DoesSchemaExistAsync(db, schemaName, tx, cancellationToken).ConfigureAwait(false) - ) - { - return false; - } - - schemaName = NormalizeSchemaName(schemaName); - - var innerTx = - tx - ?? await (db as DbConnection)! - .BeginTransactionAsync(cancellationToken) - .ConfigureAwait(false); - try - { - // drop all objects in the schemaName (except tables, which will be handled separately) - var dropAllRelatedTypesSqlStatement = await QueryAsync( - db, - $""" - - SELECT CASE - WHEN type in ('C', 'D', 'F', 'UQ', 'PK') THEN - CONCAT('ALTER TABLE ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(OBJECT_NAME(o.parent_object_id)), ' DROP CONSTRAINT ', QUOTENAME(o.[name])) - WHEN type in ('SN') THEN - CONCAT('DROP SYNONYM ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) - WHEN type in ('SO') THEN - CONCAT('DROP SEQUENCE ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) - WHEN type in ('U') THEN - CONCAT('DROP TABLE ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) - WHEN type in ('V') THEN - CONCAT('DROP VIEW ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) - WHEN type in ('TR') THEN - CONCAT('DROP TRIGGER ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) - WHEN type in ('IF', 'TF', 'FN', 'FS', 'FT') THEN - CONCAT('DROP FUNCTION ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) - WHEN type in ('P', 'PC') THEN - CONCAT('DROP PROCEDURE ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) - END AS DropSqlStatement - FROM sys.objects o - WHERE o.schema_id = SCHEMA_ID('{schemaName}') - AND - type IN( - --constraints (check, default, foreign key, unique) - 'C', 'D', 'F', 'UQ', - --primary keys - 'PK', - --synonyms - 'SN', - --sequences - 'SO', - --user defined tables - 'U', - --views - 'V', - --triggers - 'TR', - --functions (inline, tableName-valued, scalar, CLR scalar, CLR tableName-valued) - 'IF', 'TF', 'FN', 'FS', 'FT', - --procedures (stored procedure, CLR stored procedure) - 'P', 'PC' - ) - ORDER BY CASE - WHEN type in ('C', 'D', 'UQ') THEN 2 - WHEN type in ('F') THEN 1 - WHEN type in ('PK') THEN 19 - WHEN type in ('SN') THEN 3 - WHEN type in ('SO') THEN 4 - WHEN type in ('U') THEN 20 - WHEN type in ('V') THEN 18 - WHEN type in ('TR') THEN 10 - WHEN type in ('IF', 'TF', 'FN', 'FS', 'FT') THEN 9 - WHEN type in ('P', 'PC') THEN 8 - END - - """, - tx: innerTx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - foreach (var dropSql in dropAllRelatedTypesSqlStatement) - { - await ExecuteAsync(db, dropSql, tx: innerTx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - } - - // drop xml schemaName collection - var dropXmlSchemaCollectionSqlStatements = await QueryAsync( - db, - $""" - SELECT 'DROP XML SCHEMA COLLECTION ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name) - FROM sys.xml_schema_collections - WHERE schema_id = SCHEMA_ID('{schemaName}') - """, - tx: innerTx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - foreach (var dropSql in dropXmlSchemaCollectionSqlStatements) - { - await ExecuteAsync(db, dropSql, tx: innerTx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - } - - // drop all custom types - var dropCustomTypesSqlStatements = await QueryAsync( - db, - $""" - SELECT 'DROP TYPE ' +QUOTENAME(SCHEMA_NAME(schema_id))+'.'+QUOTENAME(name) - FROM sys.types - WHERE schema_id = SCHEMA_ID('{schemaName}') - """, - tx: innerTx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - foreach (var dropSql in dropCustomTypesSqlStatements) - { - await ExecuteAsync(db, dropSql, tx: innerTx, cancellationToken: cancellationToken) - .ConfigureAwait(false); - } - - // drop the schemaName itself - await ExecuteAsync( - db, - $"DROP SCHEMA [{schemaName}]", - tx: innerTx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - - if (tx == null) - { - innerTx.Commit(); - } - } - catch - { - if (tx == null) - { - innerTx.Rollback(); - } - - throw; - } - finally - { - if (tx == null) - { - innerTx.Dispose(); - } - } - - return true; - } -} +using System.Data; +using System.Data.Common; + +namespace MJCZone.DapperMatic.Providers.SqlServer; + +public partial class SqlServerMethods +{ + /// + /// Drops the specified schema if it exists. + /// + /// The database connection. + /// The name of the schema to drop. + /// The transaction to use, or null to create a new transaction. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the schema was dropped. + public override async Task DropSchemaIfExistsAsync( + IDbConnection db, + string schemaName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if ( + !await DoesSchemaExistAsync(db, schemaName, tx, cancellationToken).ConfigureAwait(false) + ) + { + return false; + } + + schemaName = NormalizeSchemaName(schemaName); + + var innerTx = + tx + ?? await (db as DbConnection)! + .BeginTransactionAsync(cancellationToken) + .ConfigureAwait(false); + try + { + // drop all objects in the schemaName (except tables, which will be handled separately) + var dropAllRelatedTypesSqlStatement = await QueryAsync( + db, + $""" + + SELECT CASE + WHEN type in ('C', 'D', 'F', 'UQ', 'PK') THEN + CONCAT('ALTER TABLE ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(OBJECT_NAME(o.parent_object_id)), ' DROP CONSTRAINT ', QUOTENAME(o.[name])) + WHEN type in ('SN') THEN + CONCAT('DROP SYNONYM ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) + WHEN type in ('SO') THEN + CONCAT('DROP SEQUENCE ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) + WHEN type in ('U') THEN + CONCAT('DROP TABLE ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) + WHEN type in ('V') THEN + CONCAT('DROP VIEW ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) + WHEN type in ('TR') THEN + CONCAT('DROP TRIGGER ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) + WHEN type in ('IF', 'TF', 'FN', 'FS', 'FT') THEN + CONCAT('DROP FUNCTION ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) + WHEN type in ('P', 'PC') THEN + CONCAT('DROP PROCEDURE ', QUOTENAME(SCHEMA_NAME(o.schema_id))+'.'+QUOTENAME(o.[name])) + END AS DropSqlStatement + FROM sys.objects o + WHERE o.schema_id = SCHEMA_ID('{schemaName}') + AND + type IN( + --constraints (check, default, foreign key, unique) + 'C', 'D', 'F', 'UQ', + --primary keys + 'PK', + --synonyms + 'SN', + --sequences + 'SO', + --user defined tables + 'U', + --views + 'V', + --triggers + 'TR', + --functions (inline, tableName-valued, scalar, CLR scalar, CLR tableName-valued) + 'IF', 'TF', 'FN', 'FS', 'FT', + --procedures (stored procedure, CLR stored procedure) + 'P', 'PC' + ) + ORDER BY CASE + WHEN type in ('C', 'D', 'UQ') THEN 2 + WHEN type in ('F') THEN 1 + WHEN type in ('PK') THEN 19 + WHEN type in ('SN') THEN 3 + WHEN type in ('SO') THEN 4 + WHEN type in ('U') THEN 20 + WHEN type in ('V') THEN 18 + WHEN type in ('TR') THEN 10 + WHEN type in ('IF', 'TF', 'FN', 'FS', 'FT') THEN 9 + WHEN type in ('P', 'PC') THEN 8 + END + + """, + tx: innerTx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + foreach (var dropSql in dropAllRelatedTypesSqlStatement) + { + await ExecuteAsync(db, dropSql, tx: innerTx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + + // drop xml schemaName collection + var dropXmlSchemaCollectionSqlStatements = await QueryAsync( + db, + $""" + SELECT 'DROP XML SCHEMA COLLECTION ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name) + FROM sys.xml_schema_collections + WHERE schema_id = SCHEMA_ID('{schemaName}') + """, + tx: innerTx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + foreach (var dropSql in dropXmlSchemaCollectionSqlStatements) + { + await ExecuteAsync(db, dropSql, tx: innerTx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + + // drop all custom types + var dropCustomTypesSqlStatements = await QueryAsync( + db, + $""" + SELECT 'DROP TYPE ' +QUOTENAME(SCHEMA_NAME(schema_id))+'.'+QUOTENAME(name) + FROM sys.types + WHERE schema_id = SCHEMA_ID('{schemaName}') + """, + tx: innerTx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + foreach (var dropSql in dropCustomTypesSqlStatements) + { + await ExecuteAsync(db, dropSql, tx: innerTx, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + + // drop the schemaName itself + await ExecuteAsync( + db, + $"DROP SCHEMA [{schemaName}]", + tx: innerTx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + + if (tx == null) + { + innerTx.Commit(); + } + } + catch + { + if (tx == null) + { + innerTx.Rollback(); + } + + throw; + } + finally + { + if (tx == null) + { + innerTx.Dispose(); + } + } + + return true; + } +} diff --git a/src/DapperMatic/Providers/SqlServer/SqlServerMethods.Strings.cs b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.Strings.cs similarity index 95% rename from src/DapperMatic/Providers/SqlServer/SqlServerMethods.Strings.cs rename to src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.Strings.cs index 092a2b1..cf6bc75 100644 --- a/src/DapperMatic/Providers/SqlServer/SqlServerMethods.Strings.cs +++ b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.Strings.cs @@ -1,6 +1,6 @@ -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.SqlServer; +namespace MJCZone.DapperMatic.Providers.SqlServer; public partial class SqlServerMethods { diff --git a/src/DapperMatic/Providers/SqlServer/SqlServerMethods.Tables.cs b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.Tables.cs similarity index 91% rename from src/DapperMatic/Providers/SqlServer/SqlServerMethods.Tables.cs rename to src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.Tables.cs index afe529a..395bf56 100644 --- a/src/DapperMatic/Providers/SqlServer/SqlServerMethods.Tables.cs +++ b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.Tables.cs @@ -1,12 +1,12 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.SqlServer; +namespace MJCZone.DapperMatic.Providers.SqlServer; public partial class SqlServerMethods { /// - public override async Task> GetTablesAsync( + public override async Task> GetTablesAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, @@ -228,7 +228,7 @@ string default_expression ) .ConfigureAwait(false); - var tables = new List(); + var tables = new List(); foreach ( var tableColumns in columnResults.GroupBy(r => new { r.schema_name, r.table_name }) @@ -257,13 +257,13 @@ string default_expression }) .Select(gb => { - return new DxForeignKeyConstraint( + return new DmForeignKeyConstraint( gb.Key.schema_name, gb.Key.table_name, gb.Key.constraint_name, - gb.Select(c => new DxOrderedColumn(c.column_name)).ToArray(), + gb.Select(c => new DmOrderedColumn(c.column_name)).ToArray(), gb.Key.referenced_table_name, - gb.Select(c => new DxOrderedColumn(c.referenced_column_name)).ToArray(), + gb.Select(c => new DmOrderedColumn(c.referenced_column_name)).ToArray(), gb.Key.delete_rule.ToForeignKeyAction(), gb.Key.update_rule.ToForeignKeyAction() ); @@ -274,7 +274,7 @@ string default_expression t.schema_name.Equals(schemaName, StringComparison.OrdinalIgnoreCase) && t.table_name.Equals(tableName, StringComparison.OrdinalIgnoreCase) ) - .Select(c => new DxCheckConstraint( + .Select(c => new DmCheckConstraint( c.schema_name, c.table_name, c.column_name, @@ -287,7 +287,7 @@ string default_expression t.schema_name.Equals(schemaName, StringComparison.OrdinalIgnoreCase) && t.table_name.Equals(tableName, StringComparison.OrdinalIgnoreCase) ) - .Select(c => new DxDefaultConstraint( + .Select(c => new DmDefaultConstraint( c.schema_name, c.table_name, c.column_name, @@ -300,15 +300,15 @@ string default_expression var primaryKeyConstraintInfo = tableConstraints.Where(t => t.is_primary_key).ToArray(); var primaryKeyConstraint = primaryKeyConstraintInfo.Length > 0 - ? new DxPrimaryKeyConstraint( + ? new DmPrimaryKeyConstraint( primaryKeyConstraintInfo[0].schema_name, primaryKeyConstraintInfo[0].table_name, primaryKeyConstraintInfo[0].constraint_name, primaryKeyConstraintInfo .OrderBy(t => t.column_key_ordinal) - .Select(t => new DxOrderedColumn( + .Select(t => new DmOrderedColumn( t.column_name, - t.is_desc ? DxColumnOrder.Descending : DxColumnOrder.Ascending + t.is_desc ? DmColumnOrder.Descending : DmColumnOrder.Ascending )) .ToArray() ) @@ -325,14 +325,14 @@ string default_expression }) .ToArray(); var uniqueConstraints = uniqueConstraintsInfo - .Select(t => new DxUniqueConstraint( + .Select(t => new DmUniqueConstraint( t.Key.schema_name, t.Key.table_name, t.Key.constraint_name, t.OrderBy(c => c.column_key_ordinal) - .Select(c => new DxOrderedColumn( + .Select(c => new DmOrderedColumn( c.column_name, - c.is_desc ? DxColumnOrder.Descending : DxColumnOrder.Ascending + c.is_desc ? DmColumnOrder.Descending : DmColumnOrder.Ascending )) .ToArray() )) @@ -349,21 +349,21 @@ string default_expression }) .ToArray(); var indexes = indexesInfo - .Select(t => new DxIndex( + .Select(t => new DmIndex( t.Key.schema_name, t.Key.table_name, t.Key.constraint_name, t.OrderBy(c => c.column_key_ordinal) - .Select(c => new DxOrderedColumn( + .Select(c => new DmOrderedColumn( c.column_name, - c.is_desc ? DxColumnOrder.Descending : DxColumnOrder.Ascending + c.is_desc ? DmColumnOrder.Descending : DmColumnOrder.Ascending )) .ToArray(), t.First().is_unique )) .ToArray(); - var columns = new List(); + var columns = new List(); foreach (var tableColumn in tableColumns) { var columnIsUniqueViaUniqueConstraintOrIndex = @@ -416,7 +416,7 @@ string default_expression var dotnetTypeDescriptor = GetDotnetTypeFromSqlType(tableColumn.data_type); - var column = new DxColumn( + var column = new DmColumn( tableColumn.schema_name, tableColumn.table_name, tableColumn.column_name, @@ -469,7 +469,7 @@ string default_expression columns.Add(column); } - var table = new DxTable( + var table = new DmTable( schemaName, tableName, [.. columns], @@ -487,7 +487,7 @@ string default_expression } /// - protected override async Task> GetIndexesInternalAsync( + protected override async Task> GetIndexesInternalAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, @@ -564,20 +564,20 @@ int is_descending_key r => (r.is_unique, r.column_name, r.key_ordinal, r.is_descending_key) ); - var indexes = new List(); + var indexes = new List(); // ReSharper disable once LoopCanBeConvertedToQuery foreach (var group in grouped) { - var index = new DxIndex( + var index = new DmIndex( group.Key.schema_name, group.Key.table_name, group.Key.index_name, group - .Select(g => new DxOrderedColumn( + .Select(g => new DmOrderedColumn( g.column_name, g.is_descending_key == 1 - ? DxColumnOrder.Descending - : DxColumnOrder.Ascending + ? DmColumnOrder.Descending + : DmColumnOrder.Ascending )) .ToArray(), group.First().is_unique == 1 diff --git a/src/DapperMatic/Providers/SqlServer/SqlServerMethods.cs b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.cs similarity index 93% rename from src/DapperMatic/Providers/SqlServer/SqlServerMethods.cs rename to src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.cs index cd5643b..85ba7f4 100644 --- a/src/DapperMatic/Providers/SqlServer/SqlServerMethods.cs +++ b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethods.cs @@ -1,66 +1,66 @@ -using System.Data; -using DapperMatic.Providers.Base; - -namespace DapperMatic.Providers.SqlServer; - -/// -/// Provides SQL Server specific database methods. -/// -public partial class SqlServerMethods - : DatabaseMethodsBase, - ISqlServerMethods -{ - private static string _defaultSchema = "dbo"; - - /// - /// Initializes a new instance of the class. - /// - internal SqlServerMethods() - : base(DbProviderType.SqlServer) { } - - /// - /// Gets the characters used for quoting identifiers. - /// - public override char[] QuoteChars => ['[', ']']; - - /// - /// Gets the default schema. - /// - protected override string DefaultSchema => _defaultSchema; - - /// - /// Sets the default schema. - /// - /// The schema name. - public static void SetDefaultSchema(string schema) - { - _defaultSchema = schema; - } - - /// - /// Gets the database version asynchronously. - /// - /// The database connection. - /// The transaction. - /// The cancellation token. - /// The database version. - public override async Task GetDatabaseVersionAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - /* - SELECT - SERVERPROPERTY('Productversion') As [SQL Server Version] --> 15.0.2000.5, 15.0.4390.2 - SERVERPROPERTY('Productlevel') As [SQL Server Build Level], --> RTM - SERVERPROPERTY('edition') As [SQL Server Edition] --> Express Edition (64-bit), Developer Edition (64-bit), etc. - */ - - const string sql = "SELECT SERVERPROPERTY('Productversion')"; - var versionString = - await ExecuteScalarAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false) ?? string.Empty; - return DbProviderUtils.ExtractVersionFromVersionString(versionString); - } -} +using System.Data; +using MJCZone.DapperMatic.Providers.Base; + +namespace MJCZone.DapperMatic.Providers.SqlServer; + +/// +/// Provides SQL Server specific database methods. +/// +public partial class SqlServerMethods + : DatabaseMethodsBase, + ISqlServerMethods +{ + private static string _defaultSchema = "dbo"; + + /// + /// Initializes a new instance of the class. + /// + internal SqlServerMethods() + : base(DbProviderType.SqlServer) { } + + /// + /// Gets the characters used for quoting identifiers. + /// + public override char[] QuoteChars => ['[', ']']; + + /// + /// Gets the default schema. + /// + protected override string DefaultSchema => _defaultSchema; + + /// + /// Sets the default schema. + /// + /// The schema name. + public static void SetDefaultSchema(string schema) + { + _defaultSchema = schema; + } + + /// + /// Gets the database version asynchronously. + /// + /// The database connection. + /// The transaction. + /// The cancellation token. + /// The database version. + public override async Task GetDatabaseVersionAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + /* + SELECT + SERVERPROPERTY('Productversion') As [SQL Server Version] --> 15.0.2000.5, 15.0.4390.2 + SERVERPROPERTY('Productlevel') As [SQL Server Build Level], --> RTM + SERVERPROPERTY('edition') As [SQL Server Edition] --> Express Edition (64-bit), Developer Edition (64-bit), etc. + */ + + const string sql = "SELECT SERVERPROPERTY('Productversion')"; + var versionString = + await ExecuteScalarAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false) ?? string.Empty; + return DbProviderUtils.ExtractVersionFromVersionString(versionString); + } +} diff --git a/src/DapperMatic/Providers/SqlServer/SqlServerMethodsFactory.cs b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethodsFactory.cs similarity index 92% rename from src/DapperMatic/Providers/SqlServer/SqlServerMethodsFactory.cs rename to src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethodsFactory.cs index 8a1182e..21aebe2 100644 --- a/src/DapperMatic/Providers/SqlServer/SqlServerMethodsFactory.cs +++ b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerMethodsFactory.cs @@ -1,38 +1,38 @@ -using System.Data; -using System.Reflection.Metadata.Ecma335; -using DapperMatic.Interfaces; - -namespace DapperMatic.Providers.SqlServer; - -/// -/// Factory class for creating SQL Server specific database methods. -/// -public class SqlServerMethodsFactory : DatabaseMethodsFactoryBase -{ - /// - /// Determines whether the specified connection supports custom handling. - /// - /// The database connection. - /// true if the connection supports custom handling; otherwise, false. - public virtual bool SupportsConnectionCustom(IDbConnection db) => false; - - /// - /// Determines whether the specified connection is supported. - /// - /// The database connection. - /// true if the connection is supported; otherwise, false. - public override bool SupportsConnection(IDbConnection db) - { - var typeName = db.GetType().FullName; - return SupportsConnectionCustom(db) - || (typeName == "System.Data.SqlClient.SqlConnection") - || (typeName == "System.Data.SqlServerCe.SqlCeConnection") - || (typeName == "Microsoft.Data.SqlClient.SqlConnection"); - } - - /// - /// Creates the core database methods for SQL Server. - /// - /// The SQL Server specific database methods. - protected override IDatabaseMethods CreateMethodsCore() => new SqlServerMethods(); -} +using System.Data; +using System.Reflection.Metadata.Ecma335; +using MJCZone.DapperMatic.Interfaces; + +namespace MJCZone.DapperMatic.Providers.SqlServer; + +/// +/// Factory class for creating SQL Server specific database methods. +/// +public class SqlServerMethodsFactory : DatabaseMethodsFactoryBase +{ + /// + /// Determines whether the specified connection supports custom handling. + /// + /// The database connection. + /// true if the connection supports custom handling; otherwise, false. + public virtual bool SupportsConnectionCustom(IDbConnection db) => false; + + /// + /// Determines whether the specified connection is supported. + /// + /// The database connection. + /// true if the connection is supported; otherwise, false. + public override bool SupportsConnection(IDbConnection db) + { + var typeName = db.GetType().FullName; + return SupportsConnectionCustom(db) + || (typeName == "System.Data.SqlClient.SqlConnection") + || (typeName == "System.Data.SqlServerCe.SqlCeConnection") + || (typeName == "Microsoft.Data.SqlClient.SqlConnection"); + } + + /// + /// Creates the core database methods for SQL Server. + /// + /// The SQL Server specific database methods. + protected override IDatabaseMethods CreateMethodsCore() => new SqlServerMethods(); +} diff --git a/src/DapperMatic/Providers/SqlServer/SqlServerProviderTypeMap.cs b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerProviderTypeMap.cs similarity index 96% rename from src/DapperMatic/Providers/SqlServer/SqlServerProviderTypeMap.cs rename to src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerProviderTypeMap.cs index 7b35fef..92d8e3c 100644 --- a/src/DapperMatic/Providers/SqlServer/SqlServerProviderTypeMap.cs +++ b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerProviderTypeMap.cs @@ -6,9 +6,9 @@ using System.Text.Json; using System.Text.Json.Nodes; using System.Xml.Linq; -using DapperMatic.Converters; +using MJCZone.DapperMatic.Converters; -namespace DapperMatic.Providers.SqlServer; +namespace MJCZone.DapperMatic.Providers.SqlServer; // See: // https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings diff --git a/src/DapperMatic/Providers/SqlServer/SqlServerTypes.cs b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerTypes.cs similarity index 95% rename from src/DapperMatic/Providers/SqlServer/SqlServerTypes.cs rename to src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerTypes.cs index 8a0d078..95249b7 100644 --- a/src/DapperMatic/Providers/SqlServer/SqlServerTypes.cs +++ b/src/MJCZone.DapperMatic/Providers/SqlServer/SqlServerTypes.cs @@ -1,6 +1,6 @@ using System.Diagnostics.CodeAnalysis; -namespace DapperMatic.Providers.SqlServer; +namespace MJCZone.DapperMatic.Providers.SqlServer; /// /// Provides constants for SQL Server data types. diff --git a/src/DapperMatic/Providers/Sqlite/ISqliteMethods.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/ISqliteMethods.cs similarity index 58% rename from src/DapperMatic/Providers/Sqlite/ISqliteMethods.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/ISqliteMethods.cs index d3eb978..bcb293f 100644 --- a/src/DapperMatic/Providers/Sqlite/ISqliteMethods.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/ISqliteMethods.cs @@ -1,8 +1,8 @@ -using DapperMatic.Interfaces; - -namespace DapperMatic.Providers.Sqlite; - -/// -/// Provides SQLite specific database methods. -/// -public interface ISqliteMethods : IDatabaseMethods { } +using MJCZone.DapperMatic.Interfaces; + +namespace MJCZone.DapperMatic.Providers.Sqlite; + +/// +/// Provides SQLite specific database methods. +/// +public interface ISqliteMethods : IDatabaseMethods { } diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethods.CheckConstraints.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.CheckConstraints.cs similarity index 90% rename from src/DapperMatic/Providers/Sqlite/SqliteMethods.CheckConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.CheckConstraints.cs index ad2338f..09611ba 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethods.CheckConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.CheckConstraints.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Sqlite; +namespace MJCZone.DapperMatic.Providers.Sqlite; public partial class SqliteMethods { @@ -43,7 +43,10 @@ public override async Task CreateCheckConstraintIfNotExistsAsync( if (!string.IsNullOrWhiteSpace(columnName)) { return table.CheckConstraints.All(x => - !x.ConstraintName.Equals(constraintName, StringComparison.OrdinalIgnoreCase) + !x.ConstraintName.Equals( + constraintName, + StringComparison.OrdinalIgnoreCase + ) ) && table.CheckConstraints.All(x => string.IsNullOrWhiteSpace(x.ColumnName) @@ -60,7 +63,7 @@ public override async Task CreateCheckConstraintIfNotExistsAsync( table => { table.CheckConstraints.Add( - new DxCheckConstraint( + new DmCheckConstraint( schemaName, tableName, columnName, diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethods.Columns.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.Columns.cs similarity index 94% rename from src/DapperMatic/Providers/Sqlite/SqliteMethods.Columns.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.Columns.cs index 02d373f..861265d 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethods.Columns.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.Columns.cs @@ -1,102 +1,102 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Providers.Sqlite; - -public partial class SqliteMethods -{ - /// - /// Creates a column if it does not already exist in the specified table. - /// - /// The database connection. - /// The column to create. - /// The transaction to use, or null. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the column was created. - /// Thrown when the table name or column name is null or whitespace. - public override async Task CreateColumnIfNotExistsAsync( - IDbConnection db, - DxColumn column, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(column.TableName)) - { - throw new ArgumentException("Table name is required", nameof(column)); - } - - if (string.IsNullOrWhiteSpace(column.ColumnName)) - { - throw new ArgumentException("Column name is required", nameof(column)); - } - - var (_, tableName, columnName) = NormalizeNames( - column.SchemaName, - column.TableName, - column.ColumnName - ); - - return await AlterTableUsingRecreateTableStrategyAsync( - db, - DefaultSchema, - tableName, - table => - { - return table.Columns.All(x => - !x.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) - ); - }, - table => - { - table.Columns.Add(column); - return table; - }, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } - - /// - /// Drops a column if it exists in the specified table. - /// - /// The database connection. - /// The schema name. - /// The table name. - /// The column name. - /// The transaction to use, or null. - /// The cancellation token. - /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the column was dropped. - public override async Task DropColumnIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string columnName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - return await AlterTableUsingRecreateTableStrategyAsync( - db, - schemaName, - tableName, - table => - { - return table.Columns.Any(x => - x.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) - ); - }, - table => - { - table.Columns.RemoveAll(c => - c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) - ); - return table; - }, - tx: tx, - cancellationToken: cancellationToken - ) - .ConfigureAwait(false); - } -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Providers.Sqlite; + +public partial class SqliteMethods +{ + /// + /// Creates a column if it does not already exist in the specified table. + /// + /// The database connection. + /// The column to create. + /// The transaction to use, or null. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the column was created. + /// Thrown when the table name or column name is null or whitespace. + public override async Task CreateColumnIfNotExistsAsync( + IDbConnection db, + DmColumn column, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(column.TableName)) + { + throw new ArgumentException("Table name is required", nameof(column)); + } + + if (string.IsNullOrWhiteSpace(column.ColumnName)) + { + throw new ArgumentException("Column name is required", nameof(column)); + } + + var (_, tableName, columnName) = NormalizeNames( + column.SchemaName, + column.TableName, + column.ColumnName + ); + + return await AlterTableUsingRecreateTableStrategyAsync( + db, + DefaultSchema, + tableName, + table => + { + return table.Columns.All(x => + !x.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) + ); + }, + table => + { + table.Columns.Add(column); + return table; + }, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } + + /// + /// Drops a column if it exists in the specified table. + /// + /// The database connection. + /// The schema name. + /// The table name. + /// The column name. + /// The transaction to use, or null. + /// The cancellation token. + /// A task that represents the asynchronous operation. The task result contains a boolean indicating whether the column was dropped. + public override async Task DropColumnIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string columnName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + return await AlterTableUsingRecreateTableStrategyAsync( + db, + schemaName, + tableName, + table => + { + return table.Columns.Any(x => + x.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) + ); + }, + table => + { + table.Columns.RemoveAll(c => + c.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) + ); + return table; + }, + tx: tx, + cancellationToken: cancellationToken + ) + .ConfigureAwait(false); + } +} diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethods.DefaultConstraints.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.DefaultConstraints.cs similarity index 94% rename from src/DapperMatic/Providers/Sqlite/SqliteMethods.DefaultConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.DefaultConstraints.cs index 9acf234..5bbdb13 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethods.DefaultConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.DefaultConstraints.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Sqlite; +namespace MJCZone.DapperMatic.Providers.Sqlite; public partial class SqliteMethods { @@ -53,7 +53,7 @@ public override async Task CreateDefaultConstraintIfNotExistsAsync( table => { table.DefaultConstraints.Add( - new DxDefaultConstraint( + new DmDefaultConstraint( schemaName, tableName, columnName, diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethods.ForeignKeyConstraints.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.ForeignKeyConstraints.cs similarity index 91% rename from src/DapperMatic/Providers/Sqlite/SqliteMethods.ForeignKeyConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.ForeignKeyConstraints.cs index 37b1d99..418dd03 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethods.ForeignKeyConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.ForeignKeyConstraints.cs @@ -1,168 +1,168 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Providers.Sqlite; - -public partial class SqliteMethods -{ - /// - public override async Task CreateForeignKeyConstraintIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - DxOrderedColumn[] sourceColumns, - string referencedTableName, - DxOrderedColumn[] referencedColumns, - DxForeignKeyAction onDelete = DxForeignKeyAction.NoAction, - DxForeignKeyAction onUpdate = DxForeignKeyAction.NoAction, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - if (string.IsNullOrWhiteSpace(constraintName)) - { - throw new ArgumentException("Constraint name is required.", nameof(constraintName)); - } - - if (sourceColumns.Length == 0) - { - throw new ArgumentException( - "At least one column must be specified.", - nameof(sourceColumns) - ); - } - - if (string.IsNullOrWhiteSpace(referencedTableName)) - { - throw new ArgumentException( - "Referenced table name is required.", - nameof(referencedTableName) - ); - } - - if (referencedColumns.Length == 0) - { - throw new ArgumentException( - "At least one column must be specified.", - nameof(referencedColumns) - ); - } - - if (sourceColumns.Length != referencedColumns.Length) - { - throw new ArgumentException( - "The number of source columns must match the number of referenced columns.", - nameof(referencedColumns) - ); - } - - (schemaName, tableName, constraintName) = NormalizeNames( - schemaName, - tableName, - constraintName - ); - - return await AlterTableUsingRecreateTableStrategyAsync( - db, - schemaName, - tableName, - table => - { - return table.ForeignKeyConstraints.All(x => - !x.ConstraintName.Equals(constraintName, StringComparison.OrdinalIgnoreCase) - ); - }, - table => - { - table.ForeignKeyConstraints.Add( - new DxForeignKeyConstraint( - schemaName, - tableName, - constraintName, - sourceColumns, - referencedTableName, - referencedColumns, - onDelete, - onUpdate - ) - ); - return table; - }, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - public override async Task DropForeignKeyConstraintIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - (schemaName, tableName, constraintName) = NormalizeNames( - schemaName, - tableName, - constraintName - ); - - return await AlterTableUsingRecreateTableStrategyAsync( - db, - schemaName, - tableName, - table => - { - return table.ForeignKeyConstraints.Any(x => - x.ConstraintName.Equals(constraintName, StringComparison.OrdinalIgnoreCase) - ); - }, - table => - { - var foreignKey = table.ForeignKeyConstraints.FirstOrDefault(x => - x.ConstraintName.Equals(constraintName, StringComparison.OrdinalIgnoreCase) - ); - if (foreignKey is not null) - { - // remove the foreign key from the related column - foreach (var column in foreignKey.SourceColumns) - { - var sc = table.Columns.FirstOrDefault(x => - x.ColumnName.Equals( - column.ColumnName, - StringComparison.OrdinalIgnoreCase - ) - ); - // ReSharper disable once InvertIf - if (sc is not null) - { - sc.IsForeignKey = false; - sc.ReferencedTableName = null; - sc.ReferencedColumnName = null; - sc.OnDelete = null; - sc.OnUpdate = null; - } - } - - table.ForeignKeyConstraints.Remove(foreignKey); - } - table.ForeignKeyConstraints.RemoveAll(x => - x.ConstraintName.Equals(constraintName, StringComparison.OrdinalIgnoreCase) - ); - return table; - }, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Providers.Sqlite; + +public partial class SqliteMethods +{ + /// + public override async Task CreateForeignKeyConstraintIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + DmOrderedColumn[] sourceColumns, + string referencedTableName, + DmOrderedColumn[] referencedColumns, + DmForeignKeyAction onDelete = DmForeignKeyAction.NoAction, + DmForeignKeyAction onUpdate = DmForeignKeyAction.NoAction, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + if (string.IsNullOrWhiteSpace(constraintName)) + { + throw new ArgumentException("Constraint name is required.", nameof(constraintName)); + } + + if (sourceColumns.Length == 0) + { + throw new ArgumentException( + "At least one column must be specified.", + nameof(sourceColumns) + ); + } + + if (string.IsNullOrWhiteSpace(referencedTableName)) + { + throw new ArgumentException( + "Referenced table name is required.", + nameof(referencedTableName) + ); + } + + if (referencedColumns.Length == 0) + { + throw new ArgumentException( + "At least one column must be specified.", + nameof(referencedColumns) + ); + } + + if (sourceColumns.Length != referencedColumns.Length) + { + throw new ArgumentException( + "The number of source columns must match the number of referenced columns.", + nameof(referencedColumns) + ); + } + + (schemaName, tableName, constraintName) = NormalizeNames( + schemaName, + tableName, + constraintName + ); + + return await AlterTableUsingRecreateTableStrategyAsync( + db, + schemaName, + tableName, + table => + { + return table.ForeignKeyConstraints.All(x => + !x.ConstraintName.Equals(constraintName, StringComparison.OrdinalIgnoreCase) + ); + }, + table => + { + table.ForeignKeyConstraints.Add( + new DmForeignKeyConstraint( + schemaName, + tableName, + constraintName, + sourceColumns, + referencedTableName, + referencedColumns, + onDelete, + onUpdate + ) + ); + return table; + }, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + public override async Task DropForeignKeyConstraintIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + (schemaName, tableName, constraintName) = NormalizeNames( + schemaName, + tableName, + constraintName + ); + + return await AlterTableUsingRecreateTableStrategyAsync( + db, + schemaName, + tableName, + table => + { + return table.ForeignKeyConstraints.Any(x => + x.ConstraintName.Equals(constraintName, StringComparison.OrdinalIgnoreCase) + ); + }, + table => + { + var foreignKey = table.ForeignKeyConstraints.FirstOrDefault(x => + x.ConstraintName.Equals(constraintName, StringComparison.OrdinalIgnoreCase) + ); + if (foreignKey is not null) + { + // remove the foreign key from the related column + foreach (var column in foreignKey.SourceColumns) + { + var sc = table.Columns.FirstOrDefault(x => + x.ColumnName.Equals( + column.ColumnName, + StringComparison.OrdinalIgnoreCase + ) + ); + // ReSharper disable once InvertIf + if (sc is not null) + { + sc.IsForeignKey = false; + sc.ReferencedTableName = null; + sc.ReferencedColumnName = null; + sc.OnDelete = null; + sc.OnUpdate = null; + } + } + + table.ForeignKeyConstraints.Remove(foreignKey); + } + table.ForeignKeyConstraints.RemoveAll(x => + x.ConstraintName.Equals(constraintName, StringComparison.OrdinalIgnoreCase) + ); + return table; + }, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } +} diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethods.PrimaryKeyConstraints.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.PrimaryKeyConstraints.cs similarity index 91% rename from src/DapperMatic/Providers/Sqlite/SqliteMethods.PrimaryKeyConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.PrimaryKeyConstraints.cs index 2b08455..159764f 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethods.PrimaryKeyConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.PrimaryKeyConstraints.cs @@ -1,119 +1,119 @@ -using System.Data; -using DapperMatic.Models; - -namespace DapperMatic.Providers.Sqlite; - -public partial class SqliteMethods -{ - /// - public override async Task CreatePrimaryKeyConstraintIfNotExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - string constraintName, - DxOrderedColumn[] columns, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - if (string.IsNullOrWhiteSpace(constraintName)) - { - throw new ArgumentException("Constraint name is required.", nameof(constraintName)); - } - - if (columns.Length == 0) - { - throw new ArgumentException("At least one column must be specified.", nameof(columns)); - } - - if ( - await DoesPrimaryKeyConstraintExistAsync( - db, - schemaName, - tableName, - tx, - cancellationToken - ) - .ConfigureAwait(false) - ) - { - return false; - } - - (_, tableName, constraintName) = NormalizeNames(schemaName, tableName, constraintName); - - return await AlterTableUsingRecreateTableStrategyAsync( - db, - schemaName, - tableName, - table => table.PrimaryKeyConstraint is null, - table => - { - table.PrimaryKeyConstraint = new DxPrimaryKeyConstraint( - schemaName, - tableName, - constraintName, - columns - ); - - return table; - }, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } - - /// - public override async Task DropPrimaryKeyConstraintIfExistsAsync( - IDbConnection db, - string? schemaName, - string tableName, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - if (string.IsNullOrWhiteSpace(tableName)) - { - throw new ArgumentException("Table name is required.", nameof(tableName)); - } - - if ( - !await DoesPrimaryKeyConstraintExistAsync( - db, - schemaName, - tableName, - tx, - cancellationToken - ) - .ConfigureAwait(false) - ) - { - return false; - } - - return await AlterTableUsingRecreateTableStrategyAsync( - db, - schemaName, - tableName, - table => table.PrimaryKeyConstraint is not null, - table => - { - table.PrimaryKeyConstraint = null; - foreach (var column in table.Columns) - { - column.IsPrimaryKey = false; - } - return table; - }, - tx, - cancellationToken - ) - .ConfigureAwait(false); - } -} +using System.Data; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Providers.Sqlite; + +public partial class SqliteMethods +{ + /// + public override async Task CreatePrimaryKeyConstraintIfNotExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + string constraintName, + DmOrderedColumn[] columns, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + if (string.IsNullOrWhiteSpace(constraintName)) + { + throw new ArgumentException("Constraint name is required.", nameof(constraintName)); + } + + if (columns.Length == 0) + { + throw new ArgumentException("At least one column must be specified.", nameof(columns)); + } + + if ( + await DoesPrimaryKeyConstraintExistAsync( + db, + schemaName, + tableName, + tx, + cancellationToken + ) + .ConfigureAwait(false) + ) + { + return false; + } + + (_, tableName, constraintName) = NormalizeNames(schemaName, tableName, constraintName); + + return await AlterTableUsingRecreateTableStrategyAsync( + db, + schemaName, + tableName, + table => table.PrimaryKeyConstraint is null, + table => + { + table.PrimaryKeyConstraint = new DmPrimaryKeyConstraint( + schemaName, + tableName, + constraintName, + columns + ); + + return table; + }, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } + + /// + public override async Task DropPrimaryKeyConstraintIfExistsAsync( + IDbConnection db, + string? schemaName, + string tableName, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + if (string.IsNullOrWhiteSpace(tableName)) + { + throw new ArgumentException("Table name is required.", nameof(tableName)); + } + + if ( + !await DoesPrimaryKeyConstraintExistAsync( + db, + schemaName, + tableName, + tx, + cancellationToken + ) + .ConfigureAwait(false) + ) + { + return false; + } + + return await AlterTableUsingRecreateTableStrategyAsync( + db, + schemaName, + tableName, + table => table.PrimaryKeyConstraint is not null, + table => + { + table.PrimaryKeyConstraint = null; + foreach (var column in table.Columns) + { + column.IsPrimaryKey = false; + } + return table; + }, + tx, + cancellationToken + ) + .ConfigureAwait(false); + } +} diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethods.Strings.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.Strings.cs similarity index 94% rename from src/DapperMatic/Providers/Sqlite/SqliteMethods.Strings.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.Strings.cs index d9f44e4..fc56acb 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethods.Strings.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.Strings.cs @@ -1,6 +1,6 @@ -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Sqlite; +namespace MJCZone.DapperMatic.Providers.Sqlite; public partial class SqliteMethods { @@ -10,7 +10,7 @@ public partial class SqliteMethods #region Table Strings /// - protected override string SqlInlineColumnNameAndType(DxColumn column, Version dbVersion) + protected override string SqlInlineColumnNameAndType(DmColumn column, Version dbVersion) { // IF the column is an autoincrement column, the type MUST be INTEGER // https://www.sqlite.org/autoinc.html @@ -23,7 +23,7 @@ protected override string SqlInlineColumnNameAndType(DxColumn column, Version db } /// - protected override string SqlInlinePrimaryKeyAutoIncrementColumnConstraint(DxColumn column) + protected override string SqlInlinePrimaryKeyAutoIncrementColumnConstraint(DmColumn column) { return "AUTOINCREMENT"; } diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethods.Tables.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.Tables.cs similarity index 93% rename from src/DapperMatic/Providers/Sqlite/SqliteMethods.Tables.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.Tables.cs index c9569ad..992bd13 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethods.Tables.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.Tables.cs @@ -1,17 +1,17 @@ using System.Data; using System.Data.Common; using System.Text; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; // ReSharper disable LoopCanBeConvertedToQuery // ReSharper disable ForeachCanBeConvertedToQueryUsingAnotherGetEnumerator -namespace DapperMatic.Providers.Sqlite; +namespace MJCZone.DapperMatic.Providers.Sqlite; public partial class SqliteMethods { /// - public override async Task> GetTablesAsync( + public override async Task> GetTablesAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, @@ -47,7 +47,7 @@ FROM sqlite_master ) .ConfigureAwait(false); - var tables = new List(); + var tables = new List(); foreach (var result in results) { var table = SqliteSqlParser.ParseCreateTableStatement( @@ -180,7 +180,7 @@ await ExecuteAsync(db, createTableSql, tx: tx, cancellationToken: cancellationTo /// The transaction. /// The cancellation token. /// A list of indexes. - protected override async Task> GetIndexesInternalAsync( + protected override async Task> GetIndexesInternalAsync( IDbConnection db, string? schemaName, string? tableNameFilter = null, @@ -234,7 +234,7 @@ bool is_descending ) .ConfigureAwait(false); - var indexes = new List(); + var indexes = new List(); foreach ( var group in results.GroupBy(r => new @@ -245,16 +245,16 @@ bool is_descending }) ) { - var index = new DxIndex + var index = new DmIndex { SchemaName = null, TableName = group.Key.table_name, IndexName = group.Key.index_name, IsUnique = group.Key.is_unique, Columns = group - .Select(r => new DxOrderedColumn( + .Select(r => new DmOrderedColumn( r.column_name, - r.is_descending ? DxColumnOrder.Descending : DxColumnOrder.Ascending + r.is_descending ? DmColumnOrder.Descending : DmColumnOrder.Ascending )) .ToList(), }; @@ -279,8 +279,8 @@ private async Task AlterTableUsingRecreateTableStrategyAsync( IDbConnection db, string? schemaName, string tableName, - Func? validateTable, - Func updateTable, + Func? validateTable, + Func updateTable, IDbTransaction? tx, CancellationToken cancellationToken ) @@ -299,7 +299,7 @@ CancellationToken cancellationToken } // create a temporary table with the updated schema - var tmpTable = new DxTable( + var tmpTable = new DmTable( table.SchemaName, table.TableName, [.. table.Columns], @@ -328,8 +328,8 @@ await AlterTableUsingRecreateTableStrategyAsync(db, table, newTable, tx, cancell /// The cancellation token. private async Task AlterTableUsingRecreateTableStrategyAsync( IDbConnection db, - DxTable existingTable, - DxTable updatedTable, + DmTable existingTable, + DmTable updatedTable, IDbTransaction? tx, CancellationToken cancellationToken ) diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethods.UniqueConstraints.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.UniqueConstraints.cs similarity index 93% rename from src/DapperMatic/Providers/Sqlite/SqliteMethods.UniqueConstraints.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.UniqueConstraints.cs index 415695b..4f8b9c7 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethods.UniqueConstraints.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.UniqueConstraints.cs @@ -1,7 +1,7 @@ using System.Data; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Sqlite; +namespace MJCZone.DapperMatic.Providers.Sqlite; public partial class SqliteMethods { @@ -11,7 +11,7 @@ public override async Task CreateUniqueConstraintIfNotExistsAsync( string? schemaName, string tableName, string constraintName, - DxOrderedColumn[] columns, + DmOrderedColumn[] columns, IDbTransaction? tx = null, CancellationToken cancellationToken = default ) @@ -64,7 +64,7 @@ await DoesUniqueConstraintExistAsync( table => { table.UniqueConstraints.Add( - new DxUniqueConstraint(schemaName, tableName, constraintName, columns) + new DmUniqueConstraint(schemaName, tableName, constraintName, columns) ); return table; diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethods.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.cs similarity index 89% rename from src/DapperMatic/Providers/Sqlite/SqliteMethods.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.cs index c12c6e4..2ad7529 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethods.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethods.cs @@ -1,37 +1,37 @@ -using System.Data; -using DapperMatic.Providers.Base; - -namespace DapperMatic.Providers.Sqlite; - -/// -/// Provides SQLite specific database methods. -/// -public partial class SqliteMethods : DatabaseMethodsBase, ISqliteMethods -{ - /// - /// Initializes a new instance of the class. - /// - internal SqliteMethods() - : base(DbProviderType.Sqlite) { } - - /// - public override char[] QuoteChars => ['"']; - - /// - protected override string DefaultSchema => string.Empty; - - /// - public override async Task GetDatabaseVersionAsync( - IDbConnection db, - IDbTransaction? tx = null, - CancellationToken cancellationToken = default - ) - { - // sample output: 3.44.1 - const string sql = "SELECT sqlite_version()"; - var versionString = - await ExecuteScalarAsync(db, sql, tx: tx, cancellationToken: cancellationToken) - .ConfigureAwait(false) ?? string.Empty; - return DbProviderUtils.ExtractVersionFromVersionString(versionString); - } -} +using System.Data; +using MJCZone.DapperMatic.Providers.Base; + +namespace MJCZone.DapperMatic.Providers.Sqlite; + +/// +/// Provides SQLite specific database methods. +/// +public partial class SqliteMethods : DatabaseMethodsBase, ISqliteMethods +{ + /// + /// Initializes a new instance of the class. + /// + internal SqliteMethods() + : base(DbProviderType.Sqlite) { } + + /// + public override char[] QuoteChars => ['"']; + + /// + protected override string DefaultSchema => string.Empty; + + /// + public override async Task GetDatabaseVersionAsync( + IDbConnection db, + IDbTransaction? tx = null, + CancellationToken cancellationToken = default + ) + { + // sample output: 3.44.1 + const string sql = "SELECT sqlite_version()"; + var versionString = + await ExecuteScalarAsync(db, sql, tx: tx, cancellationToken: cancellationToken) + .ConfigureAwait(false) ?? string.Empty; + return DbProviderUtils.ExtractVersionFromVersionString(versionString); + } +} diff --git a/src/DapperMatic/Providers/Sqlite/SqliteMethodsFactory.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethodsFactory.cs similarity index 87% rename from src/DapperMatic/Providers/Sqlite/SqliteMethodsFactory.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethodsFactory.cs index 9dbb7e3..c3e5d40 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteMethodsFactory.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteMethodsFactory.cs @@ -1,28 +1,28 @@ -using System.Data; -using DapperMatic.Interfaces; - -namespace DapperMatic.Providers.Sqlite; - -/// -/// Provides SQLite specific database methods. -/// -public class SqliteMethodsFactory : DatabaseMethodsFactoryBase -{ - /// - /// Initializes a new instance of the class. - /// - /// Database connection. - /// true/false. - public virtual bool SupportsConnectionCustom(IDbConnection db) => false; - - /// - public override bool SupportsConnection(IDbConnection db) => - SupportsConnectionCustom(db) - || (db.GetType().FullName ?? string.Empty).Contains( - "sqlite", - StringComparison.OrdinalIgnoreCase - ); - - /// - protected override IDatabaseMethods CreateMethodsCore() => new SqliteMethods(); -} +using System.Data; +using MJCZone.DapperMatic.Interfaces; + +namespace MJCZone.DapperMatic.Providers.Sqlite; + +/// +/// Provides SQLite specific database methods. +/// +public class SqliteMethodsFactory : DatabaseMethodsFactoryBase +{ + /// + /// Initializes a new instance of the class. + /// + /// Database connection. + /// true/false. + public virtual bool SupportsConnectionCustom(IDbConnection db) => false; + + /// + public override bool SupportsConnection(IDbConnection db) => + SupportsConnectionCustom(db) + || (db.GetType().FullName ?? string.Empty).Contains( + "sqlite", + StringComparison.OrdinalIgnoreCase + ); + + /// + protected override IDatabaseMethods CreateMethodsCore() => new SqliteMethods(); +} diff --git a/src/DapperMatic/Providers/Sqlite/SqliteProviderTypeMap.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteProviderTypeMap.cs similarity index 96% rename from src/DapperMatic/Providers/Sqlite/SqliteProviderTypeMap.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteProviderTypeMap.cs index 3d12a26..a0ee33e 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteProviderTypeMap.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteProviderTypeMap.cs @@ -6,9 +6,9 @@ using System.Text.Json; using System.Text.Json.Nodes; using System.Xml.Linq; -using DapperMatic.Converters; +using MJCZone.DapperMatic.Converters; -namespace DapperMatic.Providers.Sqlite; +namespace MJCZone.DapperMatic.Providers.Sqlite; /// /// Provides SQLite specific database type mapping. diff --git a/src/DapperMatic/Providers/Sqlite/SqliteSqlParser.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteSqlParser.cs similarity index 94% rename from src/DapperMatic/Providers/Sqlite/SqliteSqlParser.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteSqlParser.cs index 6f057e2..0221b79 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteSqlParser.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteSqlParser.cs @@ -1,9 +1,9 @@ using System.Diagnostics.CodeAnalysis; using System.Text; using System.Text.RegularExpressions; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Providers.Sqlite; +namespace MJCZone.DapperMatic.Providers.Sqlite; internal static partial class SqliteSqlParser { @@ -13,7 +13,7 @@ internal static partial class SqliteSqlParser /// The CREATE TABLE statement to parse. /// The provider type map. /// The table schema, or null if the statement is not a CREATE TABLE statement. - public static DxTable? ParseCreateTableStatement( + public static DmTable? ParseCreateTableStatement( string createTableSql, IDbProviderTypeMap providerTypeMap ) @@ -36,7 +36,7 @@ IDbProviderTypeMap providerTypeMap return null; } - var table = new DxTable(null, tableName); + var table = new DmTable(null, tableName); // there are lots of variation of CREATE TABLE statements in SQLite, so we need to handle each variation // we can iterate this process to parse different variations and improve this over time, for now, we will @@ -163,7 +163,7 @@ out var dotnetTypeDescriptor continue; } - var column = new DxColumn( + var column = new DmColumn( null, tableName, columnName, @@ -227,7 +227,7 @@ out var dotnetTypeDescriptor columnName ); table.DefaultConstraints.Add( - new DxDefaultConstraint( + new DmDefaultConstraint( null, tableName, column.ColumnName, @@ -249,11 +249,11 @@ out var dotnetTypeDescriptor columnName ); table.UniqueConstraints.Add( - new DxUniqueConstraint( + new DmUniqueConstraint( null, tableName, uniqueConstraintName, - [new DxOrderedColumn(column.ColumnName)] + [new DmOrderedColumn(column.ColumnName)] ) ); inlineConstraintName = null; @@ -278,7 +278,7 @@ [new DxOrderedColumn(column.ColumnName)] columnName ); table.CheckConstraints.Add( - new DxCheckConstraint( + new DmCheckConstraint( null, tableName, column.ColumnName, @@ -299,7 +299,7 @@ [new DxOrderedColumn(column.ColumnName)] tableName, columnName ); - var columnOrder = DxColumnOrder.Ascending; + var columnOrder = DmColumnOrder.Ascending; if ( columnDefinition .GetChild(i + 1) @@ -307,15 +307,15 @@ [new DxOrderedColumn(column.ColumnName)] ?.Equals("DESC", StringComparison.OrdinalIgnoreCase) == true ) { - columnOrder = DxColumnOrder.Descending; + columnOrder = DmColumnOrder.Descending; // skip the next opt i++; } - table.PrimaryKeyConstraint = new DxPrimaryKeyConstraint( + table.PrimaryKeyConstraint = new DmPrimaryKeyConstraint( null, tableName, pkConstraintName, - [new DxOrderedColumn(column.ColumnName, columnOrder)] + [new DmOrderedColumn(column.ColumnName, columnOrder)] ); inlineConstraintName = null; break; @@ -360,13 +360,13 @@ [new DxOrderedColumn(column.ColumnName, columnOrder)] referenceColumnName ); - var foreignKey = new DxForeignKeyConstraint( + var foreignKey = new DmForeignKeyConstraint( null, tableName, constraintName, - [new DxOrderedColumn(column.ColumnName)], + [new DmOrderedColumn(column.ColumnName)], referencedTableName, - [new DxOrderedColumn(referenceColumnName)] + [new DmOrderedColumn(referenceColumnName)] ); var onDeleteTokenIndex = columnDefinition.FindTokenIndex( @@ -467,7 +467,7 @@ [new DxOrderedColumn(referenceColumnName)] continue; // skip this clause as it's invalid } - table.PrimaryKeyConstraint = new DxPrimaryKeyConstraint( + table.PrimaryKeyConstraint = new DmPrimaryKeyConstraint( null, tableName, inlineConstraintName @@ -508,7 +508,7 @@ [new DxOrderedColumn(referenceColumnName)] continue; // skip this clause as it's invalid } - var ucConstraint = new DxUniqueConstraint( + var ucConstraint = new DmUniqueConstraint( null, tableName, inlineConstraintName @@ -551,7 +551,7 @@ [new DxOrderedColumn(referenceColumnName)] : string.Empty ); table.CheckConstraints.Add( - new DxCheckConstraint( + new DmCheckConstraint( null, tableName, null, @@ -623,7 +623,7 @@ [new DxOrderedColumn(referenceColumnName)] fkReferencedColumnNames ); - var foreignKey = new DxForeignKeyConstraint( + var foreignKey = new DmForeignKeyConstraint( null, tableName, constraintName, @@ -694,7 +694,7 @@ [new DxOrderedColumn(referenceColumnName)] return table; } - private static DxOrderedColumn[] ExtractOrderedColumnsFromClause( + private static DmOrderedColumn[] ExtractOrderedColumnsFromClause( SqlCompoundClause? pkColumnsClause ) { @@ -713,7 +713,7 @@ private static DxOrderedColumn[] ExtractOrderedColumnsFromClause( switch (child) { case SqlWordClause wc: - return new DxOrderedColumn(wc.Text); + return new DmOrderedColumn(wc.Text); case SqlCompoundClause cc: { var ccName = cc.GetChild(0)?.Text; @@ -722,22 +722,22 @@ private static DxOrderedColumn[] ExtractOrderedColumnsFromClause( return null; } - var ccOrder = DxColumnOrder.Ascending; + var ccOrder = DmColumnOrder.Ascending; if ( cc.GetChild(1) ?.Text.Equals("DESC", StringComparison.OrdinalIgnoreCase) == true ) { - ccOrder = DxColumnOrder.Descending; + ccOrder = DmColumnOrder.Descending; } - return new DxOrderedColumn(ccName, ccOrder); + return new DmOrderedColumn(ccName, ccOrder); } default: return null; } }) .Where(oc => oc != null) - .Cast() + .Cast() .ToArray(); return pkOrderedColumns; } diff --git a/src/DapperMatic/Providers/Sqlite/SqliteTypes.cs b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteTypes.cs similarity index 95% rename from src/DapperMatic/Providers/Sqlite/SqliteTypes.cs rename to src/MJCZone.DapperMatic/Providers/Sqlite/SqliteTypes.cs index e873afe..9e556fb 100644 --- a/src/DapperMatic/Providers/Sqlite/SqliteTypes.cs +++ b/src/MJCZone.DapperMatic/Providers/Sqlite/SqliteTypes.cs @@ -1,6 +1,6 @@ using System.Diagnostics.CodeAnalysis; -namespace DapperMatic.Providers.Sqlite; +namespace MJCZone.DapperMatic.Providers.Sqlite; /// /// Provides constants for SQLite data types. diff --git a/src/DapperMatic/SqlTypeDescriptor.cs b/src/MJCZone.DapperMatic/SqlTypeDescriptor.cs similarity index 96% rename from src/DapperMatic/SqlTypeDescriptor.cs rename to src/MJCZone.DapperMatic/SqlTypeDescriptor.cs index 3dbcef0..33196b8 100644 --- a/src/DapperMatic/SqlTypeDescriptor.cs +++ b/src/MJCZone.DapperMatic/SqlTypeDescriptor.cs @@ -1,6 +1,6 @@ using System.Text; -namespace DapperMatic; +namespace MJCZone.DapperMatic; /// /// A descriptor for a SQL type that breaks up the SQL type name into its useful parts, diff --git a/src/DapperMatic/TypeAffinity.cs b/src/MJCZone.DapperMatic/TypeAffinity.cs similarity index 92% rename from src/DapperMatic/TypeAffinity.cs rename to src/MJCZone.DapperMatic/TypeAffinity.cs index 20f91e4..5f22fef 100644 --- a/src/DapperMatic/TypeAffinity.cs +++ b/src/MJCZone.DapperMatic/TypeAffinity.cs @@ -1,4 +1,4 @@ -namespace DapperMatic +namespace MJCZone.DapperMatic { /// /// Specifies the type affinity for a database column. diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Api/DocsProcessorApi.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Api/DocsProcessorApi.cs new file mode 100644 index 0000000..d4bf7de --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Api/DocsProcessorApi.cs @@ -0,0 +1,38 @@ +using Akov.NetDocsProcessor.Helpers; +using Akov.NetDocsProcessor.Input; +using Akov.NetDocsProcessor.Output; +using Akov.NetDocsProcessor.Processors; + +namespace Akov.NetDocsProcessor.Api; + +/// +/// The docs generator. +/// +public class DocsProcessorApi +{ + private readonly IDocsProcessor _docsProcessor; + + public DocsProcessorApi(IDocsProcessor? docsProcessor = null) + { + _docsProcessor = docsProcessor ?? new DocsProcessor(); + } + + /// + /// Obtains data from .net assemblies and generated xml documentation. + /// + /// Paths to the source files. + /// The generation settings. + /// + public virtual IEnumerable ObtainDocumentation( + AssemblyPaths assemblyPaths, + GenerationSettings? settings = null) + { + var assembly = FileReader.ReadAssembly(assemblyPaths.DllPath); + var xmlDoc = FileReader.ReadXml(assemblyPaths.XmlPath); + settings ??= new GenerationSettings(); + + var namespaceCollection = _docsProcessor.PopulateNamespaceCollection(assembly, xmlDoc, settings); + _docsProcessor.AddXmlComments(namespaceCollection, xmlDoc, settings); + return namespaceCollection; + } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Common/ElementType.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Common/ElementType.cs new file mode 100644 index 0000000..932b708 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Common/ElementType.cs @@ -0,0 +1,12 @@ +namespace Akov.NetDocsProcessor.Common; + +public enum ElementType +{ + Namespace, + Class, + Interface, + Record, + Struct, + Enum, + Delegate +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Common/Texts.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Common/Texts.cs new file mode 100644 index 0000000..98e367e --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Common/Texts.cs @@ -0,0 +1,6 @@ +namespace Akov.NetDocsProcessor.Common; + +public static class Texts +{ + public const string XmlCommentNotFound = "NOT FOUND"; +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Compilation/TypeSymbolObject.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Compilation/TypeSymbolObject.cs new file mode 100644 index 0000000..dc66090 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Compilation/TypeSymbolObject.cs @@ -0,0 +1,83 @@ +using System.Collections.Immutable; +using Akov.NetDocsProcessor.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using TypeInfo = System.Reflection.TypeInfo; + +namespace Akov.NetDocsProcessor.Compilation; + +internal class TypeSymbolObject +{ + private TypeSymbolObject() {} + + public static TypeSymbolObject Create(CSharpCompilation compilation, TypeInfo type) + { + var symbolObject = new TypeSymbolObject + { + Type = compilation.GetTypeByMetadataName(type.FullName ?? type.Name) + }; + + if (type.IsEnum) + { + symbolObject.InitializeEnumMembers(); + } + else + { + symbolObject.InitializeMembers(); + } + + return symbolObject; + } + + public INamedTypeSymbol? Type { get; private set; } + public ImmutableArray? Fields { get; private set; } + public ImmutableArray? Constructors { get; private set; } + public ImmutableArray? Methods { get; private set; } + public ImmutableArray? Properties { get; private set; } + public ImmutableArray? Events { get; private set; } + public ImmutableArray? EnumMembers { get; private set; } + + private void InitializeMembers() + { + if (Type is null) return; + + Constructors = Type.Constructors; + + var fields = new List(); + var methods = new List(); + var properties = new List(); + var events = new List(); + + foreach (var member in Type.GetMembers()) + { + switch (member.Kind) + { + case SymbolKind.Field: + fields.Add((IFieldSymbol)member); + break; + case SymbolKind.Property: + properties.Add((IPropertySymbol)member); + break; + case SymbolKind.Method: + var method = (IMethodSymbol)member; + if (!method.IsSpecialMethod()) + methods.Add(method); + break; + case SymbolKind.Event: + events.Add((IEventSymbol)member); + break; + } + } + + Fields = fields.ToImmutableArray(); + Methods = methods.ToImmutableArray(); + Properties = properties.ToImmutableArray(); + Events = events.ToImmutableArray(); + } + + private void InitializeEnumMembers() + { + if (Type is null) return; + EnumMembers = Type.GetMembers(); + } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/AccessLevelExtensions.Filters.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/AccessLevelExtensions.Filters.cs new file mode 100644 index 0000000..fac38e5 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/AccessLevelExtensions.Filters.cs @@ -0,0 +1,25 @@ +using System.Reflection; +using Akov.NetDocsProcessor.Input; + +namespace Akov.NetDocsProcessor.Extensions; + +internal static partial class AccessLevelExtensions +{ + public static IEnumerable OnlyVisible(this Assembly assembly, AccessLevel accessLevel) + => assembly.DefinedTypes.Where(type => type.IsVisibleFor(accessLevel)); + + public static IEnumerable OnlyVisible(this ConstructorInfo[] constructors, AccessLevel accessLevel) + => constructors.Where(ctor => ctor.IsVisibleFor(accessLevel)); + + public static IEnumerable OnlyVisible(this FieldInfo[] fields, AccessLevel accessLevel) + => fields.Where(field => field.IsVisibleFor(accessLevel)); + + public static IEnumerable OnlyVisible(this MethodInfo[] methods, AccessLevel accessLevel) + => methods.Where(method => method.IsVisibleFor(accessLevel)); + + public static IEnumerable OnlyVisible(this PropertyInfo[] properties, AccessLevel accessLevel) + => properties.Where(prop => prop.IsVisibleFor(accessLevel)); + + public static IEnumerable OnlyVisible(this EventInfo[] events, AccessLevel accessLevel) + => events.Where(@event => @event.IsVisibleFor(accessLevel)); +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/AccessLevelExtensions.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/AccessLevelExtensions.cs new file mode 100644 index 0000000..c94272d --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/AccessLevelExtensions.cs @@ -0,0 +1,62 @@ +using System.Reflection; +using Akov.NetDocsProcessor.Input; + +namespace Akov.NetDocsProcessor.Extensions; + +internal static partial class AccessLevelExtensions +{ + public static bool IsVisibleFor(this TypeInfo typeInfo, AccessLevel accessLevel) + => accessLevel switch + { + AccessLevel.Public => typeInfo.IsPublic, + AccessLevel.Protected => typeInfo.IsPublic || typeInfo.IsNestedFamily, + AccessLevel.Internal => typeInfo.IsPublic || typeInfo.IsNestedAssembly, + AccessLevel.ProtectedInternal => typeInfo.IsPublic || typeInfo.IsNestedFamORAssem, + AccessLevel.Private => true, + _ => throw new InvalidOperationException( + $"Method {nameof(IsVisibleFor)} is not defined for {nameof(AccessLevel)} {accessLevel}") + }; + + // Works for constructors and methods. + public static bool IsVisibleFor(this MethodBase method, AccessLevel accessLevel) + => IsVisibleForInternal(method, null, accessLevel); + + public static bool IsVisibleFor(this FieldInfo field, AccessLevel accessLevel) + => IsVisibleForInternal(field, accessLevel); + + public static bool IsVisibleFor(this PropertyInfo property, AccessLevel accessLevel) + => IsVisibleForInternal(property.GetGetMethod(), property.GetSetMethod(), accessLevel); + + public static bool IsVisibleFor(this EventInfo @event, AccessLevel accessLevel) + => IsVisibleForInternal(@event.AddMethod, @event.RemoveMethod, accessLevel); + + private static bool IsVisibleForInternal(MethodBase? method1, MethodBase? method2, AccessLevel accessLevel) + => accessLevel switch + { + AccessLevel.Public => (method1 is not null && method1.IsPublic) || + (method2 is not null && method2.IsPublic), + AccessLevel.Protected => (method1 is not null && (method1.IsPublic || method1.IsFamily)) || + (method2 is not null && (method2.IsPublic || method2.IsFamily)), + AccessLevel.Internal => (method1 is not null && (method1.IsPublic || method1.IsAssembly)) || + (method2 is not null && (method2.IsPublic || method2.IsAssembly)), + AccessLevel.ProtectedInternal => (method1 is not null && + (method1.IsPublic || method1.IsFamilyOrAssembly)) || + (method2 is not null && + (method2.IsPublic || method2.IsFamilyOrAssembly)), + AccessLevel.Private => true, + _ => throw new InvalidOperationException( + $"Method {nameof(IsVisibleFor)} is not defined for {nameof(AccessLevel)} {accessLevel}") + }; + + private static bool IsVisibleForInternal(FieldInfo? field, AccessLevel accessLevel) + => accessLevel switch + { + AccessLevel.Public => field is not null && field.IsPublic, + AccessLevel.Protected => field is not null && (field.IsPublic || field.IsFamily), + AccessLevel.Internal => field is not null && (field.IsPublic || field.IsAssembly), + AccessLevel.ProtectedInternal => field is not null && (field.IsPublic || field.IsFamilyOrAssembly), + AccessLevel.Private => true, + _ => throw new InvalidOperationException( + $"Method {nameof(IsVisibleFor)} is not defined for {nameof(AccessLevel)} {accessLevel}") + }; +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/StringExtensions.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/StringExtensions.cs new file mode 100644 index 0000000..a48f6df --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/StringExtensions.cs @@ -0,0 +1,15 @@ +namespace Akov.NetDocsProcessor.Extensions; + +public static class StringExtensions +{ + public static string TrimRoot(this string resource, string root) + => resource.StartsWith(root) && resource.Length > root.Length + ? resource[(root.Length + 1)..] + : resource; + + public static string TrimBeforeLast(this string resource, char delimiter = '.') + { + int lastIndex = resource.LastIndexOf(delimiter); + return resource[(lastIndex + 1)..]; + } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/SymbolExtensions.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/SymbolExtensions.cs new file mode 100644 index 0000000..539dbb3 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/SymbolExtensions.cs @@ -0,0 +1,199 @@ +using System.Collections.Immutable; +using System.Reflection; +using System.Text.RegularExpressions; +using Akov.NetDocsProcessor.Input; +using Akov.NetDocsProcessor.Output; +using Microsoft.CodeAnalysis; + +namespace Akov.NetDocsProcessor.Extensions; + +internal static class SymbolExtensions +{ + public static IFieldSymbol? FindBy(this ImmutableArray? fields, FieldInfo field) + => fields?.SingleOrDefault(p => p.Name == field.Name); + + public static IMethodSymbol? FindBy(this ImmutableArray? methods, MethodBase method) + { + if (methods is null) return null; + + var methodParams = method.GetParameters().Select(p => p.ParameterType).ToList(); + + foreach (var methodSymbol in methods) + { + if(methodSymbol.Name != method.Name) continue; + + var methodSymbolParams = methodSymbol.Parameters + .Select(p => string.IsNullOrEmpty(p.Type.MetadataName) + ? p.Type.OriginalDefinition.ToString()?.WithoutNamespaces() + : p.Type.MetadataName).ToArray(); + + if (!methodSymbolParams.SequenceEqual(methodParams.Select(m => m.Name))) continue; + + if (methodSymbol.Parameters.Length == 0) return methodSymbol; + + for (int index = 0; index < methodSymbol.Parameters.Length; index++) + { + var typeArgsFromCompilation = methodSymbol.Parameters[index].Type.GetArgsTypeNames(); + var typeArgs = methodParams[index].GetArgsTypeNames(); + + if (typeArgsFromCompilation.SequenceEqual(typeArgs)) + return methodSymbol; + } + } + + return null; + } + + public static IPropertySymbol? FindBy(this ImmutableArray? properties, PropertyInfo property) + => properties?.SingleOrDefault(p => p.Name == property.Name); + + public static IEventSymbol? FindBy(this ImmutableArray? events, EventInfo @event) + => events?.SingleOrDefault(e => e.Name == @event.Name); + + public static string? GetReturnType(this ISymbol symbol) + { + switch (symbol.Kind) + { + case SymbolKind.Method: + var method = (IMethodSymbol)symbol; + if (method.MethodKind != MethodKind.Constructor) + return method.ReturnType.ToString()?.WithoutNamespaces().GetNullableTypeName(); + break; + case SymbolKind.Property: + return ((IPropertySymbol)symbol).Type.ToString()?.WithoutNamespaces().GetNullableTypeName(); + case SymbolKind.Event: + return ((IEventSymbol)symbol).Type.Name; + } + + return null; + } + + public static string? GetShortName(this ISymbol symbol) + { + switch (symbol.Kind) + { + case SymbolKind.Method: + var method = (IMethodSymbol)symbol; + return method.MethodKind == MethodKind.Constructor + ? method.ContainingType.Name + : symbol.Name; + case SymbolKind.Property: + case SymbolKind.Event: + return symbol.Name; + } + + return null; + } + + public static string? GetDisplayName(this ISymbol? symbol) + { + string? FormatParameter(string? parameterSignature) + { + if (parameterSignature is null) return null; + string[] split = parameterSignature.WithoutNamespaces().Split(' '); + return split.Length != 2 + ? parameterSignature : + $"{split[0].GetNullableTypeName()} {split[1]}"; + } + + string AddParametersIfMethod(string symbolAsString) + { + if (symbol!.Kind != SymbolKind.Method) return symbolAsString; + + var method = (IMethodSymbol)symbol; + if (method.Parameters.Length == 0) return symbolAsString; + + var parametersMatch = Regex.Match(symbolAsString, @"\((.*?)\)"); + if (parametersMatch.Success) + { + symbolAsString = symbolAsString.Replace( + parametersMatch.Groups[1].Value, + string.Join(", ", method.Parameters.Select(s => FormatParameter(s.ToString())))); + } + + return symbolAsString; + } + + string? symbolAsString = symbol?.ToString(); + if (symbolAsString is null) return null; + + symbolAsString = AddParametersIfMethod(symbolAsString); + + string? containingType = symbol?.ContainingType.ToString(); + if (containingType is not null) + { + symbolAsString = symbolAsString.Replace(containingType, ""); + } + + // Remove namespaces and concat the substrings + return symbolAsString.WithoutNamespaces(); + } + + public static PayloadInfo GetPayload(this ISymbol symbol) + { + var payload = new PayloadInfo + { + AccessLevel = symbol.DeclaredAccessibility.ToAccessLevel(), + IsAbstract = symbol.IsAbstract, + IsOverride = symbol.IsOverride, + IsSealed = symbol.IsSealed, + IsStatic = symbol.IsStatic, + IsVirtual = symbol.IsVirtual + }; + + switch (symbol) + { + case INamedTypeSymbol type: + payload.IsGenericType = type.IsGenericType; + break; + case IFieldSymbol field: + payload.IsConst = field.IsConst; + payload.IsReadOnlyField = field.IsReadOnly; + break; + case IMethodSymbol method: + payload.IsAsync = method.IsAsync; + payload.IsExtensionMethod = method.IsExtensionMethod; + payload.IsGenericMethod = method.IsGenericMethod; + payload.IsReadOnlyMethod = method.IsReadOnly; + break; + case IPropertySymbol property: + payload.HasGetMethod = property.GetMethod is not null; + payload.HasSetMethod = property.SetMethod is not null; + payload.IsIndexer = property.IsIndexer; + payload.IsRequired = property.IsRequired; + break; + } + + return payload; + } + + public static bool IsSpecialMethod(this IMethodSymbol method) + => method.MethodKind is MethodKind.Constructor + or MethodKind.StaticConstructor + or MethodKind.Destructor + or MethodKind.PropertyGet + or MethodKind.PropertySet + or MethodKind.EventAdd + or MethodKind.EventRaise + or MethodKind.EventRemove + or MethodKind.Conversion + or MethodKind.ExplicitInterfaceImplementation + or MethodKind.UserDefinedOperator; + + private static AccessLevel ToAccessLevel(this Accessibility accessibility) + => accessibility switch + { + Accessibility.Public => AccessLevel.Public, + Accessibility.Internal => AccessLevel.Internal, + Accessibility.Protected => AccessLevel.Protected, + Accessibility.ProtectedAndInternal => AccessLevel.ProtectedInternal, + Accessibility.Private => AccessLevel.Private, + _ => AccessLevel.Private + }; + + private static string WithoutNamespaces(this string symbolAsString) + => string.Concat( + Regex.Split(symbolAsString, @"(\(|\s|\)|>|<)") + .Where(s => s != string.Empty) + .Select(str => str.TrimBeforeLast())); +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeInfoExtensions.Collections.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeInfoExtensions.Collections.cs new file mode 100644 index 0000000..cd0c38e --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeInfoExtensions.Collections.cs @@ -0,0 +1,15 @@ +using System.Reflection; + +namespace Akov.NetDocsProcessor.Extensions; + +internal static partial class TypeInfoExtensions +{ + public static IEnumerable GetAllNamespaces(this List types) + => types + .Where(t => t.Namespace is not null) + .GroupBy(t => t.Namespace) + .Select(g => g.First().Namespace!); + + public static IEnumerable FilterByNamespace(this List types, string @namespace) + => types.Where(t => t.Namespace == @namespace); +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeInfoExtensions.Populate.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeInfoExtensions.Populate.cs new file mode 100644 index 0000000..73f009b --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeInfoExtensions.Populate.cs @@ -0,0 +1,119 @@ +using System.Collections.Immutable; +using System.Reflection; +using Akov.NetDocsProcessor.Helpers; +using Akov.NetDocsProcessor.Input; +using Akov.NetDocsProcessor.Output; +using Microsoft.CodeAnalysis; +using TypeInfo = System.Reflection.TypeInfo; + +namespace Akov.NetDocsProcessor.Extensions; + +internal static partial class TypeInfoExtensions +{ + public static List PopulateConstructors(this TypeInfo typeInfo, TypeDescription parent, ImmutableArray? symbols, AccessLevel accessLevel) + => + typeInfo + .GetTypeConstructors() + .OnlyVisible(accessLevel) + .Select(constructor => + DescriptionHelper.CreateMember( + constructor.GetUniqueName(), + MemberTypes.Constructor, + symbols.FindBy(constructor), + parent.Self)) + .ToList(); + + public static List PopulateFields(this TypeInfo typeInfo, TypeDescription parent, ImmutableArray? symbols, AccessLevel accessLevel) + => + typeInfo + .GetTypeFields() + .OnlyVisible(accessLevel) + .Select(field => + DescriptionHelper.CreateMember( + field.Name, + MemberTypes.Field, + symbols.FindBy(field), + parent.Self)) + .ToList(); + + public static List PopulateMethods(this TypeInfo typeInfo, TypeDescription parent, ImmutableArray? symbols, AccessLevel accessLevel) + => + typeInfo + .GetTypeMethods() + .OnlyVisible(accessLevel) + .Select(method => + DescriptionHelper.CreateMember( + method.GetUniqueName(), + MemberTypes.Method, + symbols.FindBy(method), + parent.Self)) + .ToList(); + + public static List PopulateProperties(this TypeInfo typeInfo, TypeDescription parent, ImmutableArray? symbols, AccessLevel accessLevel) + => + typeInfo + .GetTypeProperties() + .OnlyVisible(accessLevel) + .Select(property => + DescriptionHelper.CreateMember( + property.Name, + MemberTypes.Property, + symbols.FindBy(property), + parent.Self)) + .ToList(); + + public static List PopulateEvents(this TypeInfo typeInfo, TypeDescription parent, ImmutableArray? symbols, AccessLevel accessLevel) + => + typeInfo + .GetTypeEvents() + .OnlyVisible(accessLevel) + .Select(@event => + DescriptionHelper.CreateMember( + @event.Name, + MemberTypes.Event, + symbols.FindBy(@event), + parent.Self)) + .ToList(); + + public static List PopulateEnumMembers(this TypeInfo typeInfo, TypeDescription parent, ImmutableArray? symbols) + { + var result = new List(); + if (!typeInfo.IsEnum || symbols is null) return result; + + result.AddRange( + from ISymbol? symbol in symbols + select DescriptionHelper.CreateEnumMember(symbol, parent.Self)); + + return result; + } + + private static ConstructorInfo[] GetTypeConstructors(this TypeInfo typeInfo) + => typeInfo + .GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) + .Where(m => m.DeclaringType == typeInfo) + .ToArray(); + + private static FieldInfo[] GetTypeFields(this TypeInfo typeInfo) + => typeInfo + .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) + .Where(p => p.DeclaringType == typeInfo) + .ToArray(); + + private static MethodInfo[] GetTypeMethods(this TypeInfo typeInfo) + => typeInfo + .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) + .Where(m => m.DeclaringType == typeInfo && !m.IsSpecialName && !m.IsDefined(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false)) + .ToArray(); + + private static PropertyInfo[] GetTypeProperties(this TypeInfo typeInfo) + => typeInfo + .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) + .Where(p => p.DeclaringType == typeInfo) + .ToArray(); + + private static EventInfo[] GetTypeEvents(this TypeInfo typeInfo) + => typeInfo + .GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) + .Where(e => e.DeclaringType == typeInfo) + .ToArray(); +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeInfoExtensions.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeInfoExtensions.cs new file mode 100644 index 0000000..3968061 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeInfoExtensions.cs @@ -0,0 +1,39 @@ +using Akov.NetDocsProcessor.Common; +using TypeInfo = System.Reflection.TypeInfo; + +namespace Akov.NetDocsProcessor.Extensions; + +internal static partial class TypeInfoExtensions +{ + public static string GetTypeName(this TypeInfo typeInfo) + { + if (!typeInfo.IsNested) + return typeInfo.Name; + + int plusIndex = typeInfo.FullName!.IndexOf("+", StringComparison.Ordinal); + string namespaceAndParentTypeName = typeInfo.FullName.Substring(0, plusIndex); + int lastDotIndex = namespaceAndParentTypeName.LastIndexOf(".", StringComparison.Ordinal); + string parentTypeName = namespaceAndParentTypeName.Substring(lastDotIndex + 1); + string typeName = typeInfo.FullName[plusIndex..].Replace("+", "."); + return string.Concat(parentTypeName, typeName); + } + + // Record structs will be defined as structs. + public static ElementType GetTypeElementType(this TypeInfo typeInfo) + { + if (typeof(Delegate).IsAssignableFrom(typeInfo)) + return ElementType.Delegate; + + if (typeInfo.GetMethod("$") is not null) + return ElementType.Record; + + return typeInfo switch + { + { IsClass: true } => ElementType.Class, + { IsInterface: true } => ElementType.Interface, + { IsValueType: true, IsEnum: false } => ElementType.Struct, + { IsEnum: true } => ElementType.Enum, + _ => throw new InvalidOperationException($"Cannot define the element for {typeInfo.FullName}") + }; + } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeNameExtensions.Arguments.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeNameExtensions.Arguments.cs new file mode 100644 index 0000000..3547068 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeNameExtensions.Arguments.cs @@ -0,0 +1,26 @@ +using Microsoft.CodeAnalysis; + +namespace Akov.NetDocsProcessor.Extensions; + +internal static partial class TypeNameExtensions +{ + public static List GetArgsTypeNames(this Type type) => + type.IsGenericType + ? type.GetGenericArguments().Select(x => x.Name).ToList() + : new List { type.Name }; + + public static List GetArgsTypeNames(this ITypeSymbol symbol) + { + if (symbol is ITypeParameterSymbol parameterSymbol) + return new List { parameterSymbol.Name }; + + // MJC + if (symbol is IArrayTypeSymbol arrayTypeSymbol) + return new List { arrayTypeSymbol.ElementType.Name }; + + var typeSymbol = (INamedTypeSymbol)symbol; + return typeSymbol.IsGenericType + ? typeSymbol.TypeArguments.Select(x => x.Name).ToList() + : new List { typeSymbol.Name }; + } +} diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeNameExtensions.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeNameExtensions.cs new file mode 100644 index 0000000..e66e51a --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/TypeNameExtensions.cs @@ -0,0 +1,119 @@ +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; + +namespace Akov.NetDocsProcessor.Extensions; + +internal static partial class TypeNameExtensions +{ + public static string GetUniqueName(this ConstructorInfo constructor) + { + if (constructor.IsStatic) + return "cctor"; + + var parameters = constructor.GetParameters(); + + return parameters.Length == 0 + ? "ctor" + : $"ctor-{string.Join("-", parameters.Select(p => NormalizeTypeName(p.ParameterType.Name)?.ToLower()))}"; + } + + public static string GetUniqueName(this MethodInfo method) + { + var name = method.Name.ToLower(); + + if (method.IsGenericMethod) + { + var genericArgsNames = method.GetGenericArguments().Select(arg => arg.Name).ToArray(); + name = $"{name}-{genericArgsNames.Length}"; + } + + var parameters = method.GetParameters(); + + return parameters.Length == 0 + ? name + : $"{name}-{string.Join("-", parameters.Select(p => NormalizeTypeName(p.ParameterType.Name)?.ToLower()))}"; + } + + public static string? GetTypeAliasOrName(this string? typeName) + { + if (typeName is null) return null; + + switch (typeName) + { + case "System.Boolean": + case "Boolean": + return "bool"; + case "System.Byte": + case "Byte": + return "byte"; + case "System.Char": + case "Char": + return "char"; + case "System.Decimal": + case "Decimal": + return "decimal"; + case "System.Double": + case "Double": + return "double"; + case "System.Single": + case "Single": + return "float"; + case "System.Int32": + case "Int32": + return "int"; + case "System.UInt32": + case "UInt32": + return "uint"; + case "System.Int64": + case "Int64": + return "long"; + case "System.UInt64": + case "UInt64": + return "ulong"; + case "System.Object": + case "Object": + return "object"; + case "System.Int16": + case "Int16": + return "short"; + case "System.UInt16": + case "UInt16": + return "ushort"; + case "System.String": + case "String": + return "string"; + case "Void": + return "void"; + default: + return typeName; + } + } + + public static string GetNullableTypeName(this string nullableTypeName) + { + if (string.IsNullOrEmpty(nullableTypeName)) + return nullableTypeName; + + var nullableRegex = new Regex(@"^Nullable<(.+)>"); + Match match = nullableRegex.Match(nullableTypeName); + if (!match.Success) return nullableTypeName; + + string innerTypeName = match.Groups[1].Value; + return innerTypeName.EndsWith("?") ? innerTypeName : $"{innerTypeName}?"; + } + + private static string NormalizeTypeName(string? typeName) + { + char[] charsToReplace = { '(', ')', '[', ']', '`' }; + + var sb = new StringBuilder(typeName); + + foreach (char charToReplace in charsToReplace) + { + sb.Replace(charToReplace, '-'); + } + + return sb.ToString(); + } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/XmlMemberElementExtensions.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/XmlMemberElementExtensions.cs new file mode 100644 index 0000000..a0d6328 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Extensions/XmlMemberElementExtensions.cs @@ -0,0 +1,34 @@ +using Akov.NetDocsProcessor.Output; +using Akov.NetDocsProcessor.Xml; + +namespace Akov.NetDocsProcessor.Extensions; + +internal static class XmlMemberElementExtensions +{ + public static void FillBy(this IXmlMemberBaseElement element, XmlMember xmlMember) + { + element.Summary = xmlMember.Summary?.InnerXml?.Trim(); + element.Example = xmlMember.Example?.InnerXml?.Trim(); + element.Remarks = xmlMember.Remarks?.InnerXml?.Trim(); + element.TypeParameters = xmlMember + .TypeParameters?.Select(t => new TypeParameterInfo { Name = t.Name, Text = t.Text }) + .ToList(); + + if (element is IXmlMemberElement member) + { + member.Exceptions = xmlMember + .Exceptions?.Select(e => new ExceptionInfo + { + Text = e.Text, + Reference = e.Reference + }) + .ToList(); + + member.Parameters = xmlMember + .Parameters?.Select(t => new ParameterInfo { Name = t.Name, Text = t.Text }) + .ToList(); + + member.Returns = xmlMember.Returns?.InnerXml; + } + } +} diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Helpers/DescriptionHelper.XmlSummary.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Helpers/DescriptionHelper.XmlSummary.cs new file mode 100644 index 0000000..d7804b2 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Helpers/DescriptionHelper.XmlSummary.cs @@ -0,0 +1,38 @@ +using Akov.NetDocsProcessor.Extensions; +using Akov.NetDocsProcessor.Output; +using Akov.NetDocsProcessor.Xml; + +namespace Akov.NetDocsProcessor.Helpers; + +internal partial class DescriptionHelper +{ + public static void UpdateTypeSummary(TypeDescription typeDescription, List members) + { + var typeData = members.FirstOrDefault(m => m.Name == typeDescription.CommentId); + if(typeData is null) return; + + typeDescription.FillBy(typeData); + } + + public static void UpdateMembers(List memberDescriptions, List members) + { + foreach (var memberDescription in memberDescriptions) + { + var memberData = members.FirstOrDefault(m => m.Name == memberDescription.CommentId); + if (memberData is null) continue; + + memberDescription.FillBy(memberData); + } + } + + public static void UpdateEnumMembers(List memberDescriptions, List members) + { + foreach (var memberDescription in memberDescriptions) + { + var memberData = members.FirstOrDefault(m => m.Name == memberDescription.CommentId); + if (memberData is null) continue; + + memberDescription.FillBy(memberData); + } + } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Helpers/DescriptionHelper.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Helpers/DescriptionHelper.cs new file mode 100644 index 0000000..d57b29d --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Helpers/DescriptionHelper.cs @@ -0,0 +1,74 @@ +using System.Reflection; +using Akov.NetDocsProcessor.Common; +using Akov.NetDocsProcessor.Extensions; +using Akov.NetDocsProcessor.Output; +using Microsoft.CodeAnalysis; +using TypeInfo = System.Reflection.TypeInfo; + +namespace Akov.NetDocsProcessor.Helpers; + +internal partial class DescriptionHelper +{ + public static NamespaceDescription CreateNamespace(string currentNamespace, string rootNamespace) + => new() + { + Self = new PageInfo + { + DisplayName = currentNamespace, + Url = currentNamespace.TrimRoot(rootNamespace), + ElementType = ElementType.Namespace + } + }; + + public static TypeDescription CreateType(TypeInfo typeInfo, INamedTypeSymbol? symbol, PageInfo @namespace) + { + var elementType = typeInfo.GetTypeElementType(); + return new() + { + ElementType = elementType, + Name = typeInfo.Name, + FullName = typeInfo.FullName ?? typeInfo.Name, + CommentId = symbol?.GetDocumentationCommentId() ?? Texts.XmlCommentNotFound, + Self = new PageInfo + { + DisplayName = symbol?.Name ?? typeInfo.Name, + Url = Path.Combine(@namespace.Url, typeInfo.GetTypeName()), + ElementType = elementType + }, + Namespace = @namespace, + PayloadInfo = symbol?.GetPayload() ?? new PayloadInfo() + }; + } + + public static MemberDescription CreateMember(string memberName, MemberTypes memberType, ISymbol? symbol, PageInfo parent) + { + string GetMemberFolder() + => memberType == MemberTypes.Property + ? "properties" + : $"{memberType.ToString().ToLower()}s"; + + return new() + { + Self = new PageInfo + { + DisplayName = symbol.GetDisplayName() ?? memberName, + Url = Path.Combine(parent.Url, GetMemberFolder(), memberName), + }, + CommentId = symbol?.GetDocumentationCommentId() ?? Texts.XmlCommentNotFound, + MemberType = memberType.ToString(), + Name = memberName, + ReturnType = symbol?.GetReturnType(), + Parent = parent, + Title = symbol?.GetShortName(), + PayloadInfo = symbol?.GetPayload() ?? new PayloadInfo() + }; + } + + public static EnumMemberDescription CreateEnumMember(ISymbol symbol, PageInfo parent) + => new() + { + Name = symbol.Name, + CommentId = symbol.GetDocumentationCommentId() ?? Texts.XmlCommentNotFound, + Parent = parent, + }; +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Helpers/FileReader.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Helpers/FileReader.cs new file mode 100644 index 0000000..15e34bc --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Helpers/FileReader.cs @@ -0,0 +1,18 @@ +using System.Reflection; +using System.Xml.Serialization; +using Akov.NetDocsProcessor.Xml; + +namespace Akov.NetDocsProcessor.Helpers; + +internal class FileReader +{ + public static XmlDoc ReadXml(string path) + { + var serializer = new XmlSerializer(typeof(XmlDoc)); + using var reader = new StreamReader(path); + var doc = (XmlDoc?)serializer.Deserialize(reader); + return doc ?? throw new InvalidOperationException($"The xml file {path} was not deserialized correctly"); + } + + public static Assembly ReadAssembly(string path) => Assembly.LoadFile(path); +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Input/AccessLevel.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Input/AccessLevel.cs new file mode 100644 index 0000000..bac9b2d --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Input/AccessLevel.cs @@ -0,0 +1,32 @@ +namespace Akov.NetDocsProcessor.Input; + +/// +/// Represents the access level for types and members that should be put into the documentation. +/// +public enum AccessLevel +{ + /// + /// Only public members to documentation. + /// + Public, + + /// + /// Public + protected members to documentation. + /// + Protected, + + /// + /// Public + internal members to documentation. + /// + Internal, + + /// + /// Public + protected + internal members to documentation. + /// + ProtectedInternal, + + /// + /// All members to documentation. + /// + Private +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Input/AssemblyPaths.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Input/AssemblyPaths.cs new file mode 100644 index 0000000..ad5f1cf --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Input/AssemblyPaths.cs @@ -0,0 +1,33 @@ +namespace Akov.NetDocsProcessor.Input; + +/// +/// Provides the paths for an assembly and its documentation. +/// +public class AssemblyPaths +{ + /// + /// Fill out the paths for an assembly and its documentation. + /// + /// The path to the assembly file. + /// The path to the generated documentation file. + /// + public AssemblyPaths(string dllPath, string xmlPath) + { + DllPath = dllPath ?? throw new ArgumentNullException(nameof(dllPath)); + XmlPath = xmlPath ?? throw new ArgumentNullException(nameof(xmlPath)); + if (!dllPath.EndsWith(".dll")) + throw new ArgumentException($"The `{nameof(dllPath)}` should be ending with `.dll`."); + if (!xmlPath.EndsWith(".xml")) + throw new ArgumentException($"The `{nameof(xmlPath)}` should be ending with `.xml`."); + } + + /// + /// The path to the assembly file. + /// + public string DllPath { get; } + + /// + /// The path to the generated documentation file. + /// + public string XmlPath { get; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Input/GenerationSettings.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Input/GenerationSettings.cs new file mode 100644 index 0000000..c705243 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Input/GenerationSettings.cs @@ -0,0 +1,13 @@ +namespace Akov.NetDocsProcessor.Input; + +/// +/// The set of settings for the documentation output. +/// +public class GenerationSettings +{ + /// + /// Defines which types and members will be removed from the output. + /// The default value is AccessLevel.Public. + /// + public AccessLevel AccessLevel { get; set; } = AccessLevel.Public; +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/EnumMemberDescription.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/EnumMemberDescription.cs new file mode 100644 index 0000000..1e26573 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/EnumMemberDescription.cs @@ -0,0 +1,65 @@ +namespace Akov.NetDocsProcessor.Output; + +public class EnumMemberDescription : IXmlMemberBaseElement +{ + + #if NET7_0_OR_GREATER + + /// + /// The element name. + /// + public required string Name { get; set; } + + /// + /// The element fullname. + /// + public required string CommentId { get; set; } + + /// + /// The reference to the enum page info. + /// + public required PageInfo Parent { get; set; } + +#else + + /// + /// The element name. + /// + public string Name { get; set; } = default!; + + /// + /// The element fullname. + /// + public string CommentId { get; set; } = default!; + + /// + /// The reference to the enum page info. + /// + public PageInfo Parent { get; set; } = default!; + +#endif + + /// + /// The xml summary for the member. + /// + public string? Summary { get; set; } + + /// + /// The xml example for the member. + /// + public string? Example { get; set; } + + /// + /// The remarks for the type. + /// + public string? Remarks { get; set; } + + /// + /// TypeParameters don't exist for enumerations. + /// + public List? TypeParameters + { + get => null; + set {} + } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/ExceptionInfo.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/ExceptionInfo.cs new file mode 100644 index 0000000..5607762 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/ExceptionInfo.cs @@ -0,0 +1,7 @@ +namespace Akov.NetDocsProcessor.Output; + +public class ExceptionInfo +{ + public string? Text { get; set; } + public string? Reference { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/IXmlMemberBaseElement.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/IXmlMemberBaseElement.cs new file mode 100644 index 0000000..bd859c3 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/IXmlMemberBaseElement.cs @@ -0,0 +1,9 @@ +namespace Akov.NetDocsProcessor.Output; + +public interface IXmlMemberBaseElement +{ + public string? Summary { get; set; } + public string? Example { get; set; } + public string? Remarks { get; set; } + public List? TypeParameters { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/IXmlMemberElement.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/IXmlMemberElement.cs new file mode 100644 index 0000000..fae4816 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/IXmlMemberElement.cs @@ -0,0 +1,8 @@ +namespace Akov.NetDocsProcessor.Output; + +public interface IXmlMemberElement : IXmlMemberBaseElement +{ + public string? Returns { get; set; } + public List? Exceptions { get; set; } + public List? Parameters { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/MemberDescription.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/MemberDescription.cs new file mode 100644 index 0000000..e705506 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/MemberDescription.cs @@ -0,0 +1,206 @@ +using System.Text; +using Akov.NetDocsProcessor.Common; +using Akov.NetDocsProcessor.Extensions; +using Akov.NetDocsProcessor.Input; + +namespace Akov.NetDocsProcessor.Output; + +/// +/// The member description for constructors, methods, properties and events. +/// +public class MemberDescription : IXmlMemberElement +{ + +#if NET7_0_OR_GREATER + + /// + /// The main page element e.g. `Method`, `Property`, `Event` etc. + /// + public required string MemberType { get; set; } + + /// + /// The type name. + /// + public required string Name { get; set; } + + /// + /// The type fullname. + /// + public required string CommentId { get; set; } + + /// + /// The reference to the page info. + /// + public required PageInfo Self { get; set; } + + /// + /// The reference to the parent page info. This can be a class, struct, record or interface. + /// + public required PageInfo Parent { get; set; } + + /// + /// The payload. + /// + public required PayloadInfo PayloadInfo { get; set; } + +#else + + /// + /// The main page element e.g. `Method`, `Property`, `Event` etc. + /// + public string MemberType { get; set; } = default!; + + /// + /// The type name. + /// + public string Name { get; set; } = default!; + + /// + /// The type fullname. + /// + public string CommentId { get; set; } = default!; + + /// + /// The reference to the page info. + /// + public PageInfo Self { get; set; } = default!; + + /// + /// The reference to the parent page info. This can be a class, struct, record or interface. + /// + public PageInfo Parent { get; set; } = default!; + + /// + /// The payload. + /// + public PayloadInfo PayloadInfo { get; set; } = default!; + +#endif + + /// + /// The method, event or property return type. + /// + public string? ReturnType { get; set; } + + /// + /// The title for the member. + /// + public string? Title { get; set; } + + /// + /// The xml summary for the member. + /// + public string? Summary { get; set; } + + /// + /// The xml example for the member. + /// + public string? Example { get; set; } + + /// + /// The remarks for the type. + /// + public string? Remarks { get; set; } + + /// + /// The type parameters list. + /// + public List? TypeParameters { get; set; } + + /// + /// The parameters list. + /// + public List? Parameters { get; set; } + + /// + /// The returns for the method. + /// + public string? Returns { get; set; } + + /// + /// The declared exceptions. + /// + public List? Exceptions { get; set; } + + /// + /// The list of the related references. + /// + public List? SeeAlso { get; set; } + + public override string ToString() + { + var builder = new StringBuilder(); + + if (PayloadInfo.AccessLevel == AccessLevel.ProtectedInternal) + { + builder.Append("protected internal "); + } + else + { + builder.Append($"{PayloadInfo.AccessLevel.ToString().ToLower()} "); + } + + if (PayloadInfo.IsAbstract && Parent.ElementType is not ElementType.Interface) + { + builder.Append("abstract "); + } + + if (PayloadInfo.IsOverride) + { + builder.Append("override "); + } + + if (PayloadInfo.IsSealed) + { + builder.Append("sealed "); + } + + if (PayloadInfo.IsStatic) + { + builder.Append(PayloadInfo.IsConst ? "const " : "static "); + } + + if (PayloadInfo.IsReadOnlyField) + { + builder.Append("readonly "); + } + + if (PayloadInfo.IsVirtual) + { + builder.Append("virtual "); + } + + if (PayloadInfo.IsAsync == true) + { + builder.Append("async "); + } + + if (ReturnType is not null) + { + builder.Append($"{ReturnType.GetTypeAliasOrName()} "); + } + + builder.Append($"{Self.DisplayName} "); + + bool isPropertyAndHasGetter = PayloadInfo.HasGetMethod == true; + bool isPropertyAndHasSetter = PayloadInfo.HasSetMethod == true; + + if (!isPropertyAndHasGetter && !isPropertyAndHasSetter) return builder.ToString(); + + builder.Append(" { "); + + if (isPropertyAndHasGetter) + { + builder.Append("get; "); + } + + if (isPropertyAndHasSetter) + { + builder.Append("set; "); + } + + builder.Append("} "); + + return builder.ToString(); + } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/NamespaceDescription.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/NamespaceDescription.cs new file mode 100644 index 0000000..816f2e3 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/NamespaceDescription.cs @@ -0,0 +1,33 @@ +using Akov.NetDocsProcessor.Common; + +namespace Akov.NetDocsProcessor.Output; + +/// +/// The namespace container. +/// +public class NamespaceDescription +{ + +#if NET7_0_OR_GREATER + + /// + /// The reference to the page info. + /// + public required PageInfo Self { get; set; } + +#else + + /// + /// The reference to the page info. + /// + public PageInfo Self { get; set;} = default!; + +#endif + + public ElementType ElementType => ElementType.Namespace; + + /// + /// The list of type descriptions. + /// + public List Types { get; } = new(); +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/PageInfo.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/PageInfo.cs new file mode 100644 index 0000000..30adc06 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/PageInfo.cs @@ -0,0 +1,41 @@ +using Akov.NetDocsProcessor.Common; + +namespace Akov.NetDocsProcessor.Output; + +/// +/// Represents a short page description. +/// +public class PageInfo +{ + +#if NET7_0_OR_GREATER + + /// + /// The page display name. + /// + public required string DisplayName { get; set; } + + /// + /// The page relative url. + /// + public required string Url { get; set; } + +#else + + /// + /// The page display name. + /// + public string DisplayName { get; set; } = default!; + + /// + /// The page relative url. + /// + public string Url { get; set; } = default!; + +#endif + + /// + /// Class or Interface or Delegate etc + /// + public ElementType ElementType { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/ParameterInfo.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/ParameterInfo.cs new file mode 100644 index 0000000..16d4e69 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/ParameterInfo.cs @@ -0,0 +1,7 @@ +namespace Akov.NetDocsProcessor.Output; + +public class ParameterInfo +{ + public string? Name { get; set; } + public string? Text { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/PayloadInfo.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/PayloadInfo.cs new file mode 100644 index 0000000..be0aed3 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/PayloadInfo.cs @@ -0,0 +1,34 @@ +using Akov.NetDocsProcessor.Common; +using Akov.NetDocsProcessor.Input; + +namespace Akov.NetDocsProcessor.Output; + +public class PayloadInfo +{ + // Base + public AccessLevel AccessLevel { get; set; } + public bool IsAbstract { get; set; } + public bool IsOverride { get; set; } + public bool IsSealed { get; set; } + public bool IsStatic { get; set; } + public bool IsVirtual { get; set; } + + // Type + public bool IsGenericType { get; set; } + + // Field + public bool IsConst { get; set; } + public bool IsReadOnlyField { get; set; } + + // Method + public bool? IsAsync { get; set; } + public bool? IsExtensionMethod { get; set; } + public bool? IsGenericMethod { get; set; } + public bool? IsReadOnlyMethod { get; set; } + + // Property + public bool? HasGetMethod { get; set; } + public bool? HasSetMethod { get; set; } + public bool? IsIndexer { get; set; } + public bool? IsRequired { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/TypeDescription.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/TypeDescription.cs new file mode 100644 index 0000000..3274bec --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/TypeDescription.cs @@ -0,0 +1,150 @@ +using Akov.NetDocsProcessor.Common; + +namespace Akov.NetDocsProcessor.Output; + +/// +/// The type description for classes, interfaces, records, structs, enums and delegates. +/// +public class TypeDescription : IXmlMemberBaseElement +{ + public TypeDescription() + { + Constructors = new List(); + Fields = new List(); + Methods = new List(); + Properties = new List(); + Events = new List(); + EnumMembers = new List(); + } + +#if NET7_0_OR_GREATER + + /// + /// The type name. + /// + public required string Name { get; set; } + + /// + /// The type fullname. + /// + public required string FullName { get; set; } + + /// + /// The type fullname. + /// + public required string CommentId { get; set; } + + /// + /// The reference to the page info. + /// + public required PageInfo Self { get; set; } + + /// + /// The reference to the namespace page info. + /// + public required PageInfo Namespace { get; set; } + + /// + /// The payload. + /// + public required PayloadInfo PayloadInfo { get; set; } + +#else + + /// + /// The type name. + /// + public string Name { get; set; } = default!; + + /// + /// The type fullname. + /// + public string FullName { get; set; } = default!; + + /// + /// The type fullname. + /// + public string CommentId { get; set; } = default!; + + /// + /// The reference to the page info. + /// + public PageInfo Self { get; set; } = default!; + + /// + /// The reference to the namespace page info. + /// + public PageInfo Namespace { get; set; } = default!; + + /// + /// The payload. + /// + public PayloadInfo PayloadInfo { get; set; } = default!; + +#endif + + /// + /// The main page element e.g. `Class`, `Interface`, `Record` etc. + /// + public ElementType ElementType { get; set; } + + /// + /// The title for the type. + /// + public string? Title { get; set; } + + /// + /// The xml summary for the type. + /// + public string? Summary { get; set; } + + /// + /// The xml example for the type. + /// + public string? Example { get; set; } + + /// + /// The remarks for the type. + /// + public string? Remarks { get; set; } + + /// + /// The type parameters list. + /// + public List? TypeParameters { get; set; } + + /// + /// The list of constructors. + /// + public List Fields { get; } + + /// + /// The list of constructors. + /// + public List Constructors { get; } + + /// + /// The list of methods. + /// + public List Methods { get; } + + /// + /// The list of properties. + /// + public List Properties { get; } + + /// + /// The list of events. + /// + public List Events { get; } + + /// + /// The list of enums members if type is enumeration. + /// + public List EnumMembers { get; } + + /// + /// The list of the related references. + /// + public List? SeeAlso { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/TypeParameterInfo.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/TypeParameterInfo.cs new file mode 100644 index 0000000..6769194 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Output/TypeParameterInfo.cs @@ -0,0 +1,7 @@ +namespace Akov.NetDocsProcessor.Output; + +public class TypeParameterInfo +{ + public string? Name { get; set; } + public string? Text { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Processors/DocsProcessor.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Processors/DocsProcessor.cs new file mode 100644 index 0000000..899ba36 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Processors/DocsProcessor.cs @@ -0,0 +1,108 @@ +using System.Reflection; +using Akov.NetDocsProcessor.Common; +using Akov.NetDocsProcessor.Compilation; +using Akov.NetDocsProcessor.Extensions; +using Akov.NetDocsProcessor.Helpers; +using Akov.NetDocsProcessor.Input; +using Akov.NetDocsProcessor.Output; +using Akov.NetDocsProcessor.Xml; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Akov.NetDocsProcessor.Processors; + +internal class DocsProcessor : IDocsProcessor +{ + public List PopulateNamespaceCollection(Assembly assembly, XmlDoc xmlDoc, GenerationSettings settings) + { + var result = new List(); + string rootNamespace = xmlDoc.Assembly?.Name ?? "global::"; + var compilation = CSharpCompilation.Create(null) + .AddReferences(MetadataReference.CreateFromFile(assembly.Location)); + + var types = assembly.OnlyVisible(settings.AccessLevel).ToList(); + var namespaceNames = types.GetAllNamespaces().ToList(); + + foreach (var namespaceName in namespaceNames) + { + var namespaceDescription = DescriptionHelper.CreateNamespace(namespaceName, rootNamespace); + var filteredTypes = types.FilterByNamespace(namespaceName); + + foreach (var filteredType in filteredTypes) + { + var symbolObject = TypeSymbolObject.Create(compilation, filteredType); + var typeDescription = DescriptionHelper.CreateType(filteredType, symbolObject.Type, namespaceDescription.Self); + + // No nested objects for members for delegates needed + if (typeDescription.ElementType is ElementType.Delegate) + { + namespaceDescription.Types.Add(typeDescription); + continue; + } + + // No nested objects for enums but the values needed + if (typeDescription.ElementType is ElementType.Enum) + { + var enumMembers = filteredType.PopulateEnumMembers(typeDescription, symbolObject.EnumMembers); + typeDescription.EnumMembers.AddRange(enumMembers); + namespaceDescription.Types.Add(typeDescription); + continue; + } + + var constructors = filteredType.PopulateConstructors(typeDescription, symbolObject.Constructors, settings.AccessLevel); + typeDescription.Constructors.AddRange(constructors); + + var fields = filteredType.PopulateFields(typeDescription, symbolObject.Fields, settings.AccessLevel); + typeDescription.Fields.AddRange(fields); + + var methods = filteredType.PopulateMethods(typeDescription, symbolObject.Methods, settings.AccessLevel); + typeDescription.Methods.AddRange(methods); + + var properties = filteredType.PopulateProperties(typeDescription, symbolObject.Properties, settings.AccessLevel); + typeDescription.Properties.AddRange(properties); + + var events = filteredType.PopulateEvents(typeDescription, symbolObject.Events, settings.AccessLevel); + typeDescription.Events.AddRange(events); + + namespaceDescription.Types.Add(typeDescription); + } + + result.Add(namespaceDescription); + } + + return result; + } + + public void AddXmlComments(List namespaces, XmlDoc xmlDoc, GenerationSettings settings) + { + if(xmlDoc.Members is null) return; + + foreach (var namespaceDescription in namespaces) + { + foreach (var typeDescription in namespaceDescription.Types) + { + DescriptionHelper.UpdateTypeSummary(typeDescription, xmlDoc.Members); + + // No nested objects for for delegates or enums needed + if(typeDescription.ElementType is ElementType.Delegate) continue; + + // No nested objects for for enums but enum members needed + if (typeDescription.ElementType is ElementType.Enum) + { + DescriptionHelper.UpdateEnumMembers(typeDescription.EnumMembers, xmlDoc.Members); + continue; + } + + if (typeDescription.ElementType is not ElementType.Record) + { + DescriptionHelper.UpdateMembers(typeDescription.Constructors, xmlDoc.Members); + } + + DescriptionHelper.UpdateMembers(typeDescription.Fields, xmlDoc.Members); + DescriptionHelper.UpdateMembers(typeDescription.Methods, xmlDoc.Members); + DescriptionHelper.UpdateMembers(typeDescription.Properties, xmlDoc.Members); + DescriptionHelper.UpdateMembers(typeDescription.Events, xmlDoc.Members); + } + } + } +} diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Processors/IDocsProcessor.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Processors/IDocsProcessor.cs new file mode 100644 index 0000000..2ebce09 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Processors/IDocsProcessor.cs @@ -0,0 +1,29 @@ +using System.Reflection; +using Akov.NetDocsProcessor.Input; +using Akov.NetDocsProcessor.Output; +using Akov.NetDocsProcessor.Xml; + +namespace Akov.NetDocsProcessor.Processors; + +/// +/// Represents an interface to populate data from the assembly and xml comments. +/// +public interface IDocsProcessor +{ + /// + /// Populate the collection of NamespaceDescription. + /// + /// The source assembly. + /// The source deserialized xml. + /// The generation settings. + /// The collection of NamespaceDescription. + List PopulateNamespaceCollection(Assembly assembly, XmlDoc xmlDoc, GenerationSettings settings); + + /// + /// Add xml comments to the populated NamespaceDescription list. + /// + /// The NamespaceDescription list. + /// The source deserialized xml. + /// The generation settings. + void AddXmlComments(List namespaces, XmlDoc xmlDoc, GenerationSettings settings); +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlAssembly.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlAssembly.cs new file mode 100644 index 0000000..bdcb9c5 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlAssembly.cs @@ -0,0 +1,10 @@ +using System.Xml.Serialization; + +namespace Akov.NetDocsProcessor.Xml; + +[Serializable] +public class XmlAssembly +{ + [XmlElement("name")] + public string? Name { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlDoc.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlDoc.cs new file mode 100644 index 0000000..5a11be2 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlDoc.cs @@ -0,0 +1,14 @@ +using System.Xml.Serialization; + +namespace Akov.NetDocsProcessor.Xml; + +[Serializable, XmlRoot("doc")] +public class XmlDoc +{ + [XmlElement("assembly")] + public XmlAssembly? Assembly { get; set; } + + [XmlArray("members")] + [XmlArrayItem("member")] + public List? Members { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlException.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlException.cs new file mode 100644 index 0000000..e40f9b4 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlException.cs @@ -0,0 +1,13 @@ +using System.Xml.Serialization; + +namespace Akov.NetDocsProcessor.Xml; + +[Serializable] +public class XmlException +{ + [XmlAttribute("cref")] + public string? Reference { get; set; } + + [XmlText] + public string? Text { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlMember.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlMember.cs new file mode 100644 index 0000000..44732a6 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlMember.cs @@ -0,0 +1,38 @@ +using System.Xml; +using System.Xml.Serialization; + +namespace Akov.NetDocsProcessor.Xml; + +[Serializable] +public class XmlMember +{ + [XmlAttribute("name")] + public string? Name { get; set; } + + [XmlAnyElement("summary")] + public XmlElement? Summary { get; set; } + + [XmlAnyElement("remarks")] + public XmlElement? Remarks { get; set; } + + [XmlAnyElement("example")] + public XmlElement? Example { get; set; } + + [XmlElement("exception")] + public List? Exceptions { get; set; } + + [XmlElement("param")] + public List? Parameters { get; set; } + + [XmlElement("typeparam")] + public List? TypeParameters { get; set; } + + [XmlAnyElement("returns")] + public XmlElement? Returns { get; set; } + + [XmlElement("value")] + public string? Value { get; set; } + + [XmlElement("seealso")] + public List? SeeAlso { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlParameter.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlParameter.cs new file mode 100644 index 0000000..52d51c4 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlParameter.cs @@ -0,0 +1,13 @@ +using System.Xml.Serialization; + +namespace Akov.NetDocsProcessor.Xml; + +[Serializable] +public class XmlParameter +{ + [XmlAttribute("name")] + public string? Name { get; set; } + + [XmlText] + public string? Text { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlSeeAlso.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlSeeAlso.cs new file mode 100644 index 0000000..c3b7e07 --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlSeeAlso.cs @@ -0,0 +1,13 @@ +using System.Xml.Serialization; + +namespace Akov.NetDocsProcessor.Xml; + +[Serializable] +public class XmlSeeAlso +{ + [XmlAttribute("cref")] + public string? Reference { get; set; } + + [XmlElement("summary")] + public string? Summary { get; set; } +} \ No newline at end of file diff --git a/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlTypeParameter.cs b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlTypeParameter.cs new file mode 100644 index 0000000..a7da04d --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/Akov.NetDocsProcessor/Xml/XmlTypeParameter.cs @@ -0,0 +1,13 @@ +using System.Xml.Serialization; + +namespace Akov.NetDocsProcessor.Xml; + +[Serializable] +public class XmlTypeParameter +{ + [XmlAttribute("name")] + public string? Name { get; set; } + + [XmlText] + public string? Text { get; set; } +} \ No newline at end of file diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.CheckConstraints.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.CheckConstraints.cs similarity index 90% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.CheckConstraints.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.CheckConstraints.cs index 367883e..39c22c8 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.CheckConstraints.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.CheckConstraints.cs @@ -1,132 +1,132 @@ -using DapperMatic.Models; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - [Theory] - [InlineData(null)] - [InlineData("my_app")] - protected virtual async Task Can_perform_simple_CRUD_on_CheckConstraints_Async( - string? schemaName - ) - { - using var db = await OpenConnectionAsync(); - await InitFreshSchemaAsync(db, schemaName); - - var supportsCheckConstraints = await db.SupportsCheckConstraintsAsync(); - - var testTableName = "testTableCheckConstraints"; - await db.CreateTableIfNotExistsAsync( - schemaName, - testTableName, - [new DxColumn(schemaName, testTableName, "testColumn", typeof(int))] - ); - - var constraintName = "ck_testTable"; - var exists = await db.DoesCheckConstraintExistAsync( - schemaName, - testTableName, - constraintName - ); - - if (exists) - { - await db.DropCheckConstraintIfExistsAsync(schemaName, testTableName, constraintName); - } - - await db.CreateCheckConstraintIfNotExistsAsync( - schemaName, - testTableName, - null, - constraintName, - "testColumn > 0" - ); - - exists = await db.DoesCheckConstraintExistAsync(schemaName, testTableName, constraintName); - Assert.True(supportsCheckConstraints ? exists : !exists); - - var existingConstraint = await db.GetCheckConstraintAsync( - schemaName, - testTableName, - constraintName - ); - if (!supportsCheckConstraints) - { - Assert.Null(existingConstraint); - } - else - { - Assert.Equal( - constraintName, - existingConstraint?.ConstraintName, - StringComparer.OrdinalIgnoreCase - ); - } - - var checkConstraintNames = await db.GetCheckConstraintNamesAsync(schemaName, testTableName); - if (!supportsCheckConstraints) - { - Assert.Empty(checkConstraintNames); - } - else - { - Assert.Contains(constraintName, checkConstraintNames, StringComparer.OrdinalIgnoreCase); - } - - var dropped = await db.DropCheckConstraintIfExistsAsync( - schemaName, - testTableName, - constraintName - ); - if (!supportsCheckConstraints) - { - Assert.False(dropped); - } - else - { - Assert.True(dropped); - exists = await db.DoesCheckConstraintExistAsync( - schemaName, - testTableName, - constraintName - ); - } - - exists = await db.DoesCheckConstraintExistAsync(schemaName, testTableName, constraintName); - Assert.False(exists); - - await db.DropTableIfExistsAsync(schemaName, testTableName); - - await db.CreateTableIfNotExistsAsync( - schemaName, - testTableName, - [ - new DxColumn(schemaName, testTableName, "testColumn", typeof(int)), - new DxColumn( - schemaName, - testTableName, - "testColumn2", - typeof(int), - checkExpression: "testColumn2 > 0" - ) - ] - ); - - var checkConstraint = await db.GetCheckConstraintOnColumnAsync( - schemaName, - testTableName, - "testColumn2" - ); - if (!supportsCheckConstraints) - { - Assert.Null(checkConstraint); - } - else - { - Assert.NotNull(checkConstraint); - } - - await db.DropTableIfExistsAsync(schemaName, testTableName); - } -} +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + [Theory] + [InlineData(null)] + [InlineData("my_app")] + protected virtual async Task Can_perform_simple_CRUD_on_CheckConstraints_Async( + string? schemaName + ) + { + using var db = await OpenConnectionAsync(); + await InitFreshSchemaAsync(db, schemaName); + + var supportsCheckConstraints = await db.SupportsCheckConstraintsAsync(); + + var testTableName = "testTableCheckConstraints"; + await db.CreateTableIfNotExistsAsync( + schemaName, + testTableName, + [new DmColumn(schemaName, testTableName, "testColumn", typeof(int))] + ); + + var constraintName = "ck_testTable"; + var exists = await db.DoesCheckConstraintExistAsync( + schemaName, + testTableName, + constraintName + ); + + if (exists) + { + await db.DropCheckConstraintIfExistsAsync(schemaName, testTableName, constraintName); + } + + await db.CreateCheckConstraintIfNotExistsAsync( + schemaName, + testTableName, + null, + constraintName, + "testColumn > 0" + ); + + exists = await db.DoesCheckConstraintExistAsync(schemaName, testTableName, constraintName); + Assert.True(supportsCheckConstraints ? exists : !exists); + + var existingConstraint = await db.GetCheckConstraintAsync( + schemaName, + testTableName, + constraintName + ); + if (!supportsCheckConstraints) + { + Assert.Null(existingConstraint); + } + else + { + Assert.Equal( + constraintName, + existingConstraint?.ConstraintName, + StringComparer.OrdinalIgnoreCase + ); + } + + var checkConstraintNames = await db.GetCheckConstraintNamesAsync(schemaName, testTableName); + if (!supportsCheckConstraints) + { + Assert.Empty(checkConstraintNames); + } + else + { + Assert.Contains(constraintName, checkConstraintNames, StringComparer.OrdinalIgnoreCase); + } + + var dropped = await db.DropCheckConstraintIfExistsAsync( + schemaName, + testTableName, + constraintName + ); + if (!supportsCheckConstraints) + { + Assert.False(dropped); + } + else + { + Assert.True(dropped); + exists = await db.DoesCheckConstraintExistAsync( + schemaName, + testTableName, + constraintName + ); + } + + exists = await db.DoesCheckConstraintExistAsync(schemaName, testTableName, constraintName); + Assert.False(exists); + + await db.DropTableIfExistsAsync(schemaName, testTableName); + + await db.CreateTableIfNotExistsAsync( + schemaName, + testTableName, + [ + new DmColumn(schemaName, testTableName, "testColumn", typeof(int)), + new DmColumn( + schemaName, + testTableName, + "testColumn2", + typeof(int), + checkExpression: "testColumn2 > 0" + ) + ] + ); + + var checkConstraint = await db.GetCheckConstraintOnColumnAsync( + schemaName, + testTableName, + "testColumn2" + ); + if (!supportsCheckConstraints) + { + Assert.Null(checkConstraint); + } + else + { + Assert.NotNull(checkConstraint); + } + + await db.DropTableIfExistsAsync(schemaName, testTableName); + } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.Columns.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Columns.cs similarity index 93% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.Columns.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Columns.cs index ea3fdf6..ba3e22c 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.Columns.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Columns.cs @@ -1,290 +1,290 @@ -using DapperMatic.Models; -using DapperMatic.Providers; -using DbQueryLogging; -using Npgsql; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - [Theory] - [InlineData(null)] - [InlineData("my_app")] - protected virtual async Task Can_set_common_default_expressions_on_Columns_Async( - string? schemaName - ) - { - using var db = await OpenConnectionAsync(); - await InitFreshSchemaAsync(db, schemaName); - - const string tableName = "testTableWithExpressions"; - const string columnName1 = "testColumnWithDefaultDate"; - const string columnName2 = "testColumnWithDefaultDateSetAfterCreate"; - const string columnName3 = "testColumnWithDefaultUuid"; - const string columnName4 = "testColumnWithDefaultShort"; - const string columnName5 = "testColumnWithDefaultBool"; - - string? defaultDateTimeSql = null; - string? defaultGuidSql = null; - var dbType = db.GetDbProviderType(); - - var version = await db.GetDatabaseVersionAsync(); - - switch (dbType) - { - case DbProviderType.SqlServer: - defaultDateTimeSql = "GETUTCDATE()"; - defaultGuidSql = "NEWID()"; - break; - case DbProviderType.Sqlite: - defaultDateTimeSql = "CURRENT_TIMESTAMP"; - //this could be supported IF the sqlite UUID extension was loaded and enabled - //defaultGuidSql = "uuid_blob(uuid())"; - defaultGuidSql = null; - break; - case DbProviderType.PostgreSql: - defaultDateTimeSql = "CURRENT_TIMESTAMP"; - defaultGuidSql = "uuid_generate_v4()"; - break; - case DbProviderType.MySql: - defaultDateTimeSql = version > new Version(5, 6, 5) ? "CURRENT_TIMESTAMP(6)" : null; - // only supported after 8.0.13 - // LEADS TO THIS ERROR: - // Statement is unsafe because it uses a system function that may return a different value on the replication slave. - // MySQL isn't a good database for auto-generating GUIDs. Don't do it! - // defaultGuidSql = - // version > new Version(8, 0, 13) && version < new Version(10, 0, 0) - // ? "(UUID())" - // : null; - defaultGuidSql = null; - break; - } - - // Create table with a column with an expression - var tableCreated = await db.CreateTableIfNotExistsAsync( - schemaName, - tableName, - [ - new DxColumn( - schemaName, - tableName, - "id", - typeof(int), - isPrimaryKey: true, - isAutoIncrement: true - ), - new DxColumn( - schemaName, - tableName, - columnName1, - typeof(DateTime), - defaultExpression: defaultDateTimeSql - ) - ] - ); - Assert.True(tableCreated); - - // Add a column with a default expression after the table is created - var columnCreated = await db.CreateColumnIfNotExistsAsync( - new DxColumn( - schemaName, - tableName, - columnName2, - typeof(DateTime), - defaultExpression: defaultDateTimeSql - ) - ); - Assert.True(columnCreated); - - if (defaultGuidSql != null) - { - // Add a column with a default expression after the table is created - columnCreated = await db.CreateColumnIfNotExistsAsync( - new DxColumn( - schemaName, - tableName, - columnName3, - typeof(Guid), - defaultExpression: defaultGuidSql - ) - ); - Assert.True(columnCreated); - } - - // Add a column with a default expression after the table is created - columnCreated = await db.CreateColumnIfNotExistsAsync( - new DxColumn(schemaName, tableName, columnName4, typeof(short), defaultExpression: "4") - ); - Assert.True(columnCreated); - - if ( - db is NpgsqlConnection - || db is LoggedDbConnection loggedDbConnection - && loggedDbConnection.Inner is NpgsqlConnection - ) - { - columnCreated = await db.CreateColumnIfNotExistsAsync( - new DxColumn( - schemaName, - tableName, - columnName5, - typeof(bool), - defaultExpression: "true" - ) - ); - Assert.True(columnCreated); - } - else - { - // other databases take an integer - columnCreated = await db.CreateColumnIfNotExistsAsync( - new DxColumn( - schemaName, - tableName, - columnName5, - typeof(bool), - defaultExpression: "1" - ) - ); - Assert.True(columnCreated); - } - - // Now check to make sure the default expressions are set - var table = await db.GetTableAsync(schemaName, tableName); - var columns = await db.GetColumnsAsync(schemaName, tableName); - var column1 = columns.SingleOrDefault(c => - c.ColumnName.Equals(columnName1, StringComparison.OrdinalIgnoreCase) - ); - var column2 = columns.SingleOrDefault(c => - c.ColumnName.Equals(columnName2, StringComparison.OrdinalIgnoreCase) - ); - var column4 = columns.SingleOrDefault(c => - c.ColumnName.Equals(columnName4, StringComparison.OrdinalIgnoreCase) - ); - var column5 = columns.SingleOrDefault(c => - c.ColumnName.Equals(columnName5, StringComparison.OrdinalIgnoreCase) - ); - - Assert.NotNull(column1); - Assert.NotNull(column1.DefaultExpression); - Assert.NotEmpty(column1.DefaultExpression); - - Assert.NotNull(column2); - Assert.NotNull(column2.DefaultExpression); - Assert.NotEmpty(column2.DefaultExpression); - - Assert.NotNull(column4); - Assert.NotNull(column4.DefaultExpression); - Assert.NotEmpty(column4.DefaultExpression); - - Assert.NotNull(column5); - Assert.NotNull(column5.DefaultExpression); - Assert.NotEmpty(column5.DefaultExpression); - - if (defaultGuidSql != null) - { - var column3 = columns.SingleOrDefault(c => - c.ColumnName.Equals(columnName3, StringComparison.OrdinalIgnoreCase) - ); - Assert.NotNull(column3); - Assert.NotNull(column3.DefaultExpression); - Assert.NotEmpty(column3.DefaultExpression); - } - - // Now try to remove the default expressions (first using the column name, then using the constraint name) - Assert.True( - await db.DropDefaultConstraintOnColumnIfExistsAsync(schemaName, tableName, columnName1) - ); - var constraintName = table - ?.DefaultConstraints.First(dc => - dc.ColumnName.Equals(column2.ColumnName, StringComparison.OrdinalIgnoreCase) - ) - .ConstraintName; - Assert.NotNull(constraintName); - Assert.NotEmpty(constraintName); - Assert.True( - await db.DropDefaultConstraintIfExistsAsync(schemaName, tableName, constraintName) - ); - - // TODO: timestamp columns can't have default values dropped in MariaDB, WEIRD! - // might have to change syntax to use ALTER TABLE table_name MODIFY COLUMN column_name TIMESTAMP NULL; - if ( - db.GetDbProviderType() != DbProviderType.MySql - || (version.Major != 10 && version.Major != 11) - ) - { - var table2 = await db.GetTableAsync(schemaName, tableName); - columns = await db.GetColumnsAsync(schemaName, tableName); - column1 = columns.SingleOrDefault(c => - c.ColumnName.Equals(columnName1, StringComparison.OrdinalIgnoreCase) - ); - column2 = columns.SingleOrDefault(c => - c.ColumnName.Equals(columnName2, StringComparison.OrdinalIgnoreCase) - ); - - Assert.Equal(table!.DefaultConstraints.Count - 2, table2!.DefaultConstraints.Count); - - Assert.NotNull(column1); - Assert.Null(column1.DefaultExpression); - - Assert.NotNull(column2); - Assert.Null(column2.DefaultExpression); - } - - await db.DropTableIfExistsAsync(schemaName, tableName); - } - - [Theory] - [InlineData(null)] - [InlineData("my_app")] - protected virtual async Task Can_perform_simple_CRUD_on_Columns_Async(string? schemaName) - { - using var db = await OpenConnectionAsync(); - await InitFreshSchemaAsync(db, schemaName); - - var dbType = db.GetDbProviderType(); - var dbTypeMap = db.GetProviderTypeMap(); - - const string tableName = "testWithTypedColumns"; - const string columnName = "testColumn"; - - await db.CreateTableIfNotExistsAsync( - schemaName, - tableName, - [ - new DxColumn( - schemaName, - tableName, - "id", - typeof(int), - isPrimaryKey: true, - isAutoIncrement: true - ) - ] - ); - - // try adding a columnName of all the supported types - var i = 0; - foreach (var type in GetSupportedTypes(dbTypeMap)) - { - // create a column with the supported type - var uniqueColumnName = $"{columnName}_{type.Name.ToAlpha()}_{i++}"; - var column = new DxColumn( - schemaName, - tableName, - uniqueColumnName, - type, - isNullable: true - ); - var columnCreated = await db.CreateColumnIfNotExistsAsync(column); - - if (!columnCreated) - { - columnCreated = await db.CreateColumnIfNotExistsAsync(column); - Assert.True(columnCreated); - } - } - - await db.DropTableIfExistsAsync(schemaName, tableName); - } -} +using DbQueryLogging; +using MJCZone.DapperMatic.Models; +using MJCZone.DapperMatic.Providers; +using Npgsql; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + [Theory] + [InlineData(null)] + [InlineData("my_app")] + protected virtual async Task Can_set_common_default_expressions_on_Columns_Async( + string? schemaName + ) + { + using var db = await OpenConnectionAsync(); + await InitFreshSchemaAsync(db, schemaName); + + const string tableName = "testTableWithExpressions"; + const string columnName1 = "testColumnWithDefaultDate"; + const string columnName2 = "testColumnWithDefaultDateSetAfterCreate"; + const string columnName3 = "testColumnWithDefaultUuid"; + const string columnName4 = "testColumnWithDefaultShort"; + const string columnName5 = "testColumnWithDefaultBool"; + + string? defaultDateTimeSql = null; + string? defaultGuidSql = null; + var dbType = db.GetDbProviderType(); + + var version = await db.GetDatabaseVersionAsync(); + + switch (dbType) + { + case DbProviderType.SqlServer: + defaultDateTimeSql = "GETUTCDATE()"; + defaultGuidSql = "NEWID()"; + break; + case DbProviderType.Sqlite: + defaultDateTimeSql = "CURRENT_TIMESTAMP"; + //this could be supported IF the sqlite UUID extension was loaded and enabled + //defaultGuidSql = "uuid_blob(uuid())"; + defaultGuidSql = null; + break; + case DbProviderType.PostgreSql: + defaultDateTimeSql = "CURRENT_TIMESTAMP"; + defaultGuidSql = "uuid_generate_v4()"; + break; + case DbProviderType.MySql: + defaultDateTimeSql = version > new Version(5, 6, 5) ? "CURRENT_TIMESTAMP(6)" : null; + // only supported after 8.0.13 + // LEADS TO THIS ERROR: + // Statement is unsafe because it uses a system function that may return a different value on the replication slave. + // MySQL isn't a good database for auto-generating GUIDs. Don't do it! + // defaultGuidSql = + // version > new Version(8, 0, 13) && version < new Version(10, 0, 0) + // ? "(UUID())" + // : null; + defaultGuidSql = null; + break; + } + + // Create table with a column with an expression + var tableCreated = await db.CreateTableIfNotExistsAsync( + schemaName, + tableName, + [ + new DmColumn( + schemaName, + tableName, + "id", + typeof(int), + isPrimaryKey: true, + isAutoIncrement: true + ), + new DmColumn( + schemaName, + tableName, + columnName1, + typeof(DateTime), + defaultExpression: defaultDateTimeSql + ) + ] + ); + Assert.True(tableCreated); + + // Add a column with a default expression after the table is created + var columnCreated = await db.CreateColumnIfNotExistsAsync( + new DmColumn( + schemaName, + tableName, + columnName2, + typeof(DateTime), + defaultExpression: defaultDateTimeSql + ) + ); + Assert.True(columnCreated); + + if (defaultGuidSql != null) + { + // Add a column with a default expression after the table is created + columnCreated = await db.CreateColumnIfNotExistsAsync( + new DmColumn( + schemaName, + tableName, + columnName3, + typeof(Guid), + defaultExpression: defaultGuidSql + ) + ); + Assert.True(columnCreated); + } + + // Add a column with a default expression after the table is created + columnCreated = await db.CreateColumnIfNotExistsAsync( + new DmColumn(schemaName, tableName, columnName4, typeof(short), defaultExpression: "4") + ); + Assert.True(columnCreated); + + if ( + db is NpgsqlConnection + || db is LoggedDbConnection loggedDbConnection + && loggedDbConnection.Inner is NpgsqlConnection + ) + { + columnCreated = await db.CreateColumnIfNotExistsAsync( + new DmColumn( + schemaName, + tableName, + columnName5, + typeof(bool), + defaultExpression: "true" + ) + ); + Assert.True(columnCreated); + } + else + { + // other databases take an integer + columnCreated = await db.CreateColumnIfNotExistsAsync( + new DmColumn( + schemaName, + tableName, + columnName5, + typeof(bool), + defaultExpression: "1" + ) + ); + Assert.True(columnCreated); + } + + // Now check to make sure the default expressions are set + var table = await db.GetTableAsync(schemaName, tableName); + var columns = await db.GetColumnsAsync(schemaName, tableName); + var column1 = columns.SingleOrDefault(c => + c.ColumnName.Equals(columnName1, StringComparison.OrdinalIgnoreCase) + ); + var column2 = columns.SingleOrDefault(c => + c.ColumnName.Equals(columnName2, StringComparison.OrdinalIgnoreCase) + ); + var column4 = columns.SingleOrDefault(c => + c.ColumnName.Equals(columnName4, StringComparison.OrdinalIgnoreCase) + ); + var column5 = columns.SingleOrDefault(c => + c.ColumnName.Equals(columnName5, StringComparison.OrdinalIgnoreCase) + ); + + Assert.NotNull(column1); + Assert.NotNull(column1.DefaultExpression); + Assert.NotEmpty(column1.DefaultExpression); + + Assert.NotNull(column2); + Assert.NotNull(column2.DefaultExpression); + Assert.NotEmpty(column2.DefaultExpression); + + Assert.NotNull(column4); + Assert.NotNull(column4.DefaultExpression); + Assert.NotEmpty(column4.DefaultExpression); + + Assert.NotNull(column5); + Assert.NotNull(column5.DefaultExpression); + Assert.NotEmpty(column5.DefaultExpression); + + if (defaultGuidSql != null) + { + var column3 = columns.SingleOrDefault(c => + c.ColumnName.Equals(columnName3, StringComparison.OrdinalIgnoreCase) + ); + Assert.NotNull(column3); + Assert.NotNull(column3.DefaultExpression); + Assert.NotEmpty(column3.DefaultExpression); + } + + // Now try to remove the default expressions (first using the column name, then using the constraint name) + Assert.True( + await db.DropDefaultConstraintOnColumnIfExistsAsync(schemaName, tableName, columnName1) + ); + var constraintName = table + ?.DefaultConstraints.First(dc => + dc.ColumnName.Equals(column2.ColumnName, StringComparison.OrdinalIgnoreCase) + ) + .ConstraintName; + Assert.NotNull(constraintName); + Assert.NotEmpty(constraintName); + Assert.True( + await db.DropDefaultConstraintIfExistsAsync(schemaName, tableName, constraintName) + ); + + // TODO: timestamp columns can't have default values dropped in MariaDB, WEIRD! + // might have to change syntax to use ALTER TABLE table_name MODIFY COLUMN column_name TIMESTAMP NULL; + if ( + db.GetDbProviderType() != DbProviderType.MySql + || (version.Major != 10 && version.Major != 11) + ) + { + var table2 = await db.GetTableAsync(schemaName, tableName); + columns = await db.GetColumnsAsync(schemaName, tableName); + column1 = columns.SingleOrDefault(c => + c.ColumnName.Equals(columnName1, StringComparison.OrdinalIgnoreCase) + ); + column2 = columns.SingleOrDefault(c => + c.ColumnName.Equals(columnName2, StringComparison.OrdinalIgnoreCase) + ); + + Assert.Equal(table!.DefaultConstraints.Count - 2, table2!.DefaultConstraints.Count); + + Assert.NotNull(column1); + Assert.Null(column1.DefaultExpression); + + Assert.NotNull(column2); + Assert.Null(column2.DefaultExpression); + } + + await db.DropTableIfExistsAsync(schemaName, tableName); + } + + [Theory] + [InlineData(null)] + [InlineData("my_app")] + protected virtual async Task Can_perform_simple_CRUD_on_Columns_Async(string? schemaName) + { + using var db = await OpenConnectionAsync(); + await InitFreshSchemaAsync(db, schemaName); + + var dbType = db.GetDbProviderType(); + var dbTypeMap = db.GetProviderTypeMap(); + + const string tableName = "testWithTypedColumns"; + const string columnName = "testColumn"; + + await db.CreateTableIfNotExistsAsync( + schemaName, + tableName, + [ + new DmColumn( + schemaName, + tableName, + "id", + typeof(int), + isPrimaryKey: true, + isAutoIncrement: true + ) + ] + ); + + // try adding a columnName of all the supported types + var i = 0; + foreach (var type in GetSupportedTypes(dbTypeMap)) + { + // create a column with the supported type + var uniqueColumnName = $"{columnName}_{type.Name.ToAlpha()}_{i++}"; + var column = new DmColumn( + schemaName, + tableName, + uniqueColumnName, + type, + isNullable: true + ); + var columnCreated = await db.CreateColumnIfNotExistsAsync(column); + + if (!columnCreated) + { + columnCreated = await db.CreateColumnIfNotExistsAsync(column); + Assert.True(columnCreated); + } + } + + await db.DropTableIfExistsAsync(schemaName, tableName); + } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.DefaultConstraints.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.DefaultConstraints.cs similarity index 86% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.DefaultConstraints.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.DefaultConstraints.cs index a9fa468..f1cf8f9 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.DefaultConstraints.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.DefaultConstraints.cs @@ -1,97 +1,97 @@ -using DapperMatic.Models; -using DapperMatic.Providers; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - [Theory] - [InlineData(null)] - [InlineData("my_app")] - protected virtual async Task Can_perform_simple_CRUD_on_DefaultConstraints_Async( - string? schemaName - ) - { - using var db = await OpenConnectionAsync(); - await InitFreshSchemaAsync(db, schemaName); - - var testTableName = "testTableDefaultConstraints"; - var testColumnName = "testColumn"; - await db.CreateTableIfNotExistsAsync( - schemaName, - testTableName, - [new DxColumn(schemaName, testTableName, testColumnName, typeof(int))] - ); - - // in MySQL, default constraints are not named, so this MUST use the ProviderUtils method which is what DapperMatic uses internally - var constraintName = DbProviderUtils.GenerateDefaultConstraintName( - testTableName, - testColumnName - ); - var exists = await db.DoesDefaultConstraintExistAsync( - schemaName, - testTableName, - constraintName - ); - if (exists) - { - await db.DropDefaultConstraintIfExistsAsync(schemaName, testTableName, constraintName); - } - - await db.CreateDefaultConstraintIfNotExistsAsync( - schemaName, - testTableName, - testColumnName, - constraintName, - "0" - ); - var existingConstraint = await db.GetDefaultConstraintAsync( - schemaName, - testTableName, - constraintName - ); - Assert.Equal(constraintName, existingConstraint?.ConstraintName, true); - - var defaultConstraintNames = await db.GetDefaultConstraintNamesAsync( - schemaName, - testTableName - ); - Assert.Contains(constraintName, defaultConstraintNames, StringComparer.OrdinalIgnoreCase); - - await db.DropDefaultConstraintIfExistsAsync(schemaName, testTableName, constraintName); - exists = await db.DoesDefaultConstraintExistAsync( - schemaName, - testTableName, - constraintName - ); - Assert.False(exists); - - await db.DropTableIfExistsAsync(schemaName, testTableName); - - await db.CreateTableIfNotExistsAsync( - schemaName, - testTableName, - [ - new DxColumn(schemaName, testTableName, testColumnName, typeof(int)), - new DxColumn( - schemaName, - testTableName, - "testColumn2", - typeof(int), - defaultExpression: "0" - ) - ] - ); - var defaultConstraint = await db.GetDefaultConstraintOnColumnAsync( - schemaName, - testTableName, - "testColumn2" - ); - Assert.NotNull(defaultConstraint); - - var tableDeleted = await db.DropTableIfExistsAsync(schemaName, testTableName); - Assert.True(tableDeleted); - - await InitFreshSchemaAsync(db, schemaName); - } -} +using MJCZone.DapperMatic.Models; +using MJCZone.DapperMatic.Providers; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + [Theory] + [InlineData(null)] + [InlineData("my_app")] + protected virtual async Task Can_perform_simple_CRUD_on_DefaultConstraints_Async( + string? schemaName + ) + { + using var db = await OpenConnectionAsync(); + await InitFreshSchemaAsync(db, schemaName); + + var testTableName = "testTableDefaultConstraints"; + var testColumnName = "testColumn"; + await db.CreateTableIfNotExistsAsync( + schemaName, + testTableName, + [new DmColumn(schemaName, testTableName, testColumnName, typeof(int))] + ); + + // in MySQL, default constraints are not named, so this MUST use the ProviderUtils method which is what MJCZone.DapperMatic uses internally + var constraintName = DbProviderUtils.GenerateDefaultConstraintName( + testTableName, + testColumnName + ); + var exists = await db.DoesDefaultConstraintExistAsync( + schemaName, + testTableName, + constraintName + ); + if (exists) + { + await db.DropDefaultConstraintIfExistsAsync(schemaName, testTableName, constraintName); + } + + await db.CreateDefaultConstraintIfNotExistsAsync( + schemaName, + testTableName, + testColumnName, + constraintName, + "0" + ); + var existingConstraint = await db.GetDefaultConstraintAsync( + schemaName, + testTableName, + constraintName + ); + Assert.Equal(constraintName, existingConstraint?.ConstraintName, true); + + var defaultConstraintNames = await db.GetDefaultConstraintNamesAsync( + schemaName, + testTableName + ); + Assert.Contains(constraintName, defaultConstraintNames, StringComparer.OrdinalIgnoreCase); + + await db.DropDefaultConstraintIfExistsAsync(schemaName, testTableName, constraintName); + exists = await db.DoesDefaultConstraintExistAsync( + schemaName, + testTableName, + constraintName + ); + Assert.False(exists); + + await db.DropTableIfExistsAsync(schemaName, testTableName); + + await db.CreateTableIfNotExistsAsync( + schemaName, + testTableName, + [ + new DmColumn(schemaName, testTableName, testColumnName, typeof(int)), + new DmColumn( + schemaName, + testTableName, + "testColumn2", + typeof(int), + defaultExpression: "0" + ) + ] + ); + var defaultConstraint = await db.GetDefaultConstraintOnColumnAsync( + schemaName, + testTableName, + "testColumn2" + ); + Assert.NotNull(defaultConstraint); + + var tableDeleted = await db.DropTableIfExistsAsync(schemaName, testTableName); + Assert.True(tableDeleted); + + await InitFreshSchemaAsync(db, schemaName); + } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.ForeignKeyConstraints.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.ForeignKeyConstraints.cs similarity index 90% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.ForeignKeyConstraints.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.ForeignKeyConstraints.cs index 6e18917..c552502 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.ForeignKeyConstraints.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.ForeignKeyConstraints.cs @@ -1,123 +1,123 @@ -using DapperMatic.Models; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - [Theory] - [InlineData(null)] - [InlineData("my_app")] - protected virtual async Task Can_perform_simple_CRUD_on_ForeignKeyConstraints_Async( - string? schemaName - ) - { - using var db = await OpenConnectionAsync(); - await InitFreshSchemaAsync(db, schemaName); - - const string tableName = "testWithFk"; - const string columnName = "testFkColumn"; - const string foreignKeyName = "testFk"; - const string refTableName = "testRefPk"; - const string refTableColumn = "id"; - - await db.CreateTableIfNotExistsAsync( - schemaName, - tableName, - [ - new DxColumn( - schemaName, - tableName, - columnName, - typeof(int), - defaultExpression: "1", - isNullable: false - ) - ] - ); - await db.CreateTableIfNotExistsAsync( - schemaName, - refTableName, - [ - new DxColumn( - schemaName, - refTableName, - refTableColumn, - typeof(int), - defaultExpression: "1", - isPrimaryKey: true, - isNullable: false - ) - ] - ); - - Output.WriteLine("Foreign Key Exists: {0}.{1}", tableName, foreignKeyName); - var exists = await db.DoesForeignKeyConstraintExistAsync( - schemaName, - tableName, - foreignKeyName - ); - Assert.False(exists); - - Output.WriteLine("Creating foreign key: {0}.{1}", tableName, foreignKeyName); - var created = await db.CreateForeignKeyConstraintIfNotExistsAsync( - schemaName, - tableName, - foreignKeyName, - [new DxOrderedColumn(columnName)], - refTableName, - [new DxOrderedColumn("id")], - onDelete: DxForeignKeyAction.Cascade - ); - Assert.True(created); - - Output.WriteLine("Foreign Key Exists: {0}.{1}", tableName, foreignKeyName); - exists = await db.DoesForeignKeyConstraintExistAsync(schemaName, tableName, foreignKeyName); - Assert.True(exists); - exists = await db.DoesForeignKeyConstraintExistOnColumnAsync( - schemaName, - tableName, - columnName - ); - Assert.True(exists); - - Output.WriteLine("Get Foreign Key Names: {0}", tableName); - var fkNames = await db.GetForeignKeyConstraintNamesAsync(schemaName, tableName); - Assert.Contains( - fkNames, - fk => fk.Equals(foreignKeyName, StringComparison.OrdinalIgnoreCase) - ); - - Output.WriteLine("Get Foreign Keys: {0}", tableName); - var fks = await db.GetForeignKeyConstraintsAsync(schemaName, tableName); - Assert.Contains( - fks, - fk => - fk.TableName.Equals(tableName, StringComparison.OrdinalIgnoreCase) - && fk.SourceColumns.Any(sc => - sc.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) - ) - && fk.ConstraintName.Equals(foreignKeyName, StringComparison.OrdinalIgnoreCase) - && fk.ReferencedTableName.Equals(refTableName, StringComparison.OrdinalIgnoreCase) - && fk.ReferencedColumns.Any(sc => - sc.ColumnName.Equals("id", StringComparison.OrdinalIgnoreCase) - ) - && fk.OnDelete.Equals(DxForeignKeyAction.Cascade) - ); - - Output.WriteLine("Dropping foreign key: {0}", foreignKeyName); - await db.DropForeignKeyConstraintIfExistsAsync(schemaName, tableName, foreignKeyName); - - Output.WriteLine("Foreign Key Exists: {0}", foreignKeyName); - exists = await db.DoesForeignKeyConstraintExistAsync(schemaName, tableName, foreignKeyName); - Assert.False(exists); - exists = await db.DoesForeignKeyConstraintExistOnColumnAsync( - schemaName, - tableName, - columnName - ); - Assert.False(exists); - - await db.DropTableIfExistsAsync(schemaName, tableName); - await db.DropTableIfExistsAsync(schemaName, refTableName); - } -} +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + [Theory] + [InlineData(null)] + [InlineData("my_app")] + protected virtual async Task Can_perform_simple_CRUD_on_ForeignKeyConstraints_Async( + string? schemaName + ) + { + using var db = await OpenConnectionAsync(); + await InitFreshSchemaAsync(db, schemaName); + + const string tableName = "testWithFk"; + const string columnName = "testFkColumn"; + const string foreignKeyName = "testFk"; + const string refTableName = "testRefPk"; + const string refTableColumn = "id"; + + await db.CreateTableIfNotExistsAsync( + schemaName, + tableName, + [ + new DmColumn( + schemaName, + tableName, + columnName, + typeof(int), + defaultExpression: "1", + isNullable: false + ) + ] + ); + await db.CreateTableIfNotExistsAsync( + schemaName, + refTableName, + [ + new DmColumn( + schemaName, + refTableName, + refTableColumn, + typeof(int), + defaultExpression: "1", + isPrimaryKey: true, + isNullable: false + ) + ] + ); + + Output.WriteLine("Foreign Key Exists: {0}.{1}", tableName, foreignKeyName); + var exists = await db.DoesForeignKeyConstraintExistAsync( + schemaName, + tableName, + foreignKeyName + ); + Assert.False(exists); + + Output.WriteLine("Creating foreign key: {0}.{1}", tableName, foreignKeyName); + var created = await db.CreateForeignKeyConstraintIfNotExistsAsync( + schemaName, + tableName, + foreignKeyName, + [new DmOrderedColumn(columnName)], + refTableName, + [new DmOrderedColumn("id")], + onDelete: DmForeignKeyAction.Cascade + ); + Assert.True(created); + + Output.WriteLine("Foreign Key Exists: {0}.{1}", tableName, foreignKeyName); + exists = await db.DoesForeignKeyConstraintExistAsync(schemaName, tableName, foreignKeyName); + Assert.True(exists); + exists = await db.DoesForeignKeyConstraintExistOnColumnAsync( + schemaName, + tableName, + columnName + ); + Assert.True(exists); + + Output.WriteLine("Get Foreign Key Names: {0}", tableName); + var fkNames = await db.GetForeignKeyConstraintNamesAsync(schemaName, tableName); + Assert.Contains( + fkNames, + fk => fk.Equals(foreignKeyName, StringComparison.OrdinalIgnoreCase) + ); + + Output.WriteLine("Get Foreign Keys: {0}", tableName); + var fks = await db.GetForeignKeyConstraintsAsync(schemaName, tableName); + Assert.Contains( + fks, + fk => + fk.TableName.Equals(tableName, StringComparison.OrdinalIgnoreCase) + && fk.SourceColumns.Any(sc => + sc.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase) + ) + && fk.ConstraintName.Equals(foreignKeyName, StringComparison.OrdinalIgnoreCase) + && fk.ReferencedTableName.Equals(refTableName, StringComparison.OrdinalIgnoreCase) + && fk.ReferencedColumns.Any(sc => + sc.ColumnName.Equals("id", StringComparison.OrdinalIgnoreCase) + ) + && fk.OnDelete.Equals(DmForeignKeyAction.Cascade) + ); + + Output.WriteLine("Dropping foreign key: {0}", foreignKeyName); + await db.DropForeignKeyConstraintIfExistsAsync(schemaName, tableName, foreignKeyName); + + Output.WriteLine("Foreign Key Exists: {0}", foreignKeyName); + exists = await db.DoesForeignKeyConstraintExistAsync(schemaName, tableName, foreignKeyName); + Assert.False(exists); + exists = await db.DoesForeignKeyConstraintExistOnColumnAsync( + schemaName, + tableName, + columnName + ); + Assert.False(exists); + + await db.DropTableIfExistsAsync(schemaName, tableName); + await db.DropTableIfExistsAsync(schemaName, refTableName); + } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.Indexes.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Indexes.cs similarity index 86% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.Indexes.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Indexes.cs index b75ce0a..4414992 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.Indexes.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Indexes.cs @@ -1,7 +1,7 @@ using System.Text.Json; -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Tests; +namespace MJCZone.DapperMatic.Tests; public abstract partial class DatabaseMethodsTests { @@ -30,7 +30,7 @@ protected virtual async Task Can_perform_simple_CRUD_on_Indexes_Async(string? sc const string columnName = "testColumn"; const string indexName = "testIndex"; - var columns = new List + var columns = new List { new( schemaName, @@ -44,7 +44,7 @@ protected virtual async Task Can_perform_simple_CRUD_on_Indexes_Async(string? sc for (var i = 0; i < 10; i++) { columns.Add( - new DxColumn( + new DmColumn( schemaName, tableName, columnName + "_" + i, @@ -67,7 +67,7 @@ await db.CreateIndexIfNotExistsAsync( schemaName, tableName, indexName, - [new DxOrderedColumn(columnName)], + [new DmOrderedColumn(columnName)], isUnique: true ); @@ -81,8 +81,8 @@ await db.CreateIndexIfNotExistsAsync( tableName, indexName + "_multi", [ - new DxOrderedColumn(columnName + "_1", DxColumnOrder.Descending), - new DxOrderedColumn(columnName + "_2") + new DmOrderedColumn(columnName + "_1", DmColumnOrder.Descending), + new DmOrderedColumn(columnName + "_2") ], isUnique: true ); @@ -97,8 +97,8 @@ await db.CreateIndexIfNotExistsAsync( tableName, indexName + "_multi2", [ - new DxOrderedColumn(columnName + "_3"), - new DxOrderedColumn(columnName + "_4", DxColumnOrder.Descending) + new DmOrderedColumn(columnName + "_3"), + new DmOrderedColumn(columnName + "_4", DmColumnOrder.Descending) ] ); @@ -139,15 +139,15 @@ await db.CreateIndexIfNotExistsAsync( Assert.Equal(2, idxMulti1.Columns.Count); if (supportsDescendingColumnSorts) { - Assert.Equal(DxColumnOrder.Descending, idxMulti1.Columns[0].Order); - Assert.Equal(DxColumnOrder.Ascending, idxMulti1.Columns[1].Order); + Assert.Equal(DmColumnOrder.Descending, idxMulti1.Columns[0].Order); + Assert.Equal(DmColumnOrder.Ascending, idxMulti1.Columns[1].Order); } Assert.False(idxMulti2.IsUnique); Assert.True(idxMulti2.Columns.Count == 2); - Assert.Equal(DxColumnOrder.Ascending, idxMulti2.Columns[0].Order); + Assert.Equal(DmColumnOrder.Ascending, idxMulti2.Columns[0].Order); if (supportsDescendingColumnSorts) { - Assert.Equal(DxColumnOrder.Descending, idxMulti2.Columns[1].Order); + Assert.Equal(DmColumnOrder.Descending, idxMulti2.Columns[1].Order); } var indexesOnColumn = await db.GetIndexesOnColumnAsync(schemaName, tableName, columnName); diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.PrimaryKeyConstraints.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.PrimaryKeyConstraints.cs similarity index 90% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.PrimaryKeyConstraints.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.PrimaryKeyConstraints.cs index 307023b..a5c2974 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.PrimaryKeyConstraints.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.PrimaryKeyConstraints.cs @@ -1,55 +1,55 @@ -using DapperMatic.Models; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - [Theory] - [InlineData(null)] - [InlineData("my_app")] - protected virtual async Task Can_perform_simple_CRUD_on_PrimaryKeyConstraints_Async( - string? schemaName - ) - { - using var db = await OpenConnectionAsync(); - await InitFreshSchemaAsync(db, schemaName); - - const string tableName = "testWithPk"; - const string columnName = "testColumn"; - const string primaryKeyName = "testPk"; - - await db.CreateTableIfNotExistsAsync( - schemaName, - tableName, - [ - new DxColumn( - schemaName, - tableName, - columnName, - typeof(int), - defaultExpression: "1", - isNullable: false - ) - ] - ); - Output.WriteLine("Primary Key Exists: {0}.{1}", tableName, primaryKeyName); - var exists = await db.DoesPrimaryKeyConstraintExistAsync(schemaName, tableName); - Assert.False(exists); - Output.WriteLine("Creating primary key: {0}.{1}", tableName, primaryKeyName); - await db.CreatePrimaryKeyConstraintIfNotExistsAsync( - schemaName, - tableName, - primaryKeyName, - [new DxOrderedColumn(columnName)] - ); - Output.WriteLine("Primary Key Exists: {0}.{1}", tableName, primaryKeyName); - exists = await db.DoesPrimaryKeyConstraintExistAsync(schemaName, tableName); - Assert.True(exists); - Output.WriteLine("Dropping primary key: {0}.{1}", tableName, primaryKeyName); - await db.DropPrimaryKeyConstraintIfExistsAsync(schemaName, tableName); - Output.WriteLine("Primary Key Exists: {0}.{1}", tableName, primaryKeyName); - exists = await db.DoesPrimaryKeyConstraintExistAsync(schemaName, tableName); - Assert.False(exists); - await db.DropTableIfExistsAsync(schemaName, tableName); - } -} +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + [Theory] + [InlineData(null)] + [InlineData("my_app")] + protected virtual async Task Can_perform_simple_CRUD_on_PrimaryKeyConstraints_Async( + string? schemaName + ) + { + using var db = await OpenConnectionAsync(); + await InitFreshSchemaAsync(db, schemaName); + + const string tableName = "testWithPk"; + const string columnName = "testColumn"; + const string primaryKeyName = "testPk"; + + await db.CreateTableIfNotExistsAsync( + schemaName, + tableName, + [ + new DmColumn( + schemaName, + tableName, + columnName, + typeof(int), + defaultExpression: "1", + isNullable: false + ) + ] + ); + Output.WriteLine("Primary Key Exists: {0}.{1}", tableName, primaryKeyName); + var exists = await db.DoesPrimaryKeyConstraintExistAsync(schemaName, tableName); + Assert.False(exists); + Output.WriteLine("Creating primary key: {0}.{1}", tableName, primaryKeyName); + await db.CreatePrimaryKeyConstraintIfNotExistsAsync( + schemaName, + tableName, + primaryKeyName, + [new DmOrderedColumn(columnName)] + ); + Output.WriteLine("Primary Key Exists: {0}.{1}", tableName, primaryKeyName); + exists = await db.DoesPrimaryKeyConstraintExistAsync(schemaName, tableName); + Assert.True(exists); + Output.WriteLine("Dropping primary key: {0}.{1}", tableName, primaryKeyName); + await db.DropPrimaryKeyConstraintIfExistsAsync(schemaName, tableName); + Output.WriteLine("Primary Key Exists: {0}.{1}", tableName, primaryKeyName); + exists = await db.DoesPrimaryKeyConstraintExistAsync(schemaName, tableName); + Assert.False(exists); + await db.DropTableIfExistsAsync(schemaName, tableName); + } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.Schemas.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Schemas.cs similarity index 94% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.Schemas.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Schemas.cs index fd2c4a8..df3cbf5 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.Schemas.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Schemas.cs @@ -1,43 +1,43 @@ -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - [Theory] - [InlineData("my_app")] - protected virtual async Task Can_perform_simple_CRUD_on_Schemas_Async(string schemaName) - { - using var db = await OpenConnectionAsync(); - - var supportsSchemas = db.SupportsSchemas(); - if (!supportsSchemas) - { - Output.WriteLine("This test requires a database that supports schemas."); - return; - } - - var exists = await db.DoesSchemaExistAsync(schemaName); - if (exists) - { - await db.DropSchemaIfExistsAsync(schemaName); - } - - exists = await db.DoesSchemaExistAsync(schemaName); - Assert.False(exists); - - Output.WriteLine("Creating schemaName: {0}", schemaName); - var created = await db.CreateSchemaIfNotExistsAsync(schemaName); - Assert.True(created); - exists = await db.DoesSchemaExistAsync(schemaName); - Assert.True(exists); - - var schemas = await db.GetSchemaNamesAsync(); - Assert.Contains(schemaName, schemas, StringComparer.OrdinalIgnoreCase); - - Output.WriteLine("Dropping schemaName: {0}", schemaName); - var dropped = await db.DropSchemaIfExistsAsync(schemaName); - Assert.True(dropped); - - exists = await db.DoesSchemaExistAsync(schemaName); - Assert.False(exists); - } -} +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + [Theory] + [InlineData("my_app")] + protected virtual async Task Can_perform_simple_CRUD_on_Schemas_Async(string schemaName) + { + using var db = await OpenConnectionAsync(); + + var supportsSchemas = db.SupportsSchemas(); + if (!supportsSchemas) + { + Output.WriteLine("This test requires a database that supports schemas."); + return; + } + + var exists = await db.DoesSchemaExistAsync(schemaName); + if (exists) + { + await db.DropSchemaIfExistsAsync(schemaName); + } + + exists = await db.DoesSchemaExistAsync(schemaName); + Assert.False(exists); + + Output.WriteLine("Creating schemaName: {0}", schemaName); + var created = await db.CreateSchemaIfNotExistsAsync(schemaName); + Assert.True(created); + exists = await db.DoesSchemaExistAsync(schemaName); + Assert.True(exists); + + var schemas = await db.GetSchemaNamesAsync(); + Assert.Contains(schemaName, schemas, StringComparer.OrdinalIgnoreCase); + + Output.WriteLine("Dropping schemaName: {0}", schemaName); + var dropped = await db.DropSchemaIfExistsAsync(schemaName); + Assert.True(dropped); + + exists = await db.DoesSchemaExistAsync(schemaName); + Assert.False(exists); + } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.TableFactory.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.TableFactory.cs similarity index 92% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.TableFactory.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.TableFactory.cs index 97afec5..eb9e4c8 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.TableFactory.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.TableFactory.cs @@ -1,179 +1,179 @@ -using System.Collections.ObjectModel; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using Dapper; -using DapperMatic.DataAnnotations; -using DapperMatic.Models; -using DapperMatic.Providers; -using Microsoft.Data.SqlClient.DataClassification; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - [Theory] - [InlineData(typeof(TestDao1))] - [InlineData(typeof(TestDao2))] - [InlineData(typeof(TestDao3))] - [InlineData(typeof(TestTable4))] - protected virtual async Task Can_create_tables_from_model_classes_async(Type type) - { - var tableDef = DxTableFactory.GetTable(type); - - using var db = await OpenConnectionAsync(); - - if (!string.IsNullOrWhiteSpace(tableDef.SchemaName)) - { - await db.CreateSchemaIfNotExistsAsync(tableDef.SchemaName); - } - - await db.CreateTableIfNotExistsAsync(tableDef); - - var tableExists = await db.DoesTableExistAsync(tableDef.SchemaName, tableDef.TableName); - Assert.True(tableExists); - - var dropped = await db.DropTableIfExistsAsync(tableDef.SchemaName, tableDef.TableName); - Assert.True(dropped); - } -} - -[Table("TestTable1")] -public class TestDao1 -{ - [Key] - public Guid Id { get; set; } -} - -[Table("TestTable2", Schema = "my_app")] -public class TestDao2 -{ - [Key] - public Guid Id { get; set; } -} - -[DxTable("TestTable3")] -public class TestDao3 -{ - [DxPrimaryKeyConstraint] - public Guid Id { get; set; } -} - -[DxPrimaryKeyConstraint([nameof(TestTable4.Id)])] -public class TestTable4 -{ - public Guid Id { get; set; } - - // create column of all supported types - public string StringColumn { get; set; } = null!; - public int IntColumn { get; set; } - public long LongColumn { get; set; } - public short ShortColumn { get; set; } - public byte ByteColumn { get; set; } - public decimal DecimalColumn { get; set; } - public double DoubleColumn { get; set; } - public float FloatColumn { get; set; } - public bool BoolColumn { get; set; } - public DateTime DateTimeColumn { get; set; } - public DateTimeOffset DateTimeOffsetColumn { get; set; } - public TimeSpan TimeSpanColumn { get; set; } - public byte[] ByteArrayColumn { get; set; } = null!; - public Guid GuidColumn { get; set; } - public char CharColumn { get; set; } - public char[] CharArrayColumn { get; set; } = null!; - public object ObjectColumn { get; set; } = null!; - - // create column of all supported nullable types - public string? NullableStringColumn { get; set; } - public int? NullableIntColumn { get; set; } - public long? NullableLongColumn { get; set; } - public short? NullableShortColumn { get; set; } - public byte? NullableByteColumn { get; set; } - public decimal? NullableDecimalColumn { get; set; } - public double? NullableDoubleColumn { get; set; } - public float? NullableFloatColumn { get; set; } - public bool? NullableBoolColumn { get; set; } - public DateTime? NullableDateTimeColumn { get; set; } - public DateTimeOffset? NullableDateTimeOffsetColumn { get; set; } - public TimeSpan? NullableTimeSpanColumn { get; set; } - public byte[]? NullableByteArrayColumn { get; set; } - public Guid? NullableGuidColumn { get; set; } - public char? NullableCharColumn { get; set; } - public char[]? NullableCharArrayColumn { get; set; } - public object? NullableObjectColumn { get; set; } - - // create columns of all enumerable types - public IDictionary IDictionaryColumn { get; set; } = null!; - public IDictionary? NullableIDictionaryColumn { get; set; } - public Dictionary DictionaryColumn { get; set; } = null!; - public Dictionary? NullableDictionaryColumn { get; set; } - public IDictionary IObjectDictionaryColumn { get; set; } = null!; - public IDictionary? NullableIObjectDictionaryColumn { get; set; } - public Dictionary ObjectDictionaryColumn { get; set; } = null!; - public Dictionary? NullableObjectDictionaryColumn { get; set; } - public IList IListColumn { get; set; } = null!; - public IList? NullableIListColumn { get; set; } - public List ListColumn { get; set; } = null!; - public List? NullableListColumn { get; set; } - public ICollection ICollectionColumn { get; set; } = null!; - public ICollection? NullableICollectionColumn { get; set; } - public Collection CollectionColumn { get; set; } = null!; - public Collection? NullableCollectionColumn { get; set; } - public IEnumerable IEnumerableColumn { get; set; } = null!; - public IEnumerable? NullableIEnumerableColumn { get; set; } - - // create columns of arrays - public string[] StringArrayColumn { get; set; } = null!; - public string[]? NullableStringArrayColumn { get; set; } - public int[] IntArrayColumn { get; set; } = null!; - public int[]? NullableIntArrayColumn { get; set; } - public long[] LongArrayColumn { get; set; } = null!; - public long[]? NullableLongArrayColumn { get; set; } - public Guid[] GuidArrayColumn { get; set; } = null!; - public Guid[]? NullableGuidArrayColumn { get; set; } - - // create columns of enums, structs and classes - public TestEnum EnumColumn { get; set; } - public TestEnum? NullableEnumColumn { get; set; } - public TestStruct StructColumn { get; set; } - public TestStruct? NullableStructColumn { get; set; } - public TestClass ClassColumn { get; set; } = null!; - public TestClass? NullableClassColumn { get; set; } - public TestInterface InterfaceColumn { get; set; } = null!; - public TestInterface? NullableInterfaceColumn { get; set; } - public TestAbstractClass AbstractClassColumn { get; set; } = null!; - public TestAbstractClass? NullableAbstractClassColumn { get; set; } - public TestConcreteClass ConcreteClass { get; set; } = null!; - public TestConcreteClass? NullableConcreteClass { get; set; } -} - -public enum TestEnum -{ - Value1, - Value2, - Value3 -} - -public struct TestStruct -{ - public int Value { get; set; } -} - -public class TestClass -{ - public int Value { get; set; } -} - -public interface TestInterface -{ - int Value { get; set; } -} - -public abstract class TestAbstractClass -{ - public int Value { get; set; } -} - -public class TestConcreteClass : TestAbstractClass -{ - public int Value2 { get; set; } -} +using System.Collections.ObjectModel; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Dapper; +using Microsoft.Data.SqlClient.DataClassification; +using MJCZone.DapperMatic.DataAnnotations; +using MJCZone.DapperMatic.Models; +using MJCZone.DapperMatic.Providers; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + [Theory] + [InlineData(typeof(TestDao1))] + [InlineData(typeof(TestDao2))] + [InlineData(typeof(TestDao3))] + [InlineData(typeof(TestTable4))] + protected virtual async Task Can_create_tables_from_model_classes_async(Type type) + { + var tableDef = DmTableFactory.GetTable(type); + + using var db = await OpenConnectionAsync(); + + if (!string.IsNullOrWhiteSpace(tableDef.SchemaName)) + { + await db.CreateSchemaIfNotExistsAsync(tableDef.SchemaName); + } + + await db.CreateTableIfNotExistsAsync(tableDef); + + var tableExists = await db.DoesTableExistAsync(tableDef.SchemaName, tableDef.TableName); + Assert.True(tableExists); + + var dropped = await db.DropTableIfExistsAsync(tableDef.SchemaName, tableDef.TableName); + Assert.True(dropped); + } +} + +[Table("TestTable1")] +public class TestDao1 +{ + [Key] + public Guid Id { get; set; } +} + +[Table("TestTable2", Schema = "my_app")] +public class TestDao2 +{ + [Key] + public Guid Id { get; set; } +} + +[DmTable("TestTable3")] +public class TestDao3 +{ + [DmPrimaryKeyConstraint] + public Guid Id { get; set; } +} + +[DmPrimaryKeyConstraint([nameof(TestTable4.Id)])] +public class TestTable4 +{ + public Guid Id { get; set; } + + // create column of all supported types + public string StringColumn { get; set; } = null!; + public int IntColumn { get; set; } + public long LongColumn { get; set; } + public short ShortColumn { get; set; } + public byte ByteColumn { get; set; } + public decimal DecimalColumn { get; set; } + public double DoubleColumn { get; set; } + public float FloatColumn { get; set; } + public bool BoolColumn { get; set; } + public DateTime DateTimeColumn { get; set; } + public DateTimeOffset DateTimeOffsetColumn { get; set; } + public TimeSpan TimeSpanColumn { get; set; } + public byte[] ByteArrayColumn { get; set; } = null!; + public Guid GuidColumn { get; set; } + public char CharColumn { get; set; } + public char[] CharArrayColumn { get; set; } = null!; + public object ObjectColumn { get; set; } = null!; + + // create column of all supported nullable types + public string? NullableStringColumn { get; set; } + public int? NullableIntColumn { get; set; } + public long? NullableLongColumn { get; set; } + public short? NullableShortColumn { get; set; } + public byte? NullableByteColumn { get; set; } + public decimal? NullableDecimalColumn { get; set; } + public double? NullableDoubleColumn { get; set; } + public float? NullableFloatColumn { get; set; } + public bool? NullableBoolColumn { get; set; } + public DateTime? NullableDateTimeColumn { get; set; } + public DateTimeOffset? NullableDateTimeOffsetColumn { get; set; } + public TimeSpan? NullableTimeSpanColumn { get; set; } + public byte[]? NullableByteArrayColumn { get; set; } + public Guid? NullableGuidColumn { get; set; } + public char? NullableCharColumn { get; set; } + public char[]? NullableCharArrayColumn { get; set; } + public object? NullableObjectColumn { get; set; } + + // create columns of all enumerable types + public IDictionary IDictionaryColumn { get; set; } = null!; + public IDictionary? NullableIDictionaryColumn { get; set; } + public Dictionary DictionaryColumn { get; set; } = null!; + public Dictionary? NullableDictionaryColumn { get; set; } + public IDictionary IObjectDictionaryColumn { get; set; } = null!; + public IDictionary? NullableIObjectDictionaryColumn { get; set; } + public Dictionary ObjectDictionaryColumn { get; set; } = null!; + public Dictionary? NullableObjectDictionaryColumn { get; set; } + public IList IListColumn { get; set; } = null!; + public IList? NullableIListColumn { get; set; } + public List ListColumn { get; set; } = null!; + public List? NullableListColumn { get; set; } + public ICollection ICollectionColumn { get; set; } = null!; + public ICollection? NullableICollectionColumn { get; set; } + public Collection CollectionColumn { get; set; } = null!; + public Collection? NullableCollectionColumn { get; set; } + public IEnumerable IEnumerableColumn { get; set; } = null!; + public IEnumerable? NullableIEnumerableColumn { get; set; } + + // create columns of arrays + public string[] StringArrayColumn { get; set; } = null!; + public string[]? NullableStringArrayColumn { get; set; } + public int[] IntArrayColumn { get; set; } = null!; + public int[]? NullableIntArrayColumn { get; set; } + public long[] LongArrayColumn { get; set; } = null!; + public long[]? NullableLongArrayColumn { get; set; } + public Guid[] GuidArrayColumn { get; set; } = null!; + public Guid[]? NullableGuidArrayColumn { get; set; } + + // create columns of enums, structs and classes + public TestEnum EnumColumn { get; set; } + public TestEnum? NullableEnumColumn { get; set; } + public TestStruct StructColumn { get; set; } + public TestStruct? NullableStructColumn { get; set; } + public TestClass ClassColumn { get; set; } = null!; + public TestClass? NullableClassColumn { get; set; } + public TestInterface InterfaceColumn { get; set; } = null!; + public TestInterface? NullableInterfaceColumn { get; set; } + public TestAbstractClass AbstractClassColumn { get; set; } = null!; + public TestAbstractClass? NullableAbstractClassColumn { get; set; } + public TestConcreteClass ConcreteClass { get; set; } = null!; + public TestConcreteClass? NullableConcreteClass { get; set; } +} + +public enum TestEnum +{ + Value1, + Value2, + Value3 +} + +public struct TestStruct +{ + public int Value { get; set; } +} + +public class TestClass +{ + public int Value { get; set; } +} + +public interface TestInterface +{ + int Value { get; set; } +} + +public abstract class TestAbstractClass +{ + public int Value { get; set; } +} + +public class TestConcreteClass : TestAbstractClass +{ + public int Value2 { get; set; } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.Tables.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Tables.cs similarity index 92% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.Tables.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Tables.cs index 5ace7ff..39ed64d 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.Tables.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Tables.cs @@ -1,118 +1,118 @@ -using Dapper; -using DapperMatic.Models; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - [Theory] - [InlineData(null)] - [InlineData("my_app")] - protected virtual async Task Can_perform_simple_CRUD_on_Tables_Async(string? schemaName) - { - using var db = await OpenConnectionAsync(); - await InitFreshSchemaAsync(db, schemaName); - - var supportsSchemas = db.SupportsSchemas(); - - var tableName = "testTable"; - - var exists = await db.DoesTableExistAsync(schemaName, tableName); - if (exists) - { - await db.DropTableIfExistsAsync(schemaName, tableName); - } - - exists = await db.DoesTableExistAsync(schemaName, tableName); - Assert.False(exists); - - var nonExistentTable = await db.GetTableAsync(schemaName, tableName); - Assert.Null(nonExistentTable); - - var table = new DxTable( - schemaName, - tableName, - [ - new DxColumn( - schemaName, - tableName, - "id", - typeof(int), - isPrimaryKey: true, - isAutoIncrement: true - ), - new DxColumn(schemaName, tableName, "name", typeof(string), isUnique: true) - ] - ); - var created = await db.CreateTableIfNotExistsAsync(table); - Assert.True(created); - - var createdAgain = await db.CreateTableIfNotExistsAsync(table); - Assert.False(createdAgain); - - exists = await db.DoesTableExistAsync(schemaName, tableName); - Assert.True(exists); - - var tableNames = await db.GetTableNamesAsync(schemaName); - Assert.NotEmpty(tableNames); - Assert.Contains(tableName, tableNames, StringComparer.OrdinalIgnoreCase); - - var existingTable = await db.GetTableAsync(schemaName, tableName); - Assert.NotNull(existingTable); - - if (supportsSchemas) - { - Assert.NotNull(existingTable.SchemaName); - Assert.NotEmpty(existingTable.SchemaName); - } - Assert.Equal(tableName, existingTable.TableName, true); - Assert.Equal(2, existingTable.Columns.Count); - - // rename the table - var newName = "newTestTable"; - var renamed = await db.RenameTableIfExistsAsync(schemaName, tableName, newName); - Assert.True(renamed); - - exists = await db.DoesTableExistAsync(schemaName, tableName); - Assert.False(exists); - - exists = await db.DoesTableExistAsync(schemaName, newName); - Assert.True(exists); - - existingTable = await db.GetTableAsync(schemaName, newName); - Assert.NotNull(existingTable); - Assert.Equal(newName, existingTable.TableName, true); - - tableNames = await db.GetTableNamesAsync(schemaName); - Assert.Contains(newName, tableNames, StringComparer.OrdinalIgnoreCase); - - var schemaQualifiedTableName = db.GetSchemaQualifiedTableName(schemaName, newName); - - // add a new row - var newRow = new { id = 0, name = "Test" }; - await db.ExecuteAsync( - @$"INSERT INTO {schemaQualifiedTableName} (name) VALUES (@name)", - newRow - ); - - // get all rows - var rows = await db.QueryAsync( - @$"SELECT * FROM {schemaQualifiedTableName}", - new { } - ); - Assert.Single(rows); - - // truncate the table - await db.TruncateTableIfExistsAsync(schemaName, newName); - rows = await db.QueryAsync(@$"SELECT * FROM {schemaQualifiedTableName}", new { }); - Assert.Empty(rows); - - // drop the table - await db.DropTableIfExistsAsync(schemaName, newName); - - exists = await db.DoesTableExistAsync(schemaName, newName); - Assert.False(exists); - - Output.WriteLine($"Table names: {0}", string.Join(", ", tableNames)); - } -} +using Dapper; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + [Theory] + [InlineData(null)] + [InlineData("my_app")] + protected virtual async Task Can_perform_simple_CRUD_on_Tables_Async(string? schemaName) + { + using var db = await OpenConnectionAsync(); + await InitFreshSchemaAsync(db, schemaName); + + var supportsSchemas = db.SupportsSchemas(); + + var tableName = "testTable"; + + var exists = await db.DoesTableExistAsync(schemaName, tableName); + if (exists) + { + await db.DropTableIfExistsAsync(schemaName, tableName); + } + + exists = await db.DoesTableExistAsync(schemaName, tableName); + Assert.False(exists); + + var nonExistentTable = await db.GetTableAsync(schemaName, tableName); + Assert.Null(nonExistentTable); + + var table = new DmTable( + schemaName, + tableName, + [ + new DmColumn( + schemaName, + tableName, + "id", + typeof(int), + isPrimaryKey: true, + isAutoIncrement: true + ), + new DmColumn(schemaName, tableName, "name", typeof(string), isUnique: true) + ] + ); + var created = await db.CreateTableIfNotExistsAsync(table); + Assert.True(created); + + var createdAgain = await db.CreateTableIfNotExistsAsync(table); + Assert.False(createdAgain); + + exists = await db.DoesTableExistAsync(schemaName, tableName); + Assert.True(exists); + + var tableNames = await db.GetTableNamesAsync(schemaName); + Assert.NotEmpty(tableNames); + Assert.Contains(tableName, tableNames, StringComparer.OrdinalIgnoreCase); + + var existingTable = await db.GetTableAsync(schemaName, tableName); + Assert.NotNull(existingTable); + + if (supportsSchemas) + { + Assert.NotNull(existingTable.SchemaName); + Assert.NotEmpty(existingTable.SchemaName); + } + Assert.Equal(tableName, existingTable.TableName, true); + Assert.Equal(2, existingTable.Columns.Count); + + // rename the table + var newName = "newTestTable"; + var renamed = await db.RenameTableIfExistsAsync(schemaName, tableName, newName); + Assert.True(renamed); + + exists = await db.DoesTableExistAsync(schemaName, tableName); + Assert.False(exists); + + exists = await db.DoesTableExistAsync(schemaName, newName); + Assert.True(exists); + + existingTable = await db.GetTableAsync(schemaName, newName); + Assert.NotNull(existingTable); + Assert.Equal(newName, existingTable.TableName, true); + + tableNames = await db.GetTableNamesAsync(schemaName); + Assert.Contains(newName, tableNames, StringComparer.OrdinalIgnoreCase); + + var schemaQualifiedTableName = db.GetSchemaQualifiedTableName(schemaName, newName); + + // add a new row + var newRow = new { id = 0, name = "Test" }; + await db.ExecuteAsync( + @$"INSERT INTO {schemaQualifiedTableName} (name) VALUES (@name)", + newRow + ); + + // get all rows + var rows = await db.QueryAsync( + @$"SELECT * FROM {schemaQualifiedTableName}", + new { } + ); + Assert.Single(rows); + + // truncate the table + await db.TruncateTableIfExistsAsync(schemaName, newName); + rows = await db.QueryAsync(@$"SELECT * FROM {schemaQualifiedTableName}", new { }); + Assert.Empty(rows); + + // drop the table + await db.DropTableIfExistsAsync(schemaName, newName); + + exists = await db.DoesTableExistAsync(schemaName, newName); + Assert.False(exists); + + Output.WriteLine($"Table names: {0}", string.Join(", ", tableNames)); + } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.Types.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Types.cs similarity index 94% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.Types.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Types.cs index cb3dd3b..4143aa1 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.Types.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Types.cs @@ -1,90 +1,90 @@ -using DapperMatic.Providers; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - private static Type[] GetSupportedTypes(IDbProviderTypeMap dbTypeMap) - { - Type[] typesToSupport = - [ - typeof(bool), - typeof(byte), - typeof(sbyte), - typeof(short), - typeof(int), - typeof(long), - typeof(float), - typeof(double), - typeof(decimal), - typeof(char), - typeof(string), - typeof(char[]), - typeof(ReadOnlyMemory[]), - typeof(Stream), - typeof(Guid), - typeof(DateTime), - typeof(DateTimeOffset), - typeof(TimeSpan), - typeof(DateOnly), - typeof(TimeOnly), - typeof(byte[]), - typeof(object), - // generic definitions - typeof(IDictionary<,>), - typeof(Dictionary<,>), - typeof(IEnumerable<>), - typeof(ICollection<>), - typeof(List<>), - typeof(object[]), - // generics - typeof(IDictionary), - typeof(Dictionary), - typeof(Dictionary), - typeof(Dictionary), - typeof(Dictionary), - typeof(Dictionary), - typeof(Dictionary), - typeof(IEnumerable), - typeof(IEnumerable), - typeof(ICollection), - typeof(ICollection), - typeof(List), - typeof(List), - typeof(List), - typeof(string[]), - typeof(Guid[]), - typeof(int[]), - typeof(long[]), - typeof(double[]), - typeof(decimal[]), - typeof(TimeSpan[]), - // custom classes - typeof(TestClassDao) - ]; - - return typesToSupport; - } - - public class TestClassDao - { - public Guid Id { get; set; } - } - - [Fact] - protected virtual async Task Provider_type_map_supports_all_desired_dotnet_types() - { - using var db = await OpenConnectionAsync(); - var dbTypeMap = db.GetProviderTypeMap(); - foreach (var desiredType in GetSupportedTypes(dbTypeMap)) - { - var exists = dbTypeMap.TryGetProviderSqlTypeMatchingDotnetType( - new DotnetTypeDescriptor(desiredType.OrUnderlyingTypeIfNullable()), - out var sqlType - ); - - Assert.True(exists, "Could not find a SQL type for " + desiredType.FullName); - Assert.NotNull(sqlType); - } - } -} +using MJCZone.DapperMatic.Providers; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + private static Type[] GetSupportedTypes(IDbProviderTypeMap dbTypeMap) + { + Type[] typesToSupport = + [ + typeof(bool), + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(int), + typeof(long), + typeof(float), + typeof(double), + typeof(decimal), + typeof(char), + typeof(string), + typeof(char[]), + typeof(ReadOnlyMemory[]), + typeof(Stream), + typeof(Guid), + typeof(DateTime), + typeof(DateTimeOffset), + typeof(TimeSpan), + typeof(DateOnly), + typeof(TimeOnly), + typeof(byte[]), + typeof(object), + // generic definitions + typeof(IDictionary<,>), + typeof(Dictionary<,>), + typeof(IEnumerable<>), + typeof(ICollection<>), + typeof(List<>), + typeof(object[]), + // generics + typeof(IDictionary), + typeof(Dictionary), + typeof(Dictionary), + typeof(Dictionary), + typeof(Dictionary), + typeof(Dictionary), + typeof(Dictionary), + typeof(IEnumerable), + typeof(IEnumerable), + typeof(ICollection), + typeof(ICollection), + typeof(List), + typeof(List), + typeof(List), + typeof(string[]), + typeof(Guid[]), + typeof(int[]), + typeof(long[]), + typeof(double[]), + typeof(decimal[]), + typeof(TimeSpan[]), + // custom classes + typeof(TestClassDao) + ]; + + return typesToSupport; + } + + public class TestClassDao + { + public Guid Id { get; set; } + } + + [Fact] + protected virtual async Task Provider_type_map_supports_all_desired_dotnet_types() + { + using var db = await OpenConnectionAsync(); + var dbTypeMap = db.GetProviderTypeMap(); + foreach (var desiredType in GetSupportedTypes(dbTypeMap)) + { + var exists = dbTypeMap.TryGetProviderSqlTypeMatchingDotnetType( + new DotnetTypeDescriptor(desiredType.OrUnderlyingTypeIfNullable()), + out var sqlType + ); + + Assert.True(exists, "Could not find a SQL type for " + desiredType.FullName); + Assert.NotNull(sqlType); + } + } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.UniqueConstraints.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.UniqueConstraints.cs similarity index 88% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.UniqueConstraints.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.UniqueConstraints.cs index 21ecc31..4785609 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.UniqueConstraints.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.UniqueConstraints.cs @@ -1,6 +1,6 @@ -using DapperMatic.Models; +using MJCZone.DapperMatic.Models; -namespace DapperMatic.Tests; +namespace MJCZone.DapperMatic.Tests; public abstract partial class DatabaseMethodsTests { @@ -24,7 +24,7 @@ await db.CreateTableIfNotExistsAsync( schemaName, tableName, [ - new DxColumn( + new DmColumn( schemaName, tableName, columnName, @@ -32,7 +32,7 @@ await db.CreateTableIfNotExistsAsync( defaultExpression: "1", isNullable: false ), - new DxColumn( + new DmColumn( schemaName, tableName, columnName2, @@ -43,11 +43,11 @@ await db.CreateTableIfNotExistsAsync( ], uniqueConstraints: [ - new DxUniqueConstraint( + new DmUniqueConstraint( schemaName, tableName, uniqueConstraintName2, - [new DxOrderedColumn(columnName2)] + [new DmOrderedColumn(columnName2)] ) ] ); @@ -79,7 +79,7 @@ await db.CreateUniqueConstraintIfNotExistsAsync( schemaName, tableName, uniqueConstraintName, - [new DxOrderedColumn(columnName)] + [new DmOrderedColumn(columnName)] ); // make sure the new constraint is there @@ -150,7 +150,7 @@ await db.CreateTableIfNotExistsAsync( schemaName, tableName, [ - new DxColumn( + new DmColumn( schemaName, tableName, columnName, @@ -158,7 +158,7 @@ await db.CreateTableIfNotExistsAsync( defaultExpression: "1", isNullable: false ), - new DxColumn( + new DmColumn( schemaName, tableName, columnName2, @@ -169,13 +169,13 @@ await db.CreateTableIfNotExistsAsync( ], uniqueConstraints: [ - new DxUniqueConstraint( + new DmUniqueConstraint( schemaName, tableName, uniqueConstraintName, [ - new DxOrderedColumn(columnName2), - new DxOrderedColumn(columnName, DxColumnOrder.Descending) + new DmOrderedColumn(columnName2), + new DmOrderedColumn(columnName, DmColumnOrder.Descending) ] ) ] @@ -194,7 +194,7 @@ await db.CreateTableIfNotExistsAsync( uniqueConstraint.Columns[0].ColumnName, StringComparer.OrdinalIgnoreCase ); - Assert.Equal(DxColumnOrder.Ascending, uniqueConstraint.Columns[0].Order); + Assert.Equal(DmColumnOrder.Ascending, uniqueConstraint.Columns[0].Order); Assert.Equal( columnName, uniqueConstraint.Columns[1].ColumnName, @@ -202,7 +202,7 @@ await db.CreateTableIfNotExistsAsync( ); if (await db.SupportsOrderedKeysInConstraintsAsync()) { - Assert.Equal(DxColumnOrder.Descending, uniqueConstraint.Columns[1].Order); + Assert.Equal(DmColumnOrder.Descending, uniqueConstraint.Columns[1].Order); } await db.DropTableIfExistsAsync(schemaName, tableName); } diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.Views.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Views.cs similarity index 93% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.Views.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Views.cs index 6bba80c..e3723b7 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.Views.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.Views.cs @@ -1,105 +1,105 @@ -using Dapper; -using DapperMatic.Models; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests -{ - [Theory] - [InlineData(null)] - [InlineData("my_app")] - protected virtual async Task Can_perform_simple_CRUD_on_Views_Async(string? schemaName) - { - using var db = await OpenConnectionAsync(); - await InitFreshSchemaAsync(db, schemaName); - - var supportsSchemas = db.SupportsSchemas(); - - var tableForView = "testTableForView"; - - var schemaQualifiedTableName = db.GetSchemaQualifiedTableName(schemaName, tableForView); - - await db.CreateTableIfNotExistsAsync( - schemaName, - tableForView, - [ - new DxColumn( - schemaName, - tableForView, - "id", - typeof(int), - isPrimaryKey: true, - isAutoIncrement: true - ), - new DxColumn(schemaName, tableForView, "name", typeof(string)) - ] - ); - - var viewName = "testView"; - var definition = $"SELECT * FROM {schemaQualifiedTableName}"; - var created = await db.CreateViewIfNotExistsAsync(schemaName, viewName, definition); - Assert.True(created); - - var createdAgain = await db.CreateViewIfNotExistsAsync(schemaName, viewName, definition); - Assert.False(createdAgain); - - var exists = await db.DoesViewExistAsync(schemaName, viewName); - Assert.True(exists); - - var view = await db.GetViewAsync(schemaName, viewName); - Assert.NotNull(view); - - var viewNames = await db.GetViewNamesAsync(schemaName); - Assert.Contains(viewName, viewNames, StringComparer.OrdinalIgnoreCase); - - await db.ExecuteAsync($"INSERT INTO {schemaQualifiedTableName} (name) VALUES ('test123')"); - await db.ExecuteAsync($"INSERT INTO {schemaQualifiedTableName} (name) VALUES ('test456')"); - var tableRowCount = await db.ExecuteScalarAsync( - $"SELECT COUNT(*) FROM {schemaQualifiedTableName}" - ); - var viewRowCount = await db.ExecuteScalarAsync( - $"SELECT COUNT(*) FROM {schemaQualifiedTableName}" - ); - - Assert.Equal(2, tableRowCount); - Assert.Equal(2, viewRowCount); - - var updatedName = viewName + "blahblahblah"; - var updatedDefinition = $"SELECT * FROM {schemaQualifiedTableName} WHERE id = 1"; - var updated = await db.UpdateViewIfExistsAsync(schemaName, updatedName, updatedDefinition); - Assert.False(updated); // view doesn't exist - - var renamed = await db.RenameViewIfExistsAsync(schemaName, viewName, updatedName); - Assert.True(renamed); - - var renamedView = await db.GetViewAsync(schemaName, updatedName); - Assert.NotNull(renamedView); - Assert.Equal(view.Definition, renamedView.Definition); - - updated = await db.UpdateViewIfExistsAsync(schemaName, updatedName, updatedDefinition); - Assert.True(updated); - - var updatedView = await db.GetViewAsync(schemaName, updatedName); - Assert.NotNull(updatedView); - Assert.Contains("= 1", updatedView.Definition, StringComparison.OrdinalIgnoreCase); - - // databases often rewrite the definition, so we just check that it contains the updated definition - Assert.StartsWith( - "select ", - updatedView.Definition.Trim(), - StringComparison.OrdinalIgnoreCase - ); - - var dropped = await db.DropViewIfExistsAsync(schemaName, viewName); - Assert.False(dropped); - dropped = await db.DropViewIfExistsAsync(schemaName, updatedName); - Assert.True(dropped); - - exists = await db.DoesViewExistAsync(schemaName, viewName); - Assert.False(exists); - exists = await db.DoesViewExistAsync(schemaName, updatedName); - Assert.False(exists); - - await db.DropTableIfExistsAsync(schemaName, tableForView); - } -} +using Dapper; +using MJCZone.DapperMatic.Models; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests +{ + [Theory] + [InlineData(null)] + [InlineData("my_app")] + protected virtual async Task Can_perform_simple_CRUD_on_Views_Async(string? schemaName) + { + using var db = await OpenConnectionAsync(); + await InitFreshSchemaAsync(db, schemaName); + + var supportsSchemas = db.SupportsSchemas(); + + var tableForView = "testTableForView"; + + var schemaQualifiedTableName = db.GetSchemaQualifiedTableName(schemaName, tableForView); + + await db.CreateTableIfNotExistsAsync( + schemaName, + tableForView, + [ + new DmColumn( + schemaName, + tableForView, + "id", + typeof(int), + isPrimaryKey: true, + isAutoIncrement: true + ), + new DmColumn(schemaName, tableForView, "name", typeof(string)) + ] + ); + + var viewName = "testView"; + var definition = $"SELECT * FROM {schemaQualifiedTableName}"; + var created = await db.CreateViewIfNotExistsAsync(schemaName, viewName, definition); + Assert.True(created); + + var createdAgain = await db.CreateViewIfNotExistsAsync(schemaName, viewName, definition); + Assert.False(createdAgain); + + var exists = await db.DoesViewExistAsync(schemaName, viewName); + Assert.True(exists); + + var view = await db.GetViewAsync(schemaName, viewName); + Assert.NotNull(view); + + var viewNames = await db.GetViewNamesAsync(schemaName); + Assert.Contains(viewName, viewNames, StringComparer.OrdinalIgnoreCase); + + await db.ExecuteAsync($"INSERT INTO {schemaQualifiedTableName} (name) VALUES ('test123')"); + await db.ExecuteAsync($"INSERT INTO {schemaQualifiedTableName} (name) VALUES ('test456')"); + var tableRowCount = await db.ExecuteScalarAsync( + $"SELECT COUNT(*) FROM {schemaQualifiedTableName}" + ); + var viewRowCount = await db.ExecuteScalarAsync( + $"SELECT COUNT(*) FROM {schemaQualifiedTableName}" + ); + + Assert.Equal(2, tableRowCount); + Assert.Equal(2, viewRowCount); + + var updatedName = viewName + "blahblahblah"; + var updatedDefinition = $"SELECT * FROM {schemaQualifiedTableName} WHERE id = 1"; + var updated = await db.UpdateViewIfExistsAsync(schemaName, updatedName, updatedDefinition); + Assert.False(updated); // view doesn't exist + + var renamed = await db.RenameViewIfExistsAsync(schemaName, viewName, updatedName); + Assert.True(renamed); + + var renamedView = await db.GetViewAsync(schemaName, updatedName); + Assert.NotNull(renamedView); + Assert.Equal(view.Definition, renamedView.Definition); + + updated = await db.UpdateViewIfExistsAsync(schemaName, updatedName, updatedDefinition); + Assert.True(updated); + + var updatedView = await db.GetViewAsync(schemaName, updatedName); + Assert.NotNull(updatedView); + Assert.Contains("= 1", updatedView.Definition, StringComparison.OrdinalIgnoreCase); + + // databases often rewrite the definition, so we just check that it contains the updated definition + Assert.StartsWith( + "select ", + updatedView.Definition.Trim(), + StringComparison.OrdinalIgnoreCase + ); + + var dropped = await db.DropViewIfExistsAsync(schemaName, viewName); + Assert.False(dropped); + dropped = await db.DropViewIfExistsAsync(schemaName, updatedName); + Assert.True(dropped); + + exists = await db.DoesViewExistAsync(schemaName, viewName); + Assert.False(exists); + exists = await db.DoesViewExistAsync(schemaName, updatedName); + Assert.False(exists); + + await db.DropTableIfExistsAsync(schemaName, tableForView); + } +} diff --git a/tests/DapperMatic.Tests/DatabaseMethodsTests.cs b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.cs similarity index 95% rename from tests/DapperMatic.Tests/DatabaseMethodsTests.cs rename to tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.cs index e027200..bdd3daa 100644 --- a/tests/DapperMatic.Tests/DatabaseMethodsTests.cs +++ b/tests/MJCZone.DapperMatic.Tests/DatabaseMethodsTests.cs @@ -1,71 +1,71 @@ -using System.Data; -using Dapper; -using Newtonsoft.Json; -using Xunit.Abstractions; - -namespace DapperMatic.Tests; - -public abstract partial class DatabaseMethodsTests : TestBase -{ - protected DatabaseMethodsTests(ITestOutputHelper output) - : base(output) { } - - public abstract Task OpenConnectionAsync(); - - [Fact] - protected virtual async Task Database_Can_RunArbitraryQueriesAsync() - { - using var db = await OpenConnectionAsync(); - const int expected = 1; - var actual = await db.QueryFirstAsync("SELECT 1"); - Assert.Equal(expected, actual); - - // run a statement with many sql statements at the same time - await db.ExecuteAsync( - """ - - CREATE TABLE test (id INT PRIMARY KEY); - INSERT INTO test VALUES (1); - INSERT INTO test VALUES (2); - INSERT INTO test VALUES (3); - - """ - ); - var values = await db.QueryAsync("SELECT id FROM test"); - Assert.Equal(3, values.Count()); - - // run multiple select statements and read multiple result sets - var result = await db.QueryMultipleAsync( - """ - - SELECT id FROM test WHERE id = 1; - SELECT id FROM test WHERE id = 2; - SELECT id FROM test; - -- this statement is ignored by the grid reader - -- because it doesn't return any results - INSERT INTO test VALUES (4); - SELECT id FROM test WHERE id = 4; - - """ - ); - var id1 = result.Read().Single(); - var id2 = result.Read().Single(); - var allIds = result.Read().ToArray(); - var id4 = result.Read().Single(); - Assert.Equal(1, id1); - Assert.Equal(2, id2); - Assert.Equal(3, allIds.Length); - Assert.Equal(4, id4); - } - - [Fact] - protected virtual async Task GetDatabaseVersionAsync_ReturnsVersion() - { - using var db = await OpenConnectionAsync(); - - var version = await db.GetDatabaseVersionAsync(); - Assert.True(version.Major > 0); - - Output.WriteLine("Database version: {0}", version); - } -} +using System.Data; +using Dapper; +using Newtonsoft.Json; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests; + +public abstract partial class DatabaseMethodsTests : TestBase +{ + protected DatabaseMethodsTests(ITestOutputHelper output) + : base(output) { } + + public abstract Task OpenConnectionAsync(); + + [Fact] + protected virtual async Task Database_Can_RunArbitraryQueriesAsync() + { + using var db = await OpenConnectionAsync(); + const int expected = 1; + var actual = await db.QueryFirstAsync("SELECT 1"); + Assert.Equal(expected, actual); + + // run a statement with many sql statements at the same time + await db.ExecuteAsync( + """ + + CREATE TABLE test (id INT PRIMARY KEY); + INSERT INTO test VALUES (1); + INSERT INTO test VALUES (2); + INSERT INTO test VALUES (3); + + """ + ); + var values = await db.QueryAsync("SELECT id FROM test"); + Assert.Equal(3, values.Count()); + + // run multiple select statements and read multiple result sets + var result = await db.QueryMultipleAsync( + """ + + SELECT id FROM test WHERE id = 1; + SELECT id FROM test WHERE id = 2; + SELECT id FROM test; + -- this statement is ignored by the grid reader + -- because it doesn't return any results + INSERT INTO test VALUES (4); + SELECT id FROM test WHERE id = 4; + + """ + ); + var id1 = result.Read().Single(); + var id2 = result.Read().Single(); + var allIds = result.Read().ToArray(); + var id4 = result.Read().Single(); + Assert.Equal(1, id1); + Assert.Equal(2, id2); + Assert.Equal(3, allIds.Length); + Assert.Equal(4, id4); + } + + [Fact] + protected virtual async Task GetDatabaseVersionAsync_ReturnsVersion() + { + using var db = await OpenConnectionAsync(); + + var version = await db.GetDatabaseVersionAsync(); + Assert.True(version.Major > 0); + + Output.WriteLine("Database version: {0}", version); + } +} diff --git a/tests/DapperMatic.Tests/ExtensionMethodTests.cs b/tests/MJCZone.DapperMatic.Tests/ExtensionMethodTests.cs similarity index 94% rename from tests/DapperMatic.Tests/ExtensionMethodTests.cs rename to tests/MJCZone.DapperMatic.Tests/ExtensionMethodTests.cs index d5eed47..7672d1c 100644 --- a/tests/DapperMatic.Tests/ExtensionMethodTests.cs +++ b/tests/MJCZone.DapperMatic.Tests/ExtensionMethodTests.cs @@ -1,44 +1,44 @@ -namespace DapperMatic.Tests; - -public class ExtensionMethodTests -{ - // tes the GetFriendlyName method - [Theory] - [InlineData(typeof(bool), "Boolean")] - [InlineData(typeof(List), "List")] - [InlineData( - typeof(IEnumerable>>), - "IEnumerable>>" - )] - public void TestGetFriendlyName(Type input, string expected) - { - var actual = input.GetFriendlyName(); - Assert.Equal(expected, actual); - } - - // test the ToAlpha method - [Theory] - [InlineData("abc", "abc")] - [InlineData("abc123", "abc")] - [InlineData("abc123def", "abcdef")] - [InlineData("abc123def456", "abcdef")] - [InlineData("abc (&__-1234)123def456ghi", "abcdefghi")] - [InlineData("abc (&__-1234)123def456ghi", "abc(&__)defghi", "_&()")] - public void TestToAlpha(string input, string expected, string additionalAllowedCharacters = "") - { - var actual = input.ToAlpha(additionalAllowedCharacters); - Assert.Equal(expected, actual); - } - - [Theory] - [InlineData("char", "char")] - [InlineData("decimal(10,2)", "decimal")] - [InlineData("abc(12,2) dd aa", "abc dd aa")] - [InlineData("abc ( 12 ,2 ) dd aa", "abc dd aa")] - [InlineData(" nvarchar ( 255 ) ", "nvarchar")] - public void TestDiscardLengthPrecisionAndScaleFromSqlTypeName(string input, string expected) - { - var actual = input.DiscardLengthPrecisionAndScaleFromSqlTypeName(); - Assert.Equal(expected, actual); - } -} +namespace MJCZone.DapperMatic.Tests; + +public class ExtensionMethodTests +{ + // tes the GetFriendlyName method + [Theory] + [InlineData(typeof(bool), "Boolean")] + [InlineData(typeof(List), "List")] + [InlineData( + typeof(IEnumerable>>), + "IEnumerable>>" + )] + public void TestGetFriendlyName(Type input, string expected) + { + var actual = input.GetFriendlyName(); + Assert.Equal(expected, actual); + } + + // test the ToAlpha method + [Theory] + [InlineData("abc", "abc")] + [InlineData("abc123", "abc")] + [InlineData("abc123def", "abcdef")] + [InlineData("abc123def456", "abcdef")] + [InlineData("abc (&__-1234)123def456ghi", "abcdefghi")] + [InlineData("abc (&__-1234)123def456ghi", "abc(&__)defghi", "_&()")] + public void TestToAlpha(string input, string expected, string additionalAllowedCharacters = "") + { + var actual = input.ToAlpha(additionalAllowedCharacters); + Assert.Equal(expected, actual); + } + + [Theory] + [InlineData("char", "char")] + [InlineData("decimal(10,2)", "decimal")] + [InlineData("abc(12,2) dd aa", "abc dd aa")] + [InlineData("abc ( 12 ,2 ) dd aa", "abc dd aa")] + [InlineData(" nvarchar ( 255 ) ", "nvarchar")] + public void TestDiscardLengthPrecisionAndScaleFromSqlTypeName(string input, string expected) + { + var actual = input.DiscardLengthPrecisionAndScaleFromSqlTypeName(); + Assert.Equal(expected, actual); + } +} diff --git a/tests/DapperMatic.Tests/IDatabaseFixture.cs b/tests/MJCZone.DapperMatic.Tests/IDatabaseFixture.cs similarity index 71% rename from tests/DapperMatic.Tests/IDatabaseFixture.cs rename to tests/MJCZone.DapperMatic.Tests/IDatabaseFixture.cs index 74fad74..aa33f34 100644 --- a/tests/DapperMatic.Tests/IDatabaseFixture.cs +++ b/tests/MJCZone.DapperMatic.Tests/IDatabaseFixture.cs @@ -1,7 +1,7 @@ -namespace DapperMatic.Tests; - -public interface IDatabaseFixture -{ - string ConnectionString { get; } - string ContainerId { get; } -} +namespace MJCZone.DapperMatic.Tests; + +public interface IDatabaseFixture +{ + string ConnectionString { get; } + string ContainerId { get; } +} diff --git a/tests/DapperMatic.Tests/Logging/TestLogger.cs b/tests/MJCZone.DapperMatic.Tests/Logging/TestLogger.cs similarity index 88% rename from tests/DapperMatic.Tests/Logging/TestLogger.cs rename to tests/MJCZone.DapperMatic.Tests/Logging/TestLogger.cs index e5bc66e..482e687 100644 --- a/tests/DapperMatic.Tests/Logging/TestLogger.cs +++ b/tests/MJCZone.DapperMatic.Tests/Logging/TestLogger.cs @@ -1,55 +1,55 @@ -using System.Diagnostics; -using Microsoft.Extensions.Logging; -using Xunit.Abstractions; - -namespace DapperMatic.Tests.Logging; - -public class TestLogger : ILogger, IDisposable -{ - private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); - - private LogLevel _minLogLevel = LogLevel.Debug; - private ITestOutputHelper _output; - private string _categoryName; - - public TestLogger(ITestOutputHelper output, string categoryName) - { - _output = output; - _categoryName = categoryName; - } - - public IDisposable? BeginScope(TState state) - where TState : notnull - { - return this; - } - - public bool IsEnabled(LogLevel logLevel) - { - return logLevel >= _minLogLevel; - } - - public void Log( - LogLevel logLevel, - EventId eventId, - TState state, - Exception? exception, - Func formatter - ) - { - if (IsEnabled(logLevel)) - { - _output.WriteLine( - "[DapperMatic {0:hh\\:mm\\:ss\\.ff}] {1}", - _stopwatch.Elapsed, - formatter.Invoke(state, exception) - ); - } - } - - /// - public void Dispose() - { - // The default console logger does not support scopes. We return itself as IDisposable implementation. - } -} +using System.Diagnostics; +using Microsoft.Extensions.Logging; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests.Logging; + +public class TestLogger : ILogger, IDisposable +{ + private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); + + private LogLevel _minLogLevel = LogLevel.Debug; + private ITestOutputHelper _output; + private string _categoryName; + + public TestLogger(ITestOutputHelper output, string categoryName) + { + _output = output; + _categoryName = categoryName; + } + + public IDisposable? BeginScope(TState state) + where TState : notnull + { + return this; + } + + public bool IsEnabled(LogLevel logLevel) + { + return logLevel >= _minLogLevel; + } + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter + ) + { + if (IsEnabled(logLevel)) + { + _output.WriteLine( + "[MJCZone.DapperMatic {0:hh\\:mm\\:ss\\.ff}] {1}", + _stopwatch.Elapsed, + formatter.Invoke(state, exception) + ); + } + } + + /// + public void Dispose() + { + // The default console logger does not support scopes. We return itself as IDisposable implementation. + } +} diff --git a/tests/DapperMatic.Tests/Logging/TestLoggerFactory.cs b/tests/MJCZone.DapperMatic.Tests/Logging/TestLoggerFactory.cs similarity index 87% rename from tests/DapperMatic.Tests/Logging/TestLoggerFactory.cs rename to tests/MJCZone.DapperMatic.Tests/Logging/TestLoggerFactory.cs index 2203941..a45d5ab 100644 --- a/tests/DapperMatic.Tests/Logging/TestLoggerFactory.cs +++ b/tests/MJCZone.DapperMatic.Tests/Logging/TestLoggerFactory.cs @@ -1,26 +1,26 @@ -using Microsoft.Extensions.Logging; -using Xunit.Abstractions; - -namespace DapperMatic.Tests.Logging; - -public class TestLoggerProvider : ILoggerProvider -{ - private readonly ITestOutputHelper _output; - - public TestLoggerProvider(ITestOutputHelper output) - { - _output = output; - } - - public bool IsEnabled(LogLevel logLevel) - { - return true; - } - - public ILogger CreateLogger(string categoryName) - { - return new TestLogger(_output, categoryName); - } - - public void Dispose() { } -} +using Microsoft.Extensions.Logging; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests.Logging; + +public class TestLoggerProvider : ILoggerProvider +{ + private readonly ITestOutputHelper _output; + + public TestLoggerProvider(ITestOutputHelper output) + { + _output = output; + } + + public bool IsEnabled(LogLevel logLevel) + { + return true; + } + + public ILogger CreateLogger(string categoryName) + { + return new TestLogger(_output, categoryName); + } + + public void Dispose() { } +} diff --git a/tests/DapperMatic.Tests/DapperMatic.Tests.csproj b/tests/MJCZone.DapperMatic.Tests/MJCZone.DapperMatic.Tests.csproj similarity index 86% rename from tests/DapperMatic.Tests/DapperMatic.Tests.csproj rename to tests/MJCZone.DapperMatic.Tests/MJCZone.DapperMatic.Tests.csproj index f959220..820a2b5 100644 --- a/tests/DapperMatic.Tests/DapperMatic.Tests.csproj +++ b/tests/MJCZone.DapperMatic.Tests/MJCZone.DapperMatic.Tests.csproj @@ -13,7 +13,9 @@ + + @@ -31,7 +33,7 @@ - + diff --git a/tests/DapperMatic.Tests/ProviderFixtures/DatabaseFixtureBase.cs b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/DatabaseFixtureBase.cs similarity index 89% rename from tests/DapperMatic.Tests/ProviderFixtures/DatabaseFixtureBase.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderFixtures/DatabaseFixtureBase.cs index 895fdd1..ce577d6 100644 --- a/tests/DapperMatic.Tests/ProviderFixtures/DatabaseFixtureBase.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/DatabaseFixtureBase.cs @@ -1,18 +1,18 @@ -using DotNet.Testcontainers.Containers; - -namespace DapperMatic.Tests.ProviderFixtures; - -public abstract class DatabaseFixtureBase : IDatabaseFixture, IAsyncLifetime - where TContainer : DockerContainer, IDatabaseContainer -{ - public abstract TContainer Container { get; } - - public virtual string ConnectionString => Container.GetConnectionString(); - public virtual string ContainerId => $"{Container.Id}"; - - public virtual Task InitializeAsync() => Container.StartAsync(); - - public virtual Task DisposeAsync() => Container.DisposeAsync().AsTask(); - - public virtual bool IgnoreSqlType(string sqlType) => false; -} +using DotNet.Testcontainers.Containers; + +namespace MJCZone.DapperMatic.Tests.ProviderFixtures; + +public abstract class DatabaseFixtureBase : IDatabaseFixture, IAsyncLifetime + where TContainer : DockerContainer, IDatabaseContainer +{ + public abstract TContainer Container { get; } + + public virtual string ConnectionString => Container.GetConnectionString(); + public virtual string ContainerId => $"{Container.Id}"; + + public virtual Task InitializeAsync() => Container.StartAsync(); + + public virtual Task DisposeAsync() => Container.DisposeAsync().AsTask(); + + public virtual bool IgnoreSqlType(string sqlType) => false; +} diff --git a/tests/DapperMatic.Tests/ProviderFixtures/MariaDbDatabaseFixture.cs b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/MariaDbDatabaseFixture.cs similarity index 92% rename from tests/DapperMatic.Tests/ProviderFixtures/MariaDbDatabaseFixture.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderFixtures/MariaDbDatabaseFixture.cs index c4524f4..fe88b58 100644 --- a/tests/DapperMatic.Tests/ProviderFixtures/MariaDbDatabaseFixture.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/MariaDbDatabaseFixture.cs @@ -1,44 +1,44 @@ -using Testcontainers.MariaDb; -using Testcontainers.MySql; - -namespace DapperMatic.Tests.ProviderFixtures; - -public class MariaDb_11_1_DatabaseFixture : MariaDbDatabaseFixture -{ - public MariaDb_11_1_DatabaseFixture() - : base("mariadb:11.1") { } - - public override bool IgnoreSqlType(string sqlType) - { - return sqlType.Equals("geomcollection", StringComparison.OrdinalIgnoreCase) - || base.IgnoreSqlType(sqlType); - } -} - -public class MariaDb_10_11_DatabaseFixture : MariaDbDatabaseFixture -{ - public MariaDb_10_11_DatabaseFixture() - : base("mariadb:10.11") { } - - public override bool IgnoreSqlType(string sqlType) - { - return sqlType.Equals("geomcollection", StringComparison.OrdinalIgnoreCase) - || base.IgnoreSqlType(sqlType); - } -} - -public abstract class MariaDbDatabaseFixture(string imageName) - : DatabaseFixtureBase -{ - private readonly MariaDbContainer _container = new MariaDbBuilder() - .WithImage(imageName) - .WithPassword("Strong_password_123!") - .WithAutoRemove(true) - .WithCleanUp(true) - .Build(); - - public override MariaDbContainer Container - { - get { return _container; } - } -} +using Testcontainers.MariaDb; +using Testcontainers.MySql; + +namespace MJCZone.DapperMatic.Tests.ProviderFixtures; + +public class MariaDb_11_1_DatabaseFixture : MariaDbDatabaseFixture +{ + public MariaDb_11_1_DatabaseFixture() + : base("mariadb:11.1") { } + + public override bool IgnoreSqlType(string sqlType) + { + return sqlType.Equals("geomcollection", StringComparison.OrdinalIgnoreCase) + || base.IgnoreSqlType(sqlType); + } +} + +public class MariaDb_10_11_DatabaseFixture : MariaDbDatabaseFixture +{ + public MariaDb_10_11_DatabaseFixture() + : base("mariadb:10.11") { } + + public override bool IgnoreSqlType(string sqlType) + { + return sqlType.Equals("geomcollection", StringComparison.OrdinalIgnoreCase) + || base.IgnoreSqlType(sqlType); + } +} + +public abstract class MariaDbDatabaseFixture(string imageName) + : DatabaseFixtureBase +{ + private readonly MariaDbContainer _container = new MariaDbBuilder() + .WithImage(imageName) + .WithPassword("Strong_password_123!") + .WithAutoRemove(true) + .WithCleanUp(true) + .Build(); + + public override MariaDbContainer Container + { + get { return _container; } + } +} diff --git a/tests/DapperMatic.Tests/ProviderFixtures/MySqlDatabaseFixture.cs b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/MySqlDatabaseFixture.cs similarity index 91% rename from tests/DapperMatic.Tests/ProviderFixtures/MySqlDatabaseFixture.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderFixtures/MySqlDatabaseFixture.cs index c13cd90..fed1c96 100644 --- a/tests/DapperMatic.Tests/ProviderFixtures/MySqlDatabaseFixture.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/MySqlDatabaseFixture.cs @@ -1,42 +1,42 @@ -using Testcontainers.MySql; - -namespace DapperMatic.Tests.ProviderFixtures; - -public class MySql_90_DatabaseFixture : MySqlDatabaseFixture -{ - public MySql_90_DatabaseFixture() - : base("mysql:9.0") { } -} - -public class MySql_84_DatabaseFixture : MySqlDatabaseFixture -{ - public MySql_84_DatabaseFixture() - : base("mysql:8.4") { } -} - -public class MySql_57_DatabaseFixture : MySqlDatabaseFixture -{ - public MySql_57_DatabaseFixture() - : base("mysql:5.7") { } - - public override bool IgnoreSqlType(string sqlType) - { - return sqlType.Equals("geomcollection", StringComparison.OrdinalIgnoreCase) - || base.IgnoreSqlType(sqlType); - } -} - -public abstract class MySqlDatabaseFixture(string imageName) : DatabaseFixtureBase -{ - private readonly MySqlContainer _container = new MySqlBuilder() - .WithImage(imageName) - .WithPassword("Strong_password_123!") - .WithAutoRemove(true) - .WithCleanUp(true) - .Build(); - - public override MySqlContainer Container - { - get { return _container; } - } -} +using Testcontainers.MySql; + +namespace MJCZone.DapperMatic.Tests.ProviderFixtures; + +public class MySql_90_DatabaseFixture : MySqlDatabaseFixture +{ + public MySql_90_DatabaseFixture() + : base("mysql:9.0") { } +} + +public class MySql_84_DatabaseFixture : MySqlDatabaseFixture +{ + public MySql_84_DatabaseFixture() + : base("mysql:8.4") { } +} + +public class MySql_57_DatabaseFixture : MySqlDatabaseFixture +{ + public MySql_57_DatabaseFixture() + : base("mysql:5.7") { } + + public override bool IgnoreSqlType(string sqlType) + { + return sqlType.Equals("geomcollection", StringComparison.OrdinalIgnoreCase) + || base.IgnoreSqlType(sqlType); + } +} + +public abstract class MySqlDatabaseFixture(string imageName) : DatabaseFixtureBase +{ + private readonly MySqlContainer _container = new MySqlBuilder() + .WithImage(imageName) + .WithPassword("Strong_password_123!") + .WithAutoRemove(true) + .WithCleanUp(true) + .Build(); + + public override MySqlContainer Container + { + get { return _container; } + } +} diff --git a/tests/DapperMatic.Tests/ProviderFixtures/PostgreSqlDatabaseFixtures.cs b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/PostgreSqlDatabaseFixtures.cs similarity index 92% rename from tests/DapperMatic.Tests/ProviderFixtures/PostgreSqlDatabaseFixtures.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderFixtures/PostgreSqlDatabaseFixtures.cs index cd94df8..c30ad88 100644 --- a/tests/DapperMatic.Tests/ProviderFixtures/PostgreSqlDatabaseFixtures.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/PostgreSqlDatabaseFixtures.cs @@ -1,43 +1,43 @@ -using Testcontainers.PostgreSql; - -namespace DapperMatic.Tests.ProviderFixtures; - -public class PostgreSql_Postgres15_DatabaseFixture : PostgreSqlDatabaseFixture -{ - public PostgreSql_Postgres15_DatabaseFixture() - : base("postgres:16") { } -} - -public class PostgreSql_Postgres16_DatabaseFixture : PostgreSqlDatabaseFixture -{ - public PostgreSql_Postgres16_DatabaseFixture() - : base("postgres:16") { } -} - -public class PostgreSql_Postgis15_DatabaseFixture : PostgreSqlDatabaseFixture -{ - public PostgreSql_Postgis15_DatabaseFixture() - : base("postgis/postgis:15-3.4") { } -} - -public class PostgreSql_Postgis16_DatabaseFixture : PostgreSqlDatabaseFixture -{ - public PostgreSql_Postgis16_DatabaseFixture() - : base("postgis/postgis:16-3.4") { } -} - -public abstract class PostgreSqlDatabaseFixture(string imageName) - : DatabaseFixtureBase -{ - private readonly PostgreSqlContainer _container = new PostgreSqlBuilder() - .WithImage(imageName) - .WithPassword("Strong_password_123!") - .WithAutoRemove(true) - .WithCleanUp(true) - .Build(); - - public override PostgreSqlContainer Container - { - get { return _container; } - } -} +using Testcontainers.PostgreSql; + +namespace MJCZone.DapperMatic.Tests.ProviderFixtures; + +public class PostgreSql_Postgres15_DatabaseFixture : PostgreSqlDatabaseFixture +{ + public PostgreSql_Postgres15_DatabaseFixture() + : base("postgres:16") { } +} + +public class PostgreSql_Postgres16_DatabaseFixture : PostgreSqlDatabaseFixture +{ + public PostgreSql_Postgres16_DatabaseFixture() + : base("postgres:16") { } +} + +public class PostgreSql_Postgis15_DatabaseFixture : PostgreSqlDatabaseFixture +{ + public PostgreSql_Postgis15_DatabaseFixture() + : base("postgis/postgis:15-3.4") { } +} + +public class PostgreSql_Postgis16_DatabaseFixture : PostgreSqlDatabaseFixture +{ + public PostgreSql_Postgis16_DatabaseFixture() + : base("postgis/postgis:16-3.4") { } +} + +public abstract class PostgreSqlDatabaseFixture(string imageName) + : DatabaseFixtureBase +{ + private readonly PostgreSqlContainer _container = new PostgreSqlBuilder() + .WithImage(imageName) + .WithPassword("Strong_password_123!") + .WithAutoRemove(true) + .WithCleanUp(true) + .Build(); + + public override PostgreSqlContainer Container + { + get { return _container; } + } +} diff --git a/tests/DapperMatic.Tests/ProviderFixtures/SqlServerDatabaseFixtures.cs b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/SqlServerDatabaseFixtures.cs similarity index 93% rename from tests/DapperMatic.Tests/ProviderFixtures/SqlServerDatabaseFixtures.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderFixtures/SqlServerDatabaseFixtures.cs index c1e4afb..da526b8 100644 --- a/tests/DapperMatic.Tests/ProviderFixtures/SqlServerDatabaseFixtures.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderFixtures/SqlServerDatabaseFixtures.cs @@ -1,40 +1,40 @@ -using Testcontainers.MsSql; - -namespace DapperMatic.Tests.ProviderFixtures; - -public class SqlServer_2022_CU13_Ubuntu_DatabaseFixture : SqlServerDatabaseFixture -{ - public SqlServer_2022_CU13_Ubuntu_DatabaseFixture() - : base("mcr.microsoft.com/mssql/server:2022-CU13-ubuntu-22.04") { } - // : base("mcr.microsoft.com/mssql/server:2022-latest") { } -} - -public class SqlServer_2019_CU27_DatabaseFixture : SqlServerDatabaseFixture -{ - public SqlServer_2019_CU27_DatabaseFixture() - : base("mcr.microsoft.com/mssql/server:2019-CU27-ubuntu-20.04") { } - // : base("mcr.microsoft.com/mssql/server:2019-latest") { } -} - -public class SqlServer_2017_CU29_DatabaseFixture : SqlServerDatabaseFixture -{ - public SqlServer_2017_CU29_DatabaseFixture() - : base("mcr.microsoft.com/mssql/server:2017-CU29-ubuntu-16.04") { } - // : base("mcr.microsoft.com/mssql/server:2017-latest") { } -} - -public abstract class SqlServerDatabaseFixture(string imageName) - : DatabaseFixtureBase -{ - private readonly MsSqlContainer _container = new MsSqlBuilder() - .WithImage(imageName) - .WithPassword("Strong_password_123!") - .WithAutoRemove(true) - .WithCleanUp(true) - .Build(); - - public override MsSqlContainer Container - { - get { return _container; } - } -} +using Testcontainers.MsSql; + +namespace MJCZone.DapperMatic.Tests.ProviderFixtures; + +public class SqlServer_2022_CU13_Ubuntu_DatabaseFixture : SqlServerDatabaseFixture +{ + public SqlServer_2022_CU13_Ubuntu_DatabaseFixture() + : base("mcr.microsoft.com/mssql/server:2022-CU13-ubuntu-22.04") { } + // : base("mcr.microsoft.com/mssql/server:2022-latest") { } +} + +public class SqlServer_2019_CU27_DatabaseFixture : SqlServerDatabaseFixture +{ + public SqlServer_2019_CU27_DatabaseFixture() + : base("mcr.microsoft.com/mssql/server:2019-CU27-ubuntu-20.04") { } + // : base("mcr.microsoft.com/mssql/server:2019-latest") { } +} + +public class SqlServer_2017_CU29_DatabaseFixture : SqlServerDatabaseFixture +{ + public SqlServer_2017_CU29_DatabaseFixture() + : base("mcr.microsoft.com/mssql/server:2017-CU29-ubuntu-16.04") { } + // : base("mcr.microsoft.com/mssql/server:2017-latest") { } +} + +public abstract class SqlServerDatabaseFixture(string imageName) + : DatabaseFixtureBase +{ + private readonly MsSqlContainer _container = new MsSqlBuilder() + .WithImage(imageName) + .WithPassword("Strong_password_123!") + .WithAutoRemove(true) + .WithCleanUp(true) + .Build(); + + public override MsSqlContainer Container + { + get { return _container; } + } +} diff --git a/tests/DapperMatic.Tests/ProviderTests/MariaDbDatabaseMethodsTests.cs b/tests/MJCZone.DapperMatic.Tests/ProviderTests/MariaDbDatabaseMethodsTests.cs similarity index 92% rename from tests/DapperMatic.Tests/ProviderTests/MariaDbDatabaseMethodsTests.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderTests/MariaDbDatabaseMethodsTests.cs index 525c640..0161109 100644 --- a/tests/DapperMatic.Tests/ProviderTests/MariaDbDatabaseMethodsTests.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderTests/MariaDbDatabaseMethodsTests.cs @@ -1,68 +1,68 @@ -using System.Data; -using DapperMatic.Tests.ProviderFixtures; -using MySql.Data.MySqlClient; -using Xunit.Abstractions; - -namespace DapperMatic.Tests.ProviderTests; - -/// -/// Testing MariaDb 11.2 -/// -public class MariaDb_11_1_DatabaseMethodsTests( - MariaDb_11_1_DatabaseFixture fixture, - ITestOutputHelper output -) : MariaDbDatabaseMethodsTests(fixture, output) { } - -/// -/// Testing MariaDb 10.11 -/// -public class MariaDb_10_11_DatabaseMethodsTests( - MariaDb_10_11_DatabaseFixture fixture, - ITestOutputHelper output -) : MariaDbDatabaseMethodsTests(fixture, output) { } - -/// -/// Abstract class for MySql database tests -/// -/// -public abstract class MariaDbDatabaseMethodsTests( - TDatabaseFixture fixture, - ITestOutputHelper output -) : DatabaseMethodsTests(output), IClassFixture, IDisposable - where TDatabaseFixture : MariaDbDatabaseFixture -{ - static MariaDbDatabaseMethodsTests() - { - Providers.DatabaseMethodsProvider.RegisterFactory( - nameof(ProfiledMariaDbMethodsFactory), - new ProfiledMariaDbMethodsFactory() - ); - } - - public override async Task OpenConnectionAsync() - { - var connectionString = fixture.ConnectionString; - // Disable SSL for local testing and CI environments - if (!connectionString.Contains("SSL Mode", StringComparison.OrdinalIgnoreCase)) - { - connectionString += ";SSL Mode=None"; - } - var db = new DbQueryLogging.LoggedDbConnection( - new MySqlConnection(connectionString), - new Logging.TestLogger(Output, nameof(MySqlConnection)) - ); - await db.OpenAsync(); - return db; - } - - public override bool IgnoreSqlType(string sqlType) - { - return fixture.IgnoreSqlType(sqlType); - } -} - -public class ProfiledMariaDbMethodsFactory : Providers.MySql.MySqlMethodsFactory -{ - public override bool SupportsConnectionCustom(IDbConnection db) => - db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is MySqlConnection; -} +using System.Data; +using MJCZone.DapperMatic.Tests.ProviderFixtures; +using MySql.Data.MySqlClient; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests.ProviderTests; + +/// +/// Testing MariaDb 11.2 +/// +public class MariaDb_11_1_DatabaseMethodsTests( + MariaDb_11_1_DatabaseFixture fixture, + ITestOutputHelper output +) : MariaDbDatabaseMethodsTests(fixture, output) { } + +/// +/// Testing MariaDb 10.11 +/// +public class MariaDb_10_11_DatabaseMethodsTests( + MariaDb_10_11_DatabaseFixture fixture, + ITestOutputHelper output +) : MariaDbDatabaseMethodsTests(fixture, output) { } + +/// +/// Abstract class for MySql database tests +/// +/// +public abstract class MariaDbDatabaseMethodsTests( + TDatabaseFixture fixture, + ITestOutputHelper output +) : DatabaseMethodsTests(output), IClassFixture, IDisposable + where TDatabaseFixture : MariaDbDatabaseFixture +{ + static MariaDbDatabaseMethodsTests() + { + Providers.DatabaseMethodsProvider.RegisterFactory( + nameof(ProfiledMariaDbMethodsFactory), + new ProfiledMariaDbMethodsFactory() + ); + } + + public override async Task OpenConnectionAsync() + { + var connectionString = fixture.ConnectionString; + // Disable SSL for local testing and CI environments + if (!connectionString.Contains("SSL Mode", StringComparison.OrdinalIgnoreCase)) + { + connectionString += ";SSL Mode=None"; + } + var db = new DbQueryLogging.LoggedDbConnection( + new MySqlConnection(connectionString), + new Logging.TestLogger(Output, nameof(MySqlConnection)) + ); + await db.OpenAsync(); + return db; + } + + public override bool IgnoreSqlType(string sqlType) + { + return fixture.IgnoreSqlType(sqlType); + } +} + +public class ProfiledMariaDbMethodsFactory : Providers.MySql.MySqlMethodsFactory +{ + public override bool SupportsConnectionCustom(IDbConnection db) => + db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is MySqlConnection; +} diff --git a/tests/DapperMatic.Tests/ProviderTests/MySqlDatabaseMethodsTests.cs b/tests/MJCZone.DapperMatic.Tests/ProviderTests/MySqlDatabaseMethodsTests.cs similarity index 92% rename from tests/DapperMatic.Tests/ProviderTests/MySqlDatabaseMethodsTests.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderTests/MySqlDatabaseMethodsTests.cs index 3406ef6..fcbbfef 100644 --- a/tests/DapperMatic.Tests/ProviderTests/MySqlDatabaseMethodsTests.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderTests/MySqlDatabaseMethodsTests.cs @@ -1,76 +1,76 @@ -using System.Data; -using DapperMatic.Tests.ProviderFixtures; -using MySql.Data.MySqlClient; -using Xunit.Abstractions; - -namespace DapperMatic.Tests.ProviderTests; - -/// -/// Testing MySql 90 -/// -public class MySql_90_DatabaseMethodsTests( - MySql_90_DatabaseFixture fixture, - ITestOutputHelper output -) : MySqlDatabaseMethodsTests(fixture, output) { } - -/// -/// Testing MySql 84 -/// -public class MySql_84_DatabaseMethodsTests( - MySql_84_DatabaseFixture fixture, - ITestOutputHelper output -) : MySqlDatabaseMethodsTests(fixture, output) { } - -/// -/// Testing MySql 57 -/// -public class MySql_57_DatabaseMethodsTests( - MySql_57_DatabaseFixture fixture, - ITestOutputHelper output -) : MySqlDatabaseMethodsTests(fixture, output) { } - -/// -/// Abstract class for MySql database tests -/// -/// -public abstract class MySqlDatabaseMethodsTests( - TDatabaseFixture fixture, - ITestOutputHelper output -) : DatabaseMethodsTests(output), IClassFixture, IDisposable - where TDatabaseFixture : MySqlDatabaseFixture -{ - static MySqlDatabaseMethodsTests() - { - Providers.DatabaseMethodsProvider.RegisterFactory( - nameof(ProfiledMySqlMethodsFactory), - new ProfiledMySqlMethodsFactory() - ); - } - - public override async Task OpenConnectionAsync() - { - var connectionString = fixture.ConnectionString; - // Disable SSL for local testing and CI environments - if (!connectionString.Contains("SSL Mode", StringComparison.OrdinalIgnoreCase)) - { - connectionString += ";SSL Mode=None"; - } - var db = new DbQueryLogging.LoggedDbConnection( - new MySqlConnection(connectionString), - new Logging.TestLogger(Output, nameof(MySqlConnection)) - ); - await db.OpenAsync(); - return db; - } - - public override bool IgnoreSqlType(string sqlType) - { - return fixture.IgnoreSqlType(sqlType); - } -} - -public class ProfiledMySqlMethodsFactory : Providers.MySql.MySqlMethodsFactory -{ - public override bool SupportsConnectionCustom(IDbConnection db) => - db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is MySqlConnection; -} +using System.Data; +using MJCZone.DapperMatic.Tests.ProviderFixtures; +using MySql.Data.MySqlClient; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests.ProviderTests; + +/// +/// Testing MySql 90 +/// +public class MySql_90_DatabaseMethodsTests( + MySql_90_DatabaseFixture fixture, + ITestOutputHelper output +) : MySqlDatabaseMethodsTests(fixture, output) { } + +/// +/// Testing MySql 84 +/// +public class MySql_84_DatabaseMethodsTests( + MySql_84_DatabaseFixture fixture, + ITestOutputHelper output +) : MySqlDatabaseMethodsTests(fixture, output) { } + +/// +/// Testing MySql 57 +/// +public class MySql_57_DatabaseMethodsTests( + MySql_57_DatabaseFixture fixture, + ITestOutputHelper output +) : MySqlDatabaseMethodsTests(fixture, output) { } + +/// +/// Abstract class for MySql database tests +/// +/// +public abstract class MySqlDatabaseMethodsTests( + TDatabaseFixture fixture, + ITestOutputHelper output +) : DatabaseMethodsTests(output), IClassFixture, IDisposable + where TDatabaseFixture : MySqlDatabaseFixture +{ + static MySqlDatabaseMethodsTests() + { + Providers.DatabaseMethodsProvider.RegisterFactory( + nameof(ProfiledMySqlMethodsFactory), + new ProfiledMySqlMethodsFactory() + ); + } + + public override async Task OpenConnectionAsync() + { + var connectionString = fixture.ConnectionString; + // Disable SSL for local testing and CI environments + if (!connectionString.Contains("SSL Mode", StringComparison.OrdinalIgnoreCase)) + { + connectionString += ";SSL Mode=None"; + } + var db = new DbQueryLogging.LoggedDbConnection( + new MySqlConnection(connectionString), + new Logging.TestLogger(Output, nameof(MySqlConnection)) + ); + await db.OpenAsync(); + return db; + } + + public override bool IgnoreSqlType(string sqlType) + { + return fixture.IgnoreSqlType(sqlType); + } +} + +public class ProfiledMySqlMethodsFactory : Providers.MySql.MySqlMethodsFactory +{ + public override bool SupportsConnectionCustom(IDbConnection db) => + db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is MySqlConnection; +} diff --git a/tests/DapperMatic.Tests/ProviderTests/PostgreSqlDatabaseMethodsTests.cs b/tests/MJCZone.DapperMatic.Tests/ProviderTests/PostgreSqlDatabaseMethodsTests.cs similarity index 92% rename from tests/DapperMatic.Tests/ProviderTests/PostgreSqlDatabaseMethodsTests.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderTests/PostgreSqlDatabaseMethodsTests.cs index 5a93111..2b6daf5 100644 --- a/tests/DapperMatic.Tests/ProviderTests/PostgreSqlDatabaseMethodsTests.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderTests/PostgreSqlDatabaseMethodsTests.cs @@ -1,86 +1,86 @@ -using System.Data; -using Dapper; -using DapperMatic.Providers; -using DapperMatic.Tests.ProviderFixtures; -using Npgsql; -using Xunit.Abstractions; - -namespace DapperMatic.Tests.ProviderTests; - -/// -/// Testing Postgres 15 -/// -public class PostgreSql_Postgres15_DatabaseMethodsTests( - PostgreSql_Postgres15_DatabaseFixture fixture, - ITestOutputHelper output -) : PostgreSqlDatabaseMethodsTests(fixture, output) { } - -/// -/// Testing Postgres 16 -/// -public class PostgreSql_Postgres16_DatabaseMethodsTests( - PostgreSql_Postgres16_DatabaseFixture fixture, - ITestOutputHelper output -) : PostgreSqlDatabaseMethodsTests(fixture, output) { } - -/// -/// Testing Postgres 156 with Postgis -/// -public class PostgreSql_Postgis15_DatabaseMethodsTests( - PostgreSql_Postgis15_DatabaseFixture fixture, - ITestOutputHelper output -) : PostgreSqlDatabaseMethodsTests(fixture, output) { } - -/// -/// Testing Postgres 16 with Postgis -/// -public class PostgreSql_Postgis16_DatabaseMethodsTests( - PostgreSql_Postgis16_DatabaseFixture fixture, - ITestOutputHelper output -) : PostgreSqlDatabaseMethodsTests(fixture, output) { } - -/// -/// Abstract class for Postgres database tests -/// -/// -public abstract class PostgreSqlDatabaseMethodsTests( - TDatabaseFixture fixture, - ITestOutputHelper output -) : DatabaseMethodsTests(output), IClassFixture, IDisposable - where TDatabaseFixture : PostgreSqlDatabaseFixture -{ - static PostgreSqlDatabaseMethodsTests() - { - DatabaseMethodsProvider.RegisterFactory( - nameof(ProfiledPostgreSqlMethodsFactory), - new ProfiledPostgreSqlMethodsFactory() - ); - } - - public override async Task OpenConnectionAsync() - { - var db = new DbQueryLogging.LoggedDbConnection( - new NpgsqlConnection(fixture.ConnectionString), - new Logging.TestLogger(Output, nameof(NpgsqlConnection)) - ); - await db.OpenAsync(); - await db.ExecuteAsync("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";"); - await db.ExecuteAsync("CREATE EXTENSION IF NOT EXISTS \"hstore\";"); - if ( - await db.ExecuteScalarAsync( - @"select count(*) from pg_extension where extname = 'postgis'" - ) > 0 - ) - { - await db.ExecuteAsync("CREATE EXTENSION IF NOT EXISTS \"postgis\";"); - await db.ExecuteAsync("CREATE EXTENSION IF NOT EXISTS \"postgis_topology\";"); - } - return db; - } -} - -public class ProfiledPostgreSqlMethodsFactory : Providers.PostgreSql.PostgreSqlMethodsFactory -{ - public override bool SupportsConnectionCustom(IDbConnection db) => - db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is NpgsqlConnection; -} +using System.Data; +using Dapper; +using MJCZone.DapperMatic.Providers; +using MJCZone.DapperMatic.Tests.ProviderFixtures; +using Npgsql; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests.ProviderTests; + +/// +/// Testing Postgres 15 +/// +public class PostgreSql_Postgres15_DatabaseMethodsTests( + PostgreSql_Postgres15_DatabaseFixture fixture, + ITestOutputHelper output +) : PostgreSqlDatabaseMethodsTests(fixture, output) { } + +/// +/// Testing Postgres 16 +/// +public class PostgreSql_Postgres16_DatabaseMethodsTests( + PostgreSql_Postgres16_DatabaseFixture fixture, + ITestOutputHelper output +) : PostgreSqlDatabaseMethodsTests(fixture, output) { } + +/// +/// Testing Postgres 156 with Postgis +/// +public class PostgreSql_Postgis15_DatabaseMethodsTests( + PostgreSql_Postgis15_DatabaseFixture fixture, + ITestOutputHelper output +) : PostgreSqlDatabaseMethodsTests(fixture, output) { } + +/// +/// Testing Postgres 16 with Postgis +/// +public class PostgreSql_Postgis16_DatabaseMethodsTests( + PostgreSql_Postgis16_DatabaseFixture fixture, + ITestOutputHelper output +) : PostgreSqlDatabaseMethodsTests(fixture, output) { } + +/// +/// Abstract class for Postgres database tests +/// +/// +public abstract class PostgreSqlDatabaseMethodsTests( + TDatabaseFixture fixture, + ITestOutputHelper output +) : DatabaseMethodsTests(output), IClassFixture, IDisposable + where TDatabaseFixture : PostgreSqlDatabaseFixture +{ + static PostgreSqlDatabaseMethodsTests() + { + DatabaseMethodsProvider.RegisterFactory( + nameof(ProfiledPostgreSqlMethodsFactory), + new ProfiledPostgreSqlMethodsFactory() + ); + } + + public override async Task OpenConnectionAsync() + { + var db = new DbQueryLogging.LoggedDbConnection( + new NpgsqlConnection(fixture.ConnectionString), + new Logging.TestLogger(Output, nameof(NpgsqlConnection)) + ); + await db.OpenAsync(); + await db.ExecuteAsync("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";"); + await db.ExecuteAsync("CREATE EXTENSION IF NOT EXISTS \"hstore\";"); + if ( + await db.ExecuteScalarAsync( + @"select count(*) from pg_extension where extname = 'postgis'" + ) > 0 + ) + { + await db.ExecuteAsync("CREATE EXTENSION IF NOT EXISTS \"postgis\";"); + await db.ExecuteAsync("CREATE EXTENSION IF NOT EXISTS \"postgis_topology\";"); + } + return db; + } +} + +public class ProfiledPostgreSqlMethodsFactory : Providers.PostgreSql.PostgreSqlMethodsFactory +{ + public override bool SupportsConnectionCustom(IDbConnection db) => + db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is NpgsqlConnection; +} diff --git a/tests/DapperMatic.Tests/ProviderTests/SQLiteDatabaseMethodsTests.cs b/tests/MJCZone.DapperMatic.Tests/ProviderTests/SQLiteDatabaseMethodsTests.cs similarity index 93% rename from tests/DapperMatic.Tests/ProviderTests/SQLiteDatabaseMethodsTests.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderTests/SQLiteDatabaseMethodsTests.cs index e7a16ca..c7d07d9 100644 --- a/tests/DapperMatic.Tests/ProviderTests/SQLiteDatabaseMethodsTests.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderTests/SQLiteDatabaseMethodsTests.cs @@ -1,49 +1,49 @@ -using System.Data; -using System.Data.SQLite; -using Xunit.Abstractions; - -namespace DapperMatic.Tests.ProviderTests; - -public class SQLiteDatabaseMethodsTests(ITestOutputHelper output) - : DatabaseMethodsTests(output), - IDisposable -{ - static SQLiteDatabaseMethodsTests() - { - Providers.DatabaseMethodsProvider.RegisterFactory( - nameof(ProfiledSqLiteMethodsFactory), - new ProfiledSqLiteMethodsFactory() - ); - } - - public override async Task OpenConnectionAsync() - { - if (File.Exists("sqlite_tests.sqlite")) - { - File.Delete("sqlite_tests.sqlite"); - } - - var db = new DbQueryLogging.LoggedDbConnection( - new SQLiteConnection("Data Source=sqlite_tests.sqlite;Version=3;BinaryGuid=False;"), - new Logging.TestLogger(Output, nameof(SQLiteConnection)) - ); - await db.OpenAsync(); - return db; - } - - public override void Dispose() - { - if (File.Exists("sqlite_tests.sqlite")) - { - File.Delete("sqlite_tests.sqlite"); - } - - base.Dispose(); - } -} - -public class ProfiledSqLiteMethodsFactory : Providers.Sqlite.SqliteMethodsFactory -{ - public override bool SupportsConnectionCustom(IDbConnection db) => - db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is SQLiteConnection; -} +using System.Data; +using System.Data.SQLite; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests.ProviderTests; + +public class SQLiteDatabaseMethodsTests(ITestOutputHelper output) + : DatabaseMethodsTests(output), + IDisposable +{ + static SQLiteDatabaseMethodsTests() + { + Providers.DatabaseMethodsProvider.RegisterFactory( + nameof(ProfiledSqLiteMethodsFactory), + new ProfiledSqLiteMethodsFactory() + ); + } + + public override async Task OpenConnectionAsync() + { + if (File.Exists("sqlite_tests.sqlite")) + { + File.Delete("sqlite_tests.sqlite"); + } + + var db = new DbQueryLogging.LoggedDbConnection( + new SQLiteConnection("Data Source=sqlite_tests.sqlite;Version=3;BinaryGuid=False;"), + new Logging.TestLogger(Output, nameof(SQLiteConnection)) + ); + await db.OpenAsync(); + return db; + } + + public override void Dispose() + { + if (File.Exists("sqlite_tests.sqlite")) + { + File.Delete("sqlite_tests.sqlite"); + } + + base.Dispose(); + } +} + +public class ProfiledSqLiteMethodsFactory : Providers.Sqlite.SqliteMethodsFactory +{ + public override bool SupportsConnectionCustom(IDbConnection db) => + db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is SQLiteConnection; +} diff --git a/tests/DapperMatic.Tests/ProviderTests/SqlServerDatabaseMethodsTests.cs b/tests/MJCZone.DapperMatic.Tests/ProviderTests/SqlServerDatabaseMethodsTests.cs similarity index 92% rename from tests/DapperMatic.Tests/ProviderTests/SqlServerDatabaseMethodsTests.cs rename to tests/MJCZone.DapperMatic.Tests/ProviderTests/SqlServerDatabaseMethodsTests.cs index 86e3843..33f4a33 100644 --- a/tests/DapperMatic.Tests/ProviderTests/SqlServerDatabaseMethodsTests.cs +++ b/tests/MJCZone.DapperMatic.Tests/ProviderTests/SqlServerDatabaseMethodsTests.cs @@ -1,65 +1,65 @@ -using System.Data; -using System.Data.SqlClient; -using DapperMatic.Tests.ProviderFixtures; -using Xunit.Abstractions; - -namespace DapperMatic.Tests.ProviderTests; - -/// -/// Testing SqlServer 2022 Linux (CU image) -/// -public class SqlServer_2022_CU13_Ubuntu_DatabaseMethodsTests( - SqlServer_2022_CU13_Ubuntu_DatabaseFixture fixture, - ITestOutputHelper output -) : SqlServerDatabaseMethodsests(fixture, output) { } - -/// -/// Testing SqlServer 2019 -/// -public class SqlServer_2019_CU27_DatabaseMethodsTests( - SqlServer_2019_CU27_DatabaseFixture fixture, - ITestOutputHelper output -) : SqlServerDatabaseMethodsests(fixture, output) { } - -/// -/// Testing SqlServer 2017 -/// -public class SqlServer_2017_CU29_DatabaseMethodsTests( - SqlServer_2017_CU29_DatabaseFixture fixture, - ITestOutputHelper output -) : SqlServerDatabaseMethodsests(fixture, output) { } - -/// -/// Abstract class for Postgres database tests -/// -/// -public abstract class SqlServerDatabaseMethodsests( - TDatabaseFixture fixture, - ITestOutputHelper output -) : DatabaseMethodsTests(output), IClassFixture, IDisposable - where TDatabaseFixture : SqlServerDatabaseFixture -{ - static SqlServerDatabaseMethodsests() - { - Providers.DatabaseMethodsProvider.RegisterFactory( - nameof(ProfiledSqlServerMethodsFactory), - new ProfiledSqlServerMethodsFactory() - ); - } - - public override async Task OpenConnectionAsync() - { - var db = new DbQueryLogging.LoggedDbConnection( - new SqlConnection(fixture.ConnectionString), - new Logging.TestLogger(Output, nameof(SqlConnection)) - ); - await db.OpenAsync(); - return db; - } -} - -public class ProfiledSqlServerMethodsFactory : Providers.SqlServer.SqlServerMethodsFactory -{ - public override bool SupportsConnectionCustom(IDbConnection db) => - db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is SqlConnection; -} +using System.Data; +using System.Data.SqlClient; +using MJCZone.DapperMatic.Tests.ProviderFixtures; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests.ProviderTests; + +/// +/// Testing SqlServer 2022 Linux (CU image) +/// +public class SqlServer_2022_CU13_Ubuntu_DatabaseMethodsTests( + SqlServer_2022_CU13_Ubuntu_DatabaseFixture fixture, + ITestOutputHelper output +) : SqlServerDatabaseMethodsests(fixture, output) { } + +/// +/// Testing SqlServer 2019 +/// +public class SqlServer_2019_CU27_DatabaseMethodsTests( + SqlServer_2019_CU27_DatabaseFixture fixture, + ITestOutputHelper output +) : SqlServerDatabaseMethodsests(fixture, output) { } + +/// +/// Testing SqlServer 2017 +/// +public class SqlServer_2017_CU29_DatabaseMethodsTests( + SqlServer_2017_CU29_DatabaseFixture fixture, + ITestOutputHelper output +) : SqlServerDatabaseMethodsests(fixture, output) { } + +/// +/// Abstract class for Postgres database tests +/// +/// +public abstract class SqlServerDatabaseMethodsests( + TDatabaseFixture fixture, + ITestOutputHelper output +) : DatabaseMethodsTests(output), IClassFixture, IDisposable + where TDatabaseFixture : SqlServerDatabaseFixture +{ + static SqlServerDatabaseMethodsests() + { + Providers.DatabaseMethodsProvider.RegisterFactory( + nameof(ProfiledSqlServerMethodsFactory), + new ProfiledSqlServerMethodsFactory() + ); + } + + public override async Task OpenConnectionAsync() + { + var db = new DbQueryLogging.LoggedDbConnection( + new SqlConnection(fixture.ConnectionString), + new Logging.TestLogger(Output, nameof(SqlConnection)) + ); + await db.OpenAsync(); + return db; + } +} + +public class ProfiledSqlServerMethodsFactory : Providers.SqlServer.SqlServerMethodsFactory +{ + public override bool SupportsConnectionCustom(IDbConnection db) => + db is DbQueryLogging.LoggedDbConnection loggedDb && loggedDb.Inner is SqlConnection; +} diff --git a/tests/DapperMatic.Tests/TestBase.cs b/tests/MJCZone.DapperMatic.Tests/TestBase.cs similarity index 93% rename from tests/DapperMatic.Tests/TestBase.cs rename to tests/MJCZone.DapperMatic.Tests/TestBase.cs index aeace6e..73ad9dc 100644 --- a/tests/DapperMatic.Tests/TestBase.cs +++ b/tests/MJCZone.DapperMatic.Tests/TestBase.cs @@ -1,50 +1,50 @@ -using System.Data; -using Xunit.Abstractions; - -namespace DapperMatic.Tests; - -public abstract class TestBase : IDisposable -{ - protected readonly ITestOutputHelper Output; - - protected TestBase(ITestOutputHelper output) - { - Output = output; - } - - protected async Task InitFreshSchemaAsync(IDbConnection db, string? schemaName) - { - if (db.SupportsSchemas()) - { - foreach (var view in await db.GetViewsAsync(schemaName)) - { - try - { - await db.DropViewIfExistsAsync(schemaName, view.ViewName); - } - catch { } - } - foreach (var table in await db.GetTablesAsync(schemaName)) - { - await db.DropTableIfExistsAsync(schemaName, table.TableName); - } - // await db.DropSchemaIfExistsAsync(schemaName); - } - if (!string.IsNullOrEmpty(schemaName)) - { - await db.CreateSchemaIfNotExistsAsync(schemaName); - } - } - - public virtual void Dispose() - { - // nothing to dispose - } - - protected void Log(string message) - { - Output.WriteLine(message); - } - - public virtual bool IgnoreSqlType(string sqlType) => false; -} +using System.Data; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests; + +public abstract class TestBase : IDisposable +{ + protected readonly ITestOutputHelper Output; + + protected TestBase(ITestOutputHelper output) + { + Output = output; + } + + protected async Task InitFreshSchemaAsync(IDbConnection db, string? schemaName) + { + if (db.SupportsSchemas()) + { + foreach (var view in await db.GetViewsAsync(schemaName)) + { + try + { + await db.DropViewIfExistsAsync(schemaName, view.ViewName); + } + catch { } + } + foreach (var table in await db.GetTablesAsync(schemaName)) + { + await db.DropTableIfExistsAsync(schemaName, table.TableName); + } + // await db.DropSchemaIfExistsAsync(schemaName); + } + if (!string.IsNullOrEmpty(schemaName)) + { + await db.CreateSchemaIfNotExistsAsync(schemaName); + } + } + + public virtual void Dispose() + { + // nothing to dispose + } + + protected void Log(string message) + { + Output.WriteLine(message); + } + + public virtual bool IgnoreSqlType(string sqlType) => false; +} diff --git a/tests/MJCZone.DapperMatic.Tests/TestOutputDocs.cs b/tests/MJCZone.DapperMatic.Tests/TestOutputDocs.cs new file mode 100644 index 0000000..b3bec0f --- /dev/null +++ b/tests/MJCZone.DapperMatic.Tests/TestOutputDocs.cs @@ -0,0 +1,716 @@ +using System.Reflection; +using System.Text.Json; +using System.Xml.Linq; +using MJCZone.DapperMatic.Providers.Base; +using Xunit.Abstractions; + +namespace MJCZone.DapperMatic.Tests; + +public class TestOutputDocs +{ + public TestOutputDocs(ITestOutputHelper logger) + { + Logger = logger; + } + + private ITestOutputHelper Logger { get; } + + [Fact] + public void Can_generate_docs() + { + var assembly = typeof(DatabaseMethodsBase).Assembly; + + // get the directory of the current assembly + var assemblyDirectory = Path.GetDirectoryName(assembly.Location); + if (assemblyDirectory == null || !Directory.Exists(assemblyDirectory)) + { + Logger.WriteLine("Could not get the directory of the current assembly."); + Assert.True(false); + return; + } + + // get the xml documentation file for the assembly + var xmlFile = Path.Combine(assemblyDirectory, $"{assembly.GetName().Name}.xml"); + if (!File.Exists(xmlFile)) + { + Logger.WriteLine($"Could not find the xml documentation file: {xmlFile}"); + Assert.True(false); + return; + } + + // load the xml documentation file + var xml = XDocument.Load(xmlFile); + if (xml.Root == null) + { + Logger.WriteLine("Could not load the xml documentation file."); + Assert.True(false); + return; + } + + // see: https://github.com/mysticmind/reversemarkdown-net (HTML to md conversion) + + // see: https://github.com/akovanev/NetDocsProcessor/tree/main + // https://github.com/akovanev/NetDocsProcessor/blob/main/demo/Akov.Chillout.Demo/Program.cs + var akovData = new Akov.NetDocsProcessor.Api.DocsProcessorApi() + .ObtainDocumentation( + new Akov.NetDocsProcessor.Input.AssemblyPaths(assembly.Location, xmlFile), + new Akov.NetDocsProcessor.Input.GenerationSettings + { + // AccessLevel = Akov.NetDocsProcessor.Input.AccessLevel.Protected + AccessLevel = Akov.NetDocsProcessor.Input.AccessLevel.Public + } + ) + .ToList(); + + var jsonFile = Path.Combine(assemblyDirectory, $"{assembly.GetName().Name}.json"); + var stringEnumConverter = new System.Text.Json.Serialization.JsonStringEnumConverter(); + var serializationSettings = new JsonSerializerOptions + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = System + .Text + .Json + .Serialization + .JsonIgnoreCondition + .WhenWritingNull, + }; + serializationSettings.Converters.Add(stringEnumConverter); + var output = new + { + enums = new + { + elementTypes = Enum.GetValues(), + accessLevels = Enum.GetValues(), + }, + data = akovData, + }; + File.WriteAllText(jsonFile, JsonSerializer.Serialize(output, serializationSettings)); + //Logger.WriteLine(JsonSerializer.Serialize(akovData, serializationSettings)); + + var docsJsonFileName = $"{assembly.GetName().Name}.docs.json"; + var docsJsonFile = Path.Combine(assemblyDirectory, docsJsonFileName); + var docs = new Docs(); + docs.AddAssembly(assembly, xml); + File.WriteAllText(docsJsonFile, JsonSerializer.Serialize(docs, serializationSettings)); + //Logger.WriteLine(JsonSerializer.Serialize(docs, serializationSettings)); + + // output the file to the docs directory + var rootDirectory = Path.GetDirectoryName(assemblyDirectory) ?? string.Empty; + while (!File.Exists(Path.Combine(rootDirectory, ".editorconfig"))) + { + rootDirectory = Path.GetDirectoryName(rootDirectory); + if (string.IsNullOrEmpty(rootDirectory)) + { + Logger.WriteLine("Could not find the root directory."); + return; + } + } + var packagesDirectory = Path.Combine(rootDirectory, "docs", "packages"); + Directory.CreateDirectory(packagesDirectory); + File.Copy(docsJsonFile, Path.Combine(packagesDirectory, docsJsonFileName), true); + return; + + // The following is prototypical code created BEFORE the Akov.NetDocsProcessor was used. + + // Assert.NotNull(docs.Title); + + // // get the xml documentation for the type + // var xmlMemberNodes = xml.Root.Element("members")?.Elements("member"); + // Assert.NotNull(xmlMemberNodes); + + // foreach (var type in assembly.GetExportedTypes()) + // { + // Logger.WriteLine(type.FullName); + + // var xmlTypeElement = xmlMemberNodes.FirstOrDefault(e => + // e.Attribute("name")?.Value == $"T:{type.FullName}" + // ); + // var xmlConstructorNodes = xmlMemberNodes + // .Where(e => + // e.Attribute("name")?.Value.StartsWith($"M:{type.FullName}.#ctor") == true + // ) + // .ToArray(); + + // Assert.NotNull(xmlTypeElement); + + // // log the summary of the type + // if (!string.IsNullOrWhiteSpace(xmlTypeElement.Element("summary")?.Value)) + // Logger.WriteLine($"\t{xmlTypeElement.Element("summary")?.Value}"); + + // // log the remarks of the type + // if (!string.IsNullOrWhiteSpace(xmlTypeElement.Element("remarks")?.Value)) + // Logger.WriteLine($"\t{xmlTypeElement.Element("remarks")?.Value}"); + + // // log the example of the type + // if (!string.IsNullOrWhiteSpace(xmlTypeElement.Element("example")?.Value)) + // Logger.WriteLine($"\t{xmlTypeElement.Element("example")?.Value}"); + + // // log the type parameters of the type + // foreach (var param in xmlTypeElement.Elements("typeparam")) + // { + // Logger.WriteLine($"\t{param.Attribute("name")?.Value}: {param.Value}"); + // } + + // // log the constructors of the type + // var constructors = type.GetConstructors(BindingFlags.Public); + // if (constructors.Any()) + // Logger.WriteLine($"\t=== Constructors ========================\n"); + + // if (xmlConstructorNodes.Length == constructors.Length) + // { + // for (int i = 0; i < constructors.Length; i++) + // { + // ConstructorInfo? constructor = constructors[i]; + // var xmlConstructorNode = xmlConstructorNodes[i]; + + // if (xmlConstructorNode.Attribute("name") == null) + // continue; + + // Logger.WriteLine($"\t{xmlConstructorNode.Attribute("name")?.Value}"); + + // if (!string.IsNullOrWhiteSpace(xmlConstructorNode.Element("summary")?.Value)) + // Logger.WriteLine($"\t{xmlConstructorNode.Element("summary")?.Value}"); + + // if (!string.IsNullOrWhiteSpace(xmlConstructorNode.Element("remarks")?.Value)) + // Logger.WriteLine($"\t{xmlConstructorNode.Element("remarks")?.Value}"); + + // if (!string.IsNullOrWhiteSpace(xmlConstructorNode.Element("example")?.Value)) + // Logger.WriteLine($"\t{xmlConstructorNode.Element("example")?.Value}"); + // } + // } + + // // log the fields of the type + // var fields = type.GetFields(BindingFlags.Public); + // if (fields.Any()) + // Logger.WriteLine($"\t=== Fields ========================\n"); + + // foreach (var field in fields) + // { + // Logger.WriteLine($"\t{field.Name}"); + + // // get the xml documentation for the field + // var fieldElement = xml + // .Root.Element("members") + // ?.Elements("member") + // .FirstOrDefault(e => + // e.Attribute("name")?.Value == $"F:{type.FullName}.{field.Name}" + // ); + + // if (fieldElement != null) + // { + // // log the summary of the field + // if (!string.IsNullOrWhiteSpace(fieldElement.Element("summary")?.Value)) + // Logger.WriteLine($"\t\tSummary: {fieldElement.Element("summary")?.Value}"); + + // // log the remarks of the field + // if (!string.IsNullOrWhiteSpace(fieldElement.Element("remarks")?.Value)) + // Logger.WriteLine($"\t\t{fieldElement.Element("remarks")?.Value}"); + + // // log the example of the field + // if (!string.IsNullOrWhiteSpace(fieldElement.Element("example")?.Value)) + // Logger.WriteLine($"\t\t{fieldElement.Element("example")?.Value}"); + // } + // } + + // // log the properties of the type + // var properties = type.GetProperties(BindingFlags.Public); + // if (properties.Any()) + // Logger.WriteLine($"\t=== Properties ========================\n"); + + // foreach (var property in properties) + // { + // Logger.WriteLine($"\t{property.Name}"); + + // // get the xml documentation for the property + // var propertyElement = xml + // .Root.Element("members") + // ?.Elements("member") + // .FirstOrDefault(e => + // e.Attribute("name")?.Value == $"P:{type.FullName}.{property.Name}" + // ); + + // if (propertyElement != null) + // { + // // log the summary of the property + // if (!string.IsNullOrWhiteSpace(propertyElement.Element("summary")?.Value)) + // Logger.WriteLine($"\t\t{propertyElement.Element("summary")?.Value}"); + + // // log the remarks of the property + // if (!string.IsNullOrWhiteSpace(propertyElement.Element("remarks")?.Value)) + // Logger.WriteLine($"\t\t{propertyElement.Element("remarks")?.Value}"); + + // // log the example of the property + // if (!string.IsNullOrWhiteSpace(propertyElement.Element("example")?.Value)) + // Logger.WriteLine($"\t\t{propertyElement.Element("example")?.Value}"); + // } + // } + + // // log the methods of the type + // if (type.GetMethods(BindingFlags.Public).Any()) + // Logger.WriteLine($"\t=== Methods ========================\n"); + + // foreach (var method in type.GetMethods()) + // { + // Logger.WriteLine($"\tMethod: {method.Name}"); + + // // get the xml documentation for the method + // var methodElement = xml + // .Root.Element("members") + // ?.Elements("member") + // .FirstOrDefault(e => + // e.Attribute("name")?.Value == $"M:{type.FullName}.{method.Name}" + // ); + + // if (methodElement != null) + // { + // // log the summary of the method + // if (!string.IsNullOrWhiteSpace(methodElement.Element("summary")?.Value)) + // Logger.WriteLine($"\t\tSummary: {methodElement.Element("summary")?.Value}"); + + // // log the remarks of the method + // if (!string.IsNullOrWhiteSpace(methodElement.Element("remarks")?.Value)) + // Logger.WriteLine($"\t\tRemarks: {methodElement.Element("remarks")?.Value}"); + + // // log the example of the method + // if (!string.IsNullOrWhiteSpace(methodElement.Element("example")?.Value)) + // Logger.WriteLine($"\t\tExample: {methodElement.Element("example")?.Value}"); + + // // log the parameters of the method + // if (methodElement.Elements("param").Any()) + // Logger.WriteLine("\t\tParameters:"); + + // foreach (var param in methodElement.Elements("param")) + // { + // Logger.WriteLine( + // $"\t\tParam: {param.Attribute("name")?.Value}: {param.Value}" + // ); + // } + + // // log the return value of the method + // if (!string.IsNullOrWhiteSpace(methodElement.Element("returns")?.Value)) + // Logger.WriteLine($"\t\tReturns: {methodElement.Element("returns")?.Value}"); + // } + // } + // } + + // Assert.True(true); + } +} + +public class Docs +{ + public string Title { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string Product { get; set; } = string.Empty; + public string Company { get; set; } = string.Empty; + public string Version { get; set; } = string.Empty; + public string Copyright { get; set; } = string.Empty; + public Dictionary Metadata { get; set; } = []; + public List Assemblies { get; set; } = []; +} + +public static class DocsExtensions +{ + public static Docs AddAssembly(this Docs docs, Assembly assembly, XDocument docsXml) + { + var assemblyName = assembly.GetName().Name; + if (string.IsNullOrWhiteSpace(assemblyName)) + return docs; + + if (string.IsNullOrWhiteSpace(docs.Title)) + docs.Title = ( + assembly.GetCustomAttribute()?.Title ?? assemblyName + ).Trim(); + + if (string.IsNullOrEmpty(docs.Description)) + docs.Description = ( + assembly.GetCustomAttribute()?.Description + ?? string.Empty + ).Trim(); + + if (string.IsNullOrEmpty(docs.Product)) + docs.Product = ( + assembly.GetCustomAttribute()?.Product ?? string.Empty + ).Trim(); + + if (string.IsNullOrEmpty(docs.Company)) + docs.Company = ( + assembly.GetCustomAttribute()?.Company ?? string.Empty + ).Trim(); + + if (string.IsNullOrEmpty(docs.Copyright)) + docs.Copyright = ( + assembly.GetCustomAttribute()?.Copyright ?? string.Empty + ).Trim(); + + if (string.IsNullOrEmpty(docs.Version)) + docs.Version = ( + assembly.GetCustomAttribute()?.Version + ?? assembly.GetCustomAttribute()?.Version + ?? assembly.GetName()?.Version?.ToString() + ?? string.Empty + ).Trim(); + + foreach (var m in assembly.GetCustomAttributes()) + { + if (!docs.Metadata.ContainsKey(m.Key) && !string.IsNullOrWhiteSpace(m.Value)) + { + // camelCase the key + var key = m.Key[..1].ToLower() + m.Key[1..]; + docs.Metadata[key] = m.Value; + } + } + + var assemblyDocs = AssemblyDocs.Generate(assembly, docsXml); + docs.Assemblies.Add(assemblyDocs); + + return docs; + } + + public static string InnerXml(this XNode node) + { + using var reader = node.CreateReader(); + reader.MoveToContent(); + return reader.ReadInnerXml(); + + // var sb = new StringBuilder(); + // foreach (var node in node.Nodes()) + // { + // if (node is XText text) + // sb.Append(text.Value); + // else if (node is XElement el) + // { + // sb.Append(el.ToString()); + // // sb.Append(el.Value); + // } + // } + // return sb.ToString().Trim(); + } +} + +public class AssemblyDocs +{ + internal static AssemblyDocs Generate(Assembly assembly, XDocument docsXml) + { + var docsXmlAssemblyName = docsXml.Root?.Element("assembly")?.Element("name")?.Value; + + Assert.Equal(assembly.GetName().Name, docsXmlAssemblyName); + + var docs = new AssemblyDocs + { + Id = $"A:{docsXmlAssemblyName}", + Name = assembly.GetName().Name!, + FullName = assembly.FullName!, + }; + + foreach (var type in assembly.GetExportedTypes()) + { + var typeDocs = TypeDocs.Generate(type, docsXml); + docs.Types.Add(typeDocs); + } + + return docs; + } + + /// + /// Starts with A: + /// + public string Id { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public string FullName { get; set; } = string.Empty; + public List Types { get; set; } = []; +} + +public class TypeDocs +{ + internal static TypeDocs Generate(Type type, XDocument docsXml) + { + var memberNodes = docsXml.Root!.Element("members")?.Elements("member").ToArray() ?? []; + var typeNode = memberNodes.FirstOrDefault(e => + e.Attribute("name")?.Value == $"T:{type.FullName}" + ); + + Assert.NotNull(typeNode); + + var typeDocs = new TypeDocs + { + Id = $"T:{type.FullName}", + Type = new TypeRef(type), + Summary = typeNode.Element("summary")?.InnerXml().Trim(), + Remarks = typeNode.Element("remarks")?.InnerXml().Trim(), + Example = typeNode.Element("example")?.InnerXml().Trim(), + }; + + // only the constructors WITH parameters + var cstrNodes = memberNodes + .Where(e => + e.Attribute("name")?.Value?.StartsWith($"M:{type.FullName}.#ctor") == true + && e.Attribute("name")?.Value?.EndsWith("#ctor") == false + ) + .ToArray(); + var fieldNodes = memberNodes + .Where(e => e.Attribute("name")?.Value?.StartsWith($"F:{type.FullName}.") == true) + .ToArray(); + var propertyNodes = memberNodes + .Where(e => e.Attribute("name")?.Value?.StartsWith($"P:{type.FullName}.") == true) + .ToArray(); + var methodNodes = memberNodes + .Where(e => + e.Attribute("name")?.Value?.StartsWith($"M:{type.FullName}.") == true + && !e.Attribute("name")?.Value?.Contains("#ctor") == true + ) + .ToArray(); + + var bindingFlags = + BindingFlags.Public + | BindingFlags.NonPublic + | BindingFlags.Instance + | BindingFlags.Static; + + // only the constructors WITH parameters + var constructors = type.GetConstructors(bindingFlags) + .Where(c => c.GetParameters().Length > 0) + .ToArray(); + var fields = type.GetFields(bindingFlags) + .Where(m => !m.IsSpecialName && !m.IsPrivate && !(m.IsStatic && m.IsPrivate)) + .ToArray(); + var properties = type.GetProperties(bindingFlags).ToArray(); + var methods = type.GetMethods(bindingFlags) + .Where(m => + !m.IsConstructor + && !m.IsHideBySig + && m.DeclaringType?.Namespace?.StartsWith("MJCZone") == true + && !(m.IsStatic && m.IsPrivate) + ) + .ToArray(); + + if (constructors.Length != cstrNodes.Length) + Assert.Equal(constructors.Length, cstrNodes.Length); + + for (int i = 0; i < constructors.Length; i++) + { + var cstrNode = cstrNodes[i]; + Assert.NotNull(cstrNode); + + var cstrNodeName = cstrNode.Attribute("name")?.Value ?? string.Empty; + Assert.True(cstrNodeName.Length > 3, "Node name is too short."); + + var constructor = constructors[i]; + var constructorDocs = new ConstructorDocs + { + Id = $"C:{cstrNodeName[3..]}", + Summary = cstrNode.Element("summary")?.InnerXml().Trim(), + Remarks = cstrNode.Element("remarks")?.InnerXml().Trim(), + Example = cstrNode.Element("example")?.InnerXml().Trim(), + }; + typeDocs.Constructors.Add(constructorDocs); + } + + foreach (var field in fields) + { + var fieldNode = fieldNodes.FirstOrDefault(e => + e.Attribute("name")?.Value == $"F:{type.FullName}.{field.Name}" + ); + if (fieldNode == null) + continue; + Assert.NotNull(fieldNode); + + var fieldDocs = new FieldDocs + { + Id = $"F:{type.FullName}.{field.Name}", + Name = field.Name, + Inherited = field.DeclaringType != type, + IsReadOnly = field.IsInitOnly, + IsStatic = field.IsStatic, + FieldType = new TypeRef(field.FieldType), + Summary = fieldNode.Element("summary")?.InnerXml().Trim(), + Remarks = fieldNode.Element("remarks")?.InnerXml().Trim(), + Example = fieldNode.Element("example")?.InnerXml().Trim(), + }; + typeDocs.Fields.Add(fieldDocs); + } + + foreach (var property in properties) + { + var propertyNode = propertyNodes.FirstOrDefault(e => + e.Attribute("name")?.Value == $"P:{type.FullName}.{property.Name}" + ); + if (propertyNode == null) + { + propertyNode = propertyNodes.FirstOrDefault(e => + e.Attribute("name")?.Value + == $"P:{property.DeclaringType!.FullName}.{property.Name}" + ); + if (propertyNode == null) + continue; + } + Assert.NotNull(propertyNode); + + var propertyDocs = new PropertyDocs + { + Id = $"P:{type.FullName}.{property.Name}", + Name = property.Name, + Inherited = property.DeclaringType != type, + IsReadOnly = !property.CanWrite, + PropertyType = new TypeRef(property.PropertyType), + Summary = propertyNode.Element("summary")?.InnerXml().Trim(), + Remarks = propertyNode.Element("remarks")?.InnerXml().Trim(), + Example = propertyNode.Element("example")?.InnerXml().Trim(), + }; + typeDocs.Properties.Add(propertyDocs); + } + + foreach (var method in methods) + { + var methodNode = methodNodes.FirstOrDefault(e => + e.Attribute("name")?.Value.StartsWith($"M:{type.FullName}.{method.Name}") == true + ); + if (methodNode == null) + continue; + Assert.NotNull(methodNode); + + var methodDocs = new MethodDocs + { + Id = $"M:{type.FullName}.{method.Name}", + Name = method.Name, + Inherited = method.DeclaringType != type, + IsReadOnly = method.IsSpecialName, + IsStatic = method.IsStatic, + ReturnType = new TypeRef(method.ReturnType), + Summary = methodNode.Element("summary")?.InnerXml().Trim(), + Remarks = methodNode.Element("remarks")?.InnerXml().Trim(), + Example = methodNode.Element("example")?.InnerXml().Trim(), + }; + + foreach (var param in method.GetParameters()) + { + var paramNode = methodNode + .Elements("param") + .FirstOrDefault(e => + e.Attribute("name")?.Value + == $"M:{type.FullName}.{method.Name}({param.ParameterType.Name})" + ); + + var paramDocs = new TypeParamDocs + { + Type = new TypeRef(param.ParameterType), + Name = param.Name!, + Summary = paramNode?.Element("summary")?.InnerXml().Trim(), + Remarks = paramNode?.Element("remarks")?.InnerXml().Trim(), + Example = paramNode?.Element("example")?.InnerXml().Trim(), + }; + methodDocs.TypeParams.Add(paramDocs); + } + + typeDocs.Methods.Add(methodDocs); + } + + return typeDocs; + } + + /// + /// Starts with T: + /// + public string Id { get; set; } = string.Empty; + public TypeRef Type { get; set; } = null!; + public string? Summary { get; set; } = null; + public string? Remarks { get; set; } = null; + public string? Example { get; set; } = null; + public List Constructors { get; set; } = []; + public List Fields { get; set; } = []; + public List Properties { get; set; } = []; + public List Methods { get; set; } = []; +} + +public class ConstructorDocs +{ + /// + /// Starts with C: + /// + public string Id { get; set; } = string.Empty; + public List TypeParams { get; set; } = []; + public string? Summary { get; set; } = null; + public string? Remarks { get; set; } = null; + public string? Example { get; set; } = null; +} + +public class FieldDocs +{ + /// + /// Starts with F: + /// + public string Id { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public bool Inherited { get; set; } = false; + public bool IsReadOnly { get; set; } = false; + public bool IsStatic { get; set; } = false; + public TypeRef FieldType { get; set; } = null!; + public string? Summary { get; set; } = null; + public string? Remarks { get; set; } = null; + public string? Example { get; set; } = null; +} + +public class PropertyDocs +{ + /// + /// Starts with P: + /// + public string Id { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public bool Inherited { get; set; } = false; + public bool IsReadOnly { get; set; } = false; + public TypeRef PropertyType { get; set; } = null!; + public string? Summary { get; set; } = null; + public string? Remarks { get; set; } = null; + public string? Example { get; set; } = null; +} + +public class MethodDocs +{ + /// + /// Starts with M: + /// + public string Id { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public bool Inherited { get; set; } = false; + public bool IsReadOnly { get; set; } = false; + public bool IsStatic { get; set; } = false; + public TypeRef? ReturnType { get; set; } = null; + public string? Summary { get; set; } = null; + public string? Remarks { get; set; } = null; + public string? Example { get; set; } = null; + public List TypeParams { get; set; } = []; +} + +public class TypeParamDocs +{ + public TypeRef? Type { get; set; } + public string Name { get; set; } = string.Empty; + public string? Summary { get; set; } = null; + public string? Remarks { get; set; } = null; + public string? Example { get; set; } = null; +} + +public class TypeRef +{ + public TypeRef() { } + + public TypeRef(Type type) + { + Name = type.Name; + FullName = type.AssemblyQualifiedName!; + DisplayName = type.GetFriendlyName(); + Namespace = type.Namespace!; + Assembly = type.Assembly.FullName!; + } + + public string Assembly { get; set; } = string.Empty; + public string Namespace { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public string FullName { get; set; } = string.Empty; + public string DisplayName { get; set; } = string.Empty; + public List GenericArguments { get; set; } = []; + public TypeRef? BaseType { get; set; } = null; + public List Interfaces { get; set; } = []; +} diff --git a/tests/DapperMatic.Tests/xunit.runner.json b/tests/MJCZone.DapperMatic.Tests/xunit.runner.json similarity index 100% rename from tests/DapperMatic.Tests/xunit.runner.json rename to tests/MJCZone.DapperMatic.Tests/xunit.runner.json