From 0c99682b001345525f26efe8893c3bb051200f94 Mon Sep 17 00:00:00 2001 From: Augusto Mesquita Date: Mon, 23 Jan 2023 23:51:06 -0300 Subject: [PATCH] Initial commit --- .github/workflows/build.yml | 20 + .github/workflows/release.yml | 45 ++ .github/workflows/test.yml | 26 + .gitignore | 561 ++++++++++++++++++ CODEOWNERS | 13 + Dapper.FluentExecution.sln | 36 ++ LICENSE | 21 + README.md | 66 +++ src/fluent-execution/AsyncResult.cs | 25 + .../Dapper.FluentExecution.csproj | 41 ++ src/fluent-execution/ExecutionSqlBuilder.cs | 235 ++++++++ src/fluent-execution/StringExtensions.cs | 12 + .../abstractions/IExecutionBuilder.cs | 51 ++ .../sqlserver/SqlServerExecutionSqlBuilder.cs | 51 ++ .../FluentExecution.Tests.csproj | 30 + .../StringExtensionTests/OnUnitTests.cs | 56 ++ tests/fluent-execution-tests/Usings.cs | 3 + 17 files changed, 1292 insertions(+) create mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 CODEOWNERS create mode 100644 Dapper.FluentExecution.sln create mode 100644 LICENSE create mode 100644 README.md create mode 100644 src/fluent-execution/AsyncResult.cs create mode 100644 src/fluent-execution/Dapper.FluentExecution.csproj create mode 100644 src/fluent-execution/ExecutionSqlBuilder.cs create mode 100644 src/fluent-execution/StringExtensions.cs create mode 100644 src/fluent-execution/abstractions/IExecutionBuilder.cs create mode 100644 src/fluent-execution/sqlserver/SqlServerExecutionSqlBuilder.cs create mode 100644 tests/fluent-execution-tests/FluentExecution.Tests.csproj create mode 100644 tests/fluent-execution-tests/StringExtensionTests/OnUnitTests.cs create mode 100644 tests/fluent-execution-tests/Usings.cs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..fc57791 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,20 @@ +name: Build-CI + +on: + workflow_call: + +jobs: + build: + name: Building application + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Setup .NET Core SDK + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 6.0.x + + - name: Build stage + run: dotnet build --configuration Release diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..7e3a56a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,45 @@ +name: Release-CD + +on: + push: + branches: [ main ] + +env: + NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }} + GITHUB_NUGET_API_KEY: ${{ secrets.GH_TOKEN }} + NUGET_API_URL: ${{ vars.NUGET_API_URL }} + GITHUB_NUGET_API_URL: ${{ vars.GH_NUGET_API_URL }} + PROJECT_FILE_PATH: 'src/fluent-execution/Dapper.FluentExecution.csproj' + +jobs: + build: + name: Build stage + uses: ./.github/workflows/build.yml + + test: + name: Test stage + needs: [ build ] + uses: ./.github/workflows/test.yml + + Publish: + name: Publishing application + needs: [ build, test ] + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Setup .NET Core SDK + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 6.0.x + + - name: Creating project package + run: dotnet pack $PROJECT_FILE_PATH --configuration Release -o nupkg + + - name: Publishing package on Nuget V3 + run: dotnet nuget push ./nupkg/*.nupkg --source $NUGET_API_URL --skip-duplicate --api-key $NUGET_API_KEY + + + - name: Publishing package on Github Nuget + run: dotnet nuget push ./nupkg/*.nupkg --source $GITHUB_NUGET_API_URL --skip-duplicate --api-key $GITHUB_NUGET_API_KEY diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..ce50887 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,26 @@ +name: Test-CI + +on: + workflow_call: + +jobs: + build: + name: Testing application + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Setup .NET Core SDK + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 6.0.x + + - name: Build stage + run: dotnet build --configuration Release + + - name: Test stage + run: dotnet test --no-build --verbosity normal --configuration Release /p:CollectCoverage=true /p:CoverletOutputFormat=opencover + + - name: Test code coverage + uses: codecov/codecov-action@v1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f5e290c --- /dev/null +++ b/.gitignore @@ -0,0 +1,561 @@ +# Created by https://www.toptal.com/developers/gitignore/api/visualstudio,visualstudiocode,aspnetcore,dotnetcore,database +# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio,visualstudiocode,aspnetcore,dotnetcore,database + +### ASPNETCore ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/ + +### Database ### +*.accdb +*.db +*.dbf +*.mdb +*.sqlite3 +*.db-shm +*.db-wal + +### DotnetCore ### +# .NET Core build folders +bin/ +obj/ + +# Common node modules locations +/node_modules +/wwwroot/node_modules + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### VisualStudio ### +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser + +# User-specific files (MonoDevelop/Xamarin Studio) + +# Mono auto generated files +mono_crash.* + +# Build results +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +# Uncomment if you have tasks that create the project's static files in wwwroot + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results + +# NUnit +nunit-*.xml + +# Build Results of an ATL Project + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_h.h +*.iobj +*.ipdb +*_wpftmp.csproj +*.tlog + +# Chutzpah Test files + +# Visual C++ cache files + +# Visual Studio profiler + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace + +# Guidance Automation Toolkit + +# ReSharper is a .NET coding add-in + +# TeamCity is a build add-in + +# DotCover is a Code Coverage Tool + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results + +# NCrunch + +# MightyMoose + +# Web workbench (sass) + +# Installshield output folder + +# DocProject is a documentation generator add-in + +# Click-Once directory + +# Publish Web Output +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted + +# NuGet Packages +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files + +# Microsoft Azure Build Output + +# Microsoft Azure Emulator + +# Windows Store app package directories and files +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) + +# RIA/Silverlight projects + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.ndf + +# Business Intelligence projects +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes + +# GhostDoc plugin setting file + +# Node.js Tools for Visual Studio + +# Visual Studio 6 build log + +# Visual Studio 6 workspace options file + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output + +# Paket dependency manager + +# FAKE - F# Make + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +*.code-workspace + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/visualstudio,visualstudiocode,aspnetcore,dotnetcore,database + diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..4bdeb4d --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,13 @@ +# Lines starting with '#' are comments. +# Each line is a file pattern followed by one or more owners. + +# These owners will be the default owners for everything in the repo. +* @AugustoDeveloper + +# Order is important. The last matching pattern has the most precedence. +# So if a pull request only touches csharp files, only these owners +# will be requested to review. +# *.cs @AugustoDeveloper + +# You can also use email addresses if you prefer. +# docs/* developer.augustocesar@gmail.com diff --git a/Dapper.FluentExecution.sln b/Dapper.FluentExecution.sln new file mode 100644 index 0000000..0931f90 --- /dev/null +++ b/Dapper.FluentExecution.sln @@ -0,0 +1,36 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5138B612-55A2-4A24-BEBF-E7E9FFD0527E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dapper.FluentExecution", "src\fluent-execution\Dapper.FluentExecution.csproj", "{89B4FD3F-5D8E-4939-AAEB-E212CEB69412}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{A3A9E037-8405-42C6-856D-8A6B9E476E03}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluentExecution.Tests", "tests\fluent-execution-tests\FluentExecution.Tests.csproj", "{4E4AC6E0-8CF9-4656-88B4-8533079EE28F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {89B4FD3F-5D8E-4939-AAEB-E212CEB69412}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {89B4FD3F-5D8E-4939-AAEB-E212CEB69412}.Debug|Any CPU.Build.0 = Debug|Any CPU + {89B4FD3F-5D8E-4939-AAEB-E212CEB69412}.Release|Any CPU.ActiveCfg = Release|Any CPU + {89B4FD3F-5D8E-4939-AAEB-E212CEB69412}.Release|Any CPU.Build.0 = Release|Any CPU + {4E4AC6E0-8CF9-4656-88B4-8533079EE28F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4E4AC6E0-8CF9-4656-88B4-8533079EE28F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4E4AC6E0-8CF9-4656-88B4-8533079EE28F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4E4AC6E0-8CF9-4656-88B4-8533079EE28F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {89B4FD3F-5D8E-4939-AAEB-E212CEB69412} = {5138B612-55A2-4A24-BEBF-E7E9FFD0527E} + {4E4AC6E0-8CF9-4656-88B4-8533079EE28F} = {A3A9E037-8405-42C6-856D-8A6B9E476E03} + EndGlobalSection +EndGlobal diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c21af7e --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Augusto Mesquita + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5d40e52 --- /dev/null +++ b/README.md @@ -0,0 +1,66 @@ +# Dapper - Fluent Execution +![dapper-fluent-execution](https://github.com/AugustoDeveloper/dapper-fluent-execution/actions/workflows/release.yml/badge.svg) [![NuGet](https://img.shields.io/nuget/v/Dapper.FluentExecution.svg)](https://nuget.org/packages/Dapper.FluentExecution) [![Nuget](https://img.shields.io/nuget/dt/Dapper.FluentExecution.svg)](https://nuget.org/packages/Dapper.FluentExecution) + +This package is a simple, easy and fluent way to execute SQL on database connection by Dapper. + +## Installation +You can install the package using one of the options bellow: + - Package Manager +``` +PM> NuGet\Install-Package Dapper.FluentExecution -Version 0.1.1 +``` + + - .NET CLI +``` +dotnet add package Dapper.FluentExecution --version 0.1.1 +``` + + - PackageReference +``` + +``` + +## Usage + +Simple query: +```csharp +public async Task> GetAllAsync(CancellationToken cancellation = default) + => await "SELECT * FROM Persons" + .On(DatabaseConnection) + .QueryAsync(cancellation) + .ToListAsync(); +``` +Querying with parameter: +```csharp +public async Task GetByIdAsync(int id, CancellationToken cancellation = default) + => await "SELECT * FROM Persons where Id = @Id" + .On(DatabaseConnection) + .WithParameter("@Id", id) + .QuerySingleOrDefaultAsync(cancellation); +``` + +Querying with conditional parameter and append: +```csharp +public async Task GetByIdAsync(int id, int? specificAddressId, CancellationToken cancellation = default) + => await "SELECT p.* FROM Persons p inner join Addresses a on a.PersonId = p.Id where Id = @Id" + .On(DatabaseConnection) + .AppendSql(specificAddressId.HasValue, "AND a.Id = @AddressId") + .WithParameter(specificAddressId.HasValue, "@AddressId", specificAddressId) + .WithParameter("@Id", id) + .QuerySingleOrDefaultAsync(cancellation); +``` +## TODO - v0.2.0 +- [ ] Add unit tests for `IExecutionBuilder` methods +- [ ] Add summary doc on all .cs files +- [ ] Add suport to `Execution` methods on `IExecutionBuilder`. E.g.: `Execute, ExecuteAsync, ExecuteScalar, ExecuteScalarAsync...`. +- [ ] Add support to dynamic parameter by dynamic object. E.g.: `new { Param1 = "1", Param2 = 2 }` +- [ ] Add support to set command timeout +- [ ] Add support to set query as an execution of stored procedure +- [ ] Add `QueryAsync, Query,...` an `IEnumerable` result + +## Release - v0.1.1 +- Fixing `csproj` documentation to Nuget.org + +## Release - v0.1.0 +- Methods to query directly from a string by fluent builder +- Adding support to add `SqlDbType` parameters diff --git a/src/fluent-execution/AsyncResult.cs b/src/fluent-execution/AsyncResult.cs new file mode 100644 index 0000000..7995684 --- /dev/null +++ b/src/fluent-execution/AsyncResult.cs @@ -0,0 +1,25 @@ +namespace Dapper.FluentExecution; + +public struct AsyncResult +{ + private readonly Task> taskResult; + + internal AsyncResult(Task> result) + { + this.taskResult = result; + } + + public async Task> ToListAsync() + { + var newResult = await taskResult; + + return newResult.ToList(); + } + + public async Task ToArrayAsync() + { + var newResult = await taskResult; + + return newResult.ToArray(); + } +} diff --git a/src/fluent-execution/Dapper.FluentExecution.csproj b/src/fluent-execution/Dapper.FluentExecution.csproj new file mode 100644 index 0000000..f6b0285 --- /dev/null +++ b/src/fluent-execution/Dapper.FluentExecution.csproj @@ -0,0 +1,41 @@ + + + + netstandard2.0;netstandard2.1;net6.0 + enable + enable + Dapper.FluentExecution + Dapper.FluentExecution + latest + true + + + + Augusto Mesquita + Aucamana + augustodeveloper + 0.1.1 + Dapper.FluentExecution + Dapper;Dapper.Fluent;Dapper.Query;Execution;Dapper.Execution + MIT + Dapper.FluentExecution + A lite library to make easy execution SQL on database connection by Dapper + true + https://github.com/AugustoDeveloper/dapper-fluent-execution + git + main + Copyright © 2023 + + + + + <_Parameter1>FluentExecution.Tests + + + + + + + + + diff --git a/src/fluent-execution/ExecutionSqlBuilder.cs b/src/fluent-execution/ExecutionSqlBuilder.cs new file mode 100644 index 0000000..447dccb --- /dev/null +++ b/src/fluent-execution/ExecutionSqlBuilder.cs @@ -0,0 +1,235 @@ +using System.Data; +using System.Text; +using Dapper.FluentExecution.Abstractions; + +namespace Dapper.FluentExecution; + +internal class ExecutionSqlBuilder : IExecutionBuilder +{ + private readonly IDbConnection connection; + private readonly StringBuilder sqlBuilder; + private DynamicParameters? parameters; + private IDbTransaction? transaction; + + private DynamicParameters Parameters => GetParameters(); + + protected ExecutionSqlBuilder(string rootSql, IDbConnection connection) + { + this.connection = connection; + this.sqlBuilder = new(rootSql); + } + + internal static IExecutionBuilder New(string? sql, IDbConnection? connection) + { + if (string.IsNullOrWhiteSpace(sql)) + { + throw new ArgumentException("Invalid SQL script", nameof(sql)); + } + +#if NETSTANDARD2_0 + _ = connection ?? throw new ArgumentNullException(nameof(connection)); +#elif NETSTANDARD2_1 + _ = connection ?? throw new ArgumentNullException(nameof(connection)); +#else + ArgumentNullException.ThrowIfNull(connection); +#endif + + return new ExecutionSqlBuilder(sql!, connection!); + } + + private DynamicParameters GetParameters() + { + if (parameters is null) + { + parameters = new(); + } + + return parameters; + } + + private CommandDefinition BuildCommandDefinition(CancellationToken cancellation = default) + => new CommandDefinition(sqlBuilder.ToString(), parameters, transaction: transaction, cancellationToken: cancellation); + + IExecutionBuilder IExecutionBuilder.WithTransaction(IDbTransaction transaction) + { + this.transaction = transaction; + + return this; + } + + IExecutionBuilder IExecutionBuilder.AppendSql(bool condition, string sql) + { + if (condition) + { + sqlBuilder.Append(sql); + } + + return this; + } + + IExecutionBuilder IExecutionBuilder.WithParameter(string parameterName, DbType dbType, object value, int size) + { + Parameters.Add(parameterName, value, dbType, size: size); + + return this; + } + + IExecutionBuilder IExecutionBuilder.WithParameter(bool condition, string parameterName, DbType dbType, object value, int size) + { + if (condition) + { + Parameters.Add(parameterName, value, dbType, size: size); + } + + return this; + } + + IExecutionBuilder IExecutionBuilder.WithParameter(string parameterName, DbType dbType, object value) + { + Parameters.Add(parameterName, value, dbType); + + return this; + + } + + IExecutionBuilder IExecutionBuilder.WithParameter(bool condition, string parameterName, DbType dbType, object value) + { + if (condition) + { + Parameters.Add(parameterName, value, dbType); + } + + return this; + } + + IExecutionBuilder IExecutionBuilder.WithParameter(bool condition, string parameterName, object value) + { + if (condition) + { + Parameters.Add(parameterName, value); + } + return this; + } + + IExecutionBuilder IExecutionBuilder.WithParameter(string parameterName, object value) + { + Parameters.Add(parameterName, value); + + return this; + } + + IEnumerable IExecutionBuilder.Query() => this.connection.Query(BuildCommandDefinition()); + + IEnumerable IExecutionBuilder.Query() => this.connection.Query(BuildCommandDefinition()); + + dynamic IExecutionBuilder.QueryFirst() => this.connection.QueryFirst(BuildCommandDefinition()); + + T IExecutionBuilder.QueryFirst() => this.connection.QueryFirst(BuildCommandDefinition()); + + dynamic IExecutionBuilder.QuerySingle() => this.connection.QuerySingle(BuildCommandDefinition()); + + T IExecutionBuilder.QuerySingle() => this.connection.QuerySingle(BuildCommandDefinition()); + + dynamic? IExecutionBuilder.QueryFirstOrDefault() => this.connection.QueryFirst(BuildCommandDefinition()); + + public T? QueryFirstOrDefault() => this.connection.QueryFirstOrDefault(BuildCommandDefinition()); + + dynamic? IExecutionBuilder.QuerySingleOrDefault() => this.connection.QueryFirst(BuildCommandDefinition()); + + public T? QuerySingleOrDefault() => this.connection.QueryFirstOrDefault(BuildCommandDefinition()); + + T IExecutionBuilder.QueryMultiple(Func func) + { + using var gridreader = this.connection.QueryMultiple(BuildCommandDefinition()); + return func(gridreader); + } + + AsyncResult IExecutionBuilder.QueryAsync(CancellationToken cancellation) + { + var result = this.connection.QueryAsync(BuildCommandDefinition(cancellation)); + + return new(result); + } + + AsyncResult IExecutionBuilder.QueryAsync(CancellationToken cancellation) + { + var result = this.connection.QueryAsync(BuildCommandDefinition(cancellation)); + + return new(result); + } + + async Task IExecutionBuilder.QuerySingleAsync(CancellationToken cancellation) + { + return await this.connection.QuerySingleAsync(BuildCommandDefinition(cancellation)); + } + + async Task IExecutionBuilder.QuerySingleAsync(CancellationToken cancellation) + { + return await this.connection.QuerySingleAsync(BuildCommandDefinition(cancellation)); + } + + async Task IExecutionBuilder.QuerySingleOrDefaultAsync(CancellationToken cancellation) + { + var result = await this.connection.QuerySingleOrDefaultAsync(BuildCommandDefinition(cancellation)); + + if (result is not null) + { + return result; + } + + return default; + } + + public async Task QuerySingleOrDefaultAsync(CancellationToken cancellation) + { + var result = await this.connection.QuerySingleOrDefaultAsync(BuildCommandDefinition(cancellation)); + + if (result is not null) + { + return result; + } + + return default; + + } + + async Task IExecutionBuilder.QueryFirstAsync(CancellationToken cancellation) + { + return await this.connection.QueryFirstAsync(BuildCommandDefinition(cancellation)); + } + + async Task IExecutionBuilder.QueryFirstAsync(CancellationToken cancellation) + { + return await this.connection.QueryFirstAsync(BuildCommandDefinition(cancellation)); + } + + async Task IExecutionBuilder.QueryFirstOrDefaultAsync(CancellationToken cancellation) + { + var result = await this.connection.QueryFirstOrDefaultAsync(BuildCommandDefinition(cancellation)); + + if (result is not null) + { + return result; + } + + return default; + } + + public async Task QueryFirstOrDefaultAsync(CancellationToken cancellation) + { + var result = await this.connection.QueryFirstOrDefaultAsync(BuildCommandDefinition(cancellation)); + + if (result is not null) + { + return result; + } + + return default; + } + + async Task IExecutionBuilder.QueryMultipleAsync(Func> funcTask, CancellationToken cancellation) + { + using var gridReader = await this.connection.QueryMultipleAsync(BuildCommandDefinition(cancellation)); + return await funcTask(gridReader); + } +} diff --git a/src/fluent-execution/StringExtensions.cs b/src/fluent-execution/StringExtensions.cs new file mode 100644 index 0000000..5cdce64 --- /dev/null +++ b/src/fluent-execution/StringExtensions.cs @@ -0,0 +1,12 @@ +using System.Data; +using Dapper.FluentExecution.Abstractions; + +namespace Dapper.FluentExecution; + +public static class StringExtensions +{ + public static IExecutionBuilder On(this string? sql, IDbConnection? connection) + { + return ExecutionSqlBuilder.New(sql, connection); + } +} diff --git a/src/fluent-execution/abstractions/IExecutionBuilder.cs b/src/fluent-execution/abstractions/IExecutionBuilder.cs new file mode 100644 index 0000000..d69f5ba --- /dev/null +++ b/src/fluent-execution/abstractions/IExecutionBuilder.cs @@ -0,0 +1,51 @@ +using System.Data; + +namespace Dapper.FluentExecution.Abstractions; + +/// +/// +public interface IExecutionBuilder +{ + IExecutionBuilder AppendSql(bool condition, string sql); + IExecutionBuilder WithTransaction(IDbTransaction transaction); + + IExecutionBuilder WithParameter(string parameterName, DbType dbType, object value, int size); + IExecutionBuilder WithParameter(bool condition, string parameterName, DbType dbType, object value, int size); + IExecutionBuilder WithParameter(string parameterName, DbType dbType, object value); + IExecutionBuilder WithParameter(bool condition, string parameterName, DbType dbType, object value); + IExecutionBuilder WithParameter(string parameterName, object value); + IExecutionBuilder WithParameter(bool condition, string parameterName, object value); + + IEnumerable Query(); + IEnumerable Query(); + + AsyncResult QueryAsync(CancellationToken cancellation = default); + AsyncResult QueryAsync(CancellationToken cancellation = default); + + dynamic QuerySingle(); + T QuerySingle(); + + Task QuerySingleAsync(CancellationToken cancellation = default); + Task QuerySingleAsync(CancellationToken cancellation = default); + + dynamic? QuerySingleOrDefault(); + T? QuerySingleOrDefault(); + + Task QuerySingleOrDefaultAsync(CancellationToken cancellation = default); + Task QuerySingleOrDefaultAsync(CancellationToken cancellation = default); + + dynamic QueryFirst(); + T QueryFirst(); + + Task QueryFirstAsync(CancellationToken cancellation = default); + Task QueryFirstAsync(CancellationToken cancellation = default); + + dynamic? QueryFirstOrDefault(); + T? QueryFirstOrDefault(); + + Task QueryFirstOrDefaultAsync(CancellationToken cancellation = default); + Task QueryFirstOrDefaultAsync(CancellationToken cancellation = default); + + T QueryMultiple(Func func); + Task QueryMultipleAsync(Func> funcTask, CancellationToken cancellation = default); +} diff --git a/src/fluent-execution/sqlserver/SqlServerExecutionSqlBuilder.cs b/src/fluent-execution/sqlserver/SqlServerExecutionSqlBuilder.cs new file mode 100644 index 0000000..417b025 --- /dev/null +++ b/src/fluent-execution/sqlserver/SqlServerExecutionSqlBuilder.cs @@ -0,0 +1,51 @@ +using System.Data; +using Dapper.FluentExecution.Abstractions; +using Microsoft.Data.SqlClient; +using Microsoft.Data.SqlClient.Server; + +namespace Dapper.FluentExecution.SqlServer; + +public static class SqlServerExecutionSqlBuilderExtension +{ + /// https://github.com/dotnet/SqlClient/blob/0156df230c4426be535ad6af32ac7d16188377d1/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlEnums.cs#L239 + public static DbType ToDbType(this SqlDbType dbType) + => dbType switch + { + SqlDbType.VarChar => DbType.AnsiString, + SqlDbType.Char => DbType.AnsiStringFixedLength, + SqlDbType.VarBinary => DbType.Binary, + SqlDbType.TinyInt => DbType.Byte, + SqlDbType.Bit => DbType.Boolean, + SqlDbType.Money => DbType.Currency, + SqlDbType.Date => DbType.Date, + SqlDbType.DateTime => DbType.DateTime, + SqlDbType.Decimal => DbType.Decimal, + SqlDbType.Float => DbType.Double, + SqlDbType.UniqueIdentifier => DbType.Guid, + SqlDbType.SmallInt => DbType.Int16, + SqlDbType.Int => DbType.Int32, + SqlDbType.BigInt => DbType.Int64, + SqlDbType.Variant => DbType.Object, + SqlDbType.Real => DbType.Single, + SqlDbType.NVarChar => DbType.String, + SqlDbType.NChar => DbType.StringFixedLength, + SqlDbType.Time => DbType.Time, + SqlDbType.Xml => DbType.Xml, + SqlDbType.DateTime2 => DbType.DateTime2, + SqlDbType.DateTimeOffset => DbType.DateTimeOffset, + + _ => throw new NotSupportedException($"{dbType} is not supported") + }; + + public static IExecutionBuilder WithSqlParameter(this IExecutionBuilder builder, bool condition, string parameterName, SqlDbType dbType, object value) + => builder.WithParameter(condition, $"@{parameterName}", dbType.ToDbType(), value); + + public static IExecutionBuilder WithSqlParameter(this IExecutionBuilder builder, bool condition, string parameterName, SqlDbType dbType, object value, int size) + => builder.WithParameter(condition, $"@{parameterName}", dbType.ToDbType(), value, size); + + public static IExecutionBuilder WithSqlParameter(this IExecutionBuilder builder, string parameterName, SqlDbType dbType, object value) + => builder.WithParameter($"@{parameterName}", dbType.ToDbType(), value); + + public static IExecutionBuilder WithSqlParameter(this IExecutionBuilder builder, string parameterName, SqlDbType dbType, object value, int size) + => builder.WithParameter($"@{parameterName}", dbType.ToDbType(), value, size); +} diff --git a/tests/fluent-execution-tests/FluentExecution.Tests.csproj b/tests/fluent-execution-tests/FluentExecution.Tests.csproj new file mode 100644 index 0000000..08faf95 --- /dev/null +++ b/tests/fluent-execution-tests/FluentExecution.Tests.csproj @@ -0,0 +1,30 @@ + + + + net7.0 + enable + enable + Dapper.FluentExection.Tests + false + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/tests/fluent-execution-tests/StringExtensionTests/OnUnitTests.cs b/tests/fluent-execution-tests/StringExtensionTests/OnUnitTests.cs new file mode 100644 index 0000000..9b2f3f5 --- /dev/null +++ b/tests/fluent-execution-tests/StringExtensionTests/OnUnitTests.cs @@ -0,0 +1,56 @@ +using System.Data; + +namespace Dapper.FluentExecution.Tests.StringExtesionsTests; + +public class OnUniTests +{ + private readonly Mock mockConnection; + public IDbConnection Connection => mockConnection.Object; + + public OnUniTests() + { + mockConnection = new(MockBehavior.Strict); + } + + private delegate void RequestDelegate(); + + [Fact] + public void When_Pass_Valid_Connection_Should_Returns_New_Instance() + { + //arrange + string? sql = "SELECT * FROM Persons"; + + //act | assert + sql + .On(Connection).Should().NotBeNull(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void When_Pass_Invalid_Sql_Should_Thrown_ArgumentNullException(string sql) + { + //arrange + //act | assert + FluentActions + .Invoking(() => sql.On(Connection)) + .Should() + .ThrowExactly() + .WithParameterName(nameof(sql)); + } + + [Fact] + public void When_Pass_Null_Connection_Should_Thrown_ArgumentNullException() + { + //arrange + string? sql = "SELECT * FROM Persons"; + + //act | assert + FluentActions + .Invoking(() => sql.On(null)) + .Should() + .ThrowExactly() + .WithParameterName("connection"); + } +} diff --git a/tests/fluent-execution-tests/Usings.cs b/tests/fluent-execution-tests/Usings.cs new file mode 100644 index 0000000..22b43eb --- /dev/null +++ b/tests/fluent-execution-tests/Usings.cs @@ -0,0 +1,3 @@ +global using FluentAssertions; +global using Moq; +global using Xunit;