├── .gitattributes ├── .github ├── dependabot.yml └── workflows │ └── dotnetcore.yml ├── .gitignore ├── LICENSE ├── README.md ├── SqlInMemory.sln ├── src ├── SqlHelper.cs ├── SqlInMemory.csproj ├── SqlInMemory.png └── SqlInMemoryDb.cs └── test ├── SqlInMemory.Tests.csproj └── SqlInMemoryDbTests.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: nuget 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "01:30" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.github/workflows/dotnetcore.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | 3 | on: 4 | push: 5 | paths-ignore: 6 | - 'README.md' 7 | pull_request: 8 | paths-ignore: 9 | - 'README.md' 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v2.4.0 17 | 18 | - name: Setup .NET Core SDK 19 | uses: actions/setup-dotnet@v1.9.0 20 | with: 21 | dotnet-version: '6.0.x' 22 | 23 | - name: Install Dependencies 24 | run: dotnet restore 25 | 26 | - name: Build (Release) 27 | run: dotnet build --configuration Release --no-restore 28 | 29 | # - name: Test (Release) 30 | # run: dotnet test --configuration Release --no-build --no-restore 31 | 32 | - name: Pack (Release) 33 | run: dotnet pack --configuration Release --output ./nuget --no-build --no-restore 34 | 35 | - name: Publish 36 | if: github.event_name == 'push' 37 | run: | 38 | if [[ ${{github.ref}} =~ ^refs/tags/[0-9]+\.[0-9]+\.[0-9]+$ ]] 39 | then 40 | dotnet nuget push ./nuget/*.nupkg -s nuget.org -k ${{secrets.NUGET_TOKEN}} --skip-duplicate 41 | else 42 | echo "publish is only enabled by tagging with a release tag" 43 | fi 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | nuget/ 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # DNX 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | 50 | *_i.c 51 | *_p.c 52 | *_i.h 53 | *.ilk 54 | *.meta 55 | *.obj 56 | *.pch 57 | *.pdb 58 | *.pgc 59 | *.pgd 60 | *.rsp 61 | *.sbr 62 | *.tlb 63 | *.tli 64 | *.tlh 65 | *.tmp 66 | *.tmp_proj 67 | *.log 68 | *.vspscc 69 | *.vssscc 70 | .builds 71 | *.pidb 72 | *.svclog 73 | *.scc 74 | 75 | # Chutzpah Test files 76 | _Chutzpah* 77 | 78 | # Visual C++ cache files 79 | ipch/ 80 | *.aps 81 | *.ncb 82 | *.opendb 83 | *.opensdf 84 | *.sdf 85 | *.cachefile 86 | *.VC.db 87 | *.VC.VC.opendb 88 | 89 | # Visual Studio profiler 90 | *.psess 91 | *.vsp 92 | *.vspx 93 | *.sap 94 | 95 | # TFS 2012 Local Workspace 96 | $tf/ 97 | 98 | # Guidance Automation Toolkit 99 | *.gpState 100 | 101 | # ReSharper is a .NET coding add-in 102 | _ReSharper*/ 103 | *.[Rr]e[Ss]harper 104 | *.DotSettings.user 105 | 106 | # JustCode is a .NET coding add-in 107 | .JustCode 108 | 109 | # TeamCity is a build add-in 110 | _TeamCity* 111 | 112 | # DotCover is a Code Coverage Tool 113 | *.dotCover 114 | 115 | # NCrunch 116 | _NCrunch_* 117 | .*crunch*.local.xml 118 | nCrunchTemp_* 119 | 120 | # MightyMoose 121 | *.mm.* 122 | AutoTest.Net/ 123 | 124 | # Web workbench (sass) 125 | .sass-cache/ 126 | 127 | # Installshield output folder 128 | [Ee]xpress/ 129 | 130 | # DocProject is a documentation generator add-in 131 | DocProject/buildhelp/ 132 | DocProject/Help/*.HxT 133 | DocProject/Help/*.HxC 134 | DocProject/Help/*.hhc 135 | DocProject/Help/*.hhk 136 | DocProject/Help/*.hhp 137 | DocProject/Help/Html2 138 | DocProject/Help/html 139 | 140 | # Click-Once directory 141 | publish/ 142 | 143 | # Publish Web Output 144 | *.[Pp]ublish.xml 145 | *.azurePubxml 146 | # TODO: Comment the next line if you want to checkin your web deploy settings 147 | # but database connection strings (with potential passwords) will be unencrypted 148 | #*.pubxml 149 | *.publishproj 150 | 151 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 152 | # checkin your Azure Web App publish settings, but sensitive information contained 153 | # in these scripts will be unencrypted 154 | PublishScripts/ 155 | 156 | # NuGet Packages 157 | *.nupkg 158 | # The packages folder can be ignored because of Package Restore 159 | **/packages/* 160 | # except build/, which is used as an MSBuild target. 161 | !**/packages/build/ 162 | # Uncomment if necessary however generally it will be regenerated when needed 163 | #!**/packages/repositories.config 164 | # NuGet v3's project.json files produces more ignoreable files 165 | *.nuget.props 166 | *.nuget.targets 167 | 168 | # Microsoft Azure Build Output 169 | csx/ 170 | *.build.csdef 171 | 172 | # Microsoft Azure Emulator 173 | ecf/ 174 | rcf/ 175 | 176 | # Windows Store app package directories and files 177 | AppPackages/ 178 | BundleArtifacts/ 179 | Package.StoreAssociation.xml 180 | _pkginfo.txt 181 | 182 | # Visual Studio cache files 183 | # files ending in .cache can be ignored 184 | *.[Cc]ache 185 | # but keep track of directories ending in .cache 186 | !*.[Cc]ache/ 187 | 188 | # Others 189 | ClientBin/ 190 | ~$* 191 | *~ 192 | *.dbmdl 193 | *.dbproj.schemaview 194 | *.jfm 195 | *.pfx 196 | *.publishsettings 197 | node_modules/ 198 | orleans.codegen.cs 199 | 200 | # Since there are multiple workflows, uncomment next line to ignore bower_components 201 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 202 | #bower_components/ 203 | 204 | # RIA/Silverlight projects 205 | Generated_Code/ 206 | 207 | # Backup & report files from converting an old project file 208 | # to a newer Visual Studio version. Backup files are not needed, 209 | # because we have git ;-) 210 | _UpgradeReport_Files/ 211 | Backup*/ 212 | UpgradeLog*.XML 213 | UpgradeLog*.htm 214 | 215 | # SQL Server files 216 | *.mdf 217 | *.ldf 218 | 219 | # Business Intelligence projects 220 | *.rdl.data 221 | *.bim.layout 222 | *.bim_*.settings 223 | 224 | # Microsoft Fakes 225 | FakesAssemblies/ 226 | 227 | # GhostDoc plugin setting file 228 | *.GhostDoc.xml 229 | 230 | # Node.js Tools for Visual Studio 231 | .ntvs_analysis.dat 232 | 233 | # Visual Studio 6 build log 234 | *.plg 235 | 236 | # Visual Studio 6 workspace options file 237 | *.opt 238 | 239 | # Visual Studio LightSwitch build output 240 | **/*.HTMLClient/GeneratedArtifacts 241 | **/*.DesktopClient/GeneratedArtifacts 242 | **/*.DesktopClient/ModelManifest.xml 243 | **/*.Server/GeneratedArtifacts 244 | **/*.Server/ModelManifest.xml 245 | _Pvt_Extensions 246 | 247 | # Paket dependency manager 248 | .paket/paket.exe 249 | paket-files/ 250 | 251 | # FAKE - F# Make 252 | .fake/ 253 | 254 | # JetBrains Rider 255 | .idea/ 256 | *.sln.iml 257 | 258 | # CodeRush 259 | .cr/ 260 | 261 | # Python Tools for Visual Studio (PTVS) 262 | __pycache__/ 263 | *.pyc -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Mohammad Javad Ebrahimi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![NuGet](https://img.shields.io/nuget/v/SqlInMemory.svg)](https://www.nuget.org/packages/SqlInMemory/) 2 | [![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) 3 | [![Build Status](https://github.com/mjebrahimi/SqlInMemory/workflows/.NET%20Core/badge.svg)](https://github.com/mjebrahimi/SqlInMemory) 4 | 5 | 6 | # SqlInMemory 7 | 8 | **SqlInMemory** is a library for creating SqlServer database on **Memory** instead of hard disk, at last **Drops and Disposes** database when you're done with it. This is useful for **Integration Testing**. 9 | 10 | **Note : This library uses [RamDisk](https://github.com/mjebrahimi/RamDisk) which also uses [ImDisk](http://www.ltr-data.se/opencode.html/#ImDisk) in the backend for creating virtual disk drive. Therefore you have to install imdisk first. ([Download link of current stable version 2.0.10](http://www.ltr-data.se/files/imdiskinst.exe))** 11 | 12 | ## Get Started 13 | 14 | ### 1. Install Package 15 | 16 | ``` 17 | PM> Install-Package SqlInMemory 18 | ``` 19 | 20 | ### 2. Use it 21 | 22 | Pass your connection string and it will create (mount) a virtual disk drive 'Z' and create database there finaly when disposed, drop database and unmount drive. 23 | 24 | ```csharp 25 | var connectionString = "Data Source=.;Initial Catalog=TestDb;Integrated Security=true"; 26 | using (SqlInMemoryDb.Create(connectionString)) 27 | { 28 | //Use database using ADO.NET or ORM 29 | 30 | //For example using EF Core 31 | services.AddDbContext(opt => opt.UseSqlServer(connectionString)); 32 | var serviceProvider = services.BuildServiceProvider(); 33 | var appDbContext = serviceProvider.GetService(); 34 | appDbContext.Database.Migrate(); 35 | //... 36 | } 37 | ``` 38 | 39 | ## Contributing 40 | 41 | Create an [issue](https://github.com/mjebrahimi/SqlInMemory/issues/new) if you find a BUG or have a Suggestion or Question. If you want to develop this project, Fork on GitHub and Develop it and send Pull Request. 42 | 43 | A **HUGE THANKS** for your help. 44 | 45 | ## License 46 | 47 | SqlInMemory is Copyright © 2020 [Mohammd Javad Ebrahimi](https://github.com/mjebrahimi) under the [MIT License](https://github.com/mjebrahimi/SqlInMemory/LICENSE). 48 | -------------------------------------------------------------------------------- /SqlInMemory.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29728.190 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqlInMemory", "src\SqlInMemory.csproj", "{D75C2A6B-8B9D-4F84-83CB-B338089209A0}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqlInMemory.Tests", "test\SqlInMemory.Tests.csproj", "{7453BA0C-7D89-4154-9CA0-54F66B22104B}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {D75C2A6B-8B9D-4F84-83CB-B338089209A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {D75C2A6B-8B9D-4F84-83CB-B338089209A0}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {D75C2A6B-8B9D-4F84-83CB-B338089209A0}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {D75C2A6B-8B9D-4F84-83CB-B338089209A0}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {7453BA0C-7D89-4154-9CA0-54F66B22104B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {7453BA0C-7D89-4154-9CA0-54F66B22104B}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {7453BA0C-7D89-4154-9CA0-54F66B22104B}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {7453BA0C-7D89-4154-9CA0-54F66B22104B}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {B290BCF6-5E33-40C5-801B-9FB573F8B816} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /src/SqlHelper.cs: -------------------------------------------------------------------------------- 1 | #if NETSTANDARD2_0 || NET461 2 | using Microsoft.Data.SqlClient; 3 | #else 4 | using System.Data.SqlClient; 5 | #endif 6 | using System; 7 | using System.IO; 8 | 9 | namespace SqlInMemory 10 | { 11 | /// 12 | /// SqlHelper 13 | /// 14 | public static class SqlHelper 15 | { 16 | /// 17 | /// Create database if not exists 18 | /// Example 1 : databaseName: null(optional) and connectionString: "Data Source=.;Initial Catalog=MyDatabaseName;Integrated Security=true" 19 | /// Example 1 : databaseName: "MyDatabaseName" and connectionString: "Data Source=.;Initial Catalog=master;Integrated Security=true" 20 | /// 21 | /// Connection string to connect 22 | /// Database name to check or create 23 | /// Folder path to create database 24 | public static void CreateDatabaseIfNotExists(string connectionString, string databaseName = null, string folderPath = null) 25 | { 26 | if (!DatabaseExists(connectionString, databaseName)) 27 | CreateDatabase(connectionString, databaseName, folderPath); 28 | } 29 | 30 | /// 31 | /// Drop database and recreate 32 | /// Example 1 : databaseName: null(optional) and connectionString: "Data Source=.;Initial Catalog=MyDatabaseName;Integrated Security=true" 33 | /// Example 1 : databaseName: "MyDatabaseName" and connectionString: "Data Source=.;Initial Catalog=master;Integrated Security=true" 34 | /// 35 | /// Connection string to connect 36 | /// Database name to check or create 37 | /// Folder path to create database 38 | /// Force to close existing connections 39 | public static void DropDatabaseAndRecreate(string connectionString, string databaseName = null, string folderPath = null, bool force = false) 40 | { 41 | if (DatabaseExists(connectionString, databaseName)) 42 | DropDatabase(connectionString, databaseName, force); 43 | CreateDatabase(connectionString, databaseName, folderPath); 44 | } 45 | 46 | /// 47 | /// Drop database 48 | /// Example 1 : databaseName: null(optional) and connectionString: "Data Source=.;Initial Catalog=MyDatabaseName;Integrated Security=true" 49 | /// Example 1 : databaseName: "MyDatabaseName" and connectionString: "Data Source=.;Initial Catalog=master;Integrated Security=true" 50 | /// 51 | /// Connection string to connect 52 | /// Database name to check 53 | /// Force to close existing connections 54 | public static void DropDatabase(string connectionString, string databaseName = null, bool force = false) 55 | { 56 | var builder = new SqlConnectionStringBuilder(connectionString); 57 | 58 | var isMaster = builder.InitialCatalog.Equals("master", StringComparison.OrdinalIgnoreCase); 59 | if (string.IsNullOrWhiteSpace(databaseName)) 60 | { 61 | if (isMaster) 62 | throw new InvalidOperationException($"If {nameof(databaseName)} hasn't value then current InitialCatalog shouldn't be 'master'"); 63 | 64 | databaseName = builder.InitialCatalog; 65 | builder.InitialCatalog = "master"; 66 | } 67 | else 68 | { 69 | if (!isMaster) 70 | throw new InvalidOperationException($"If {nameof(databaseName)} has value ({databaseName}) then current InitialCatalog should be 'master'"); 71 | } 72 | 73 | var command = $"DROP DATABASE {databaseName};"; 74 | if (force) 75 | command = $"ALTER DATABASE {databaseName} SET SINGLE_USER WITH ROLLBACK IMMEDIATE; " + command; 76 | 77 | using (var sqlConnection = new SqlConnection(builder.ConnectionString)) 78 | { 79 | #pragma warning disable CA2100 // Review SQL queries for security vulnerabilities 80 | using (var sqlCommand = new SqlCommand(command, sqlConnection)) 81 | #pragma warning restore CA2100 // Review SQL queries for security vulnerabilities 82 | { 83 | sqlConnection.Open(); 84 | sqlCommand.ExecuteNonQuery(); 85 | } 86 | } 87 | } 88 | 89 | /// 90 | /// Checks the existence of a database 91 | /// Example 1 : databaseName: null(optional) and connectionString: "Data Source=.;Initial Catalog=MyDatabaseName;Integrated Security=true" 92 | /// Example 1 : databaseName: "MyDatabaseName" and connectionString: "Data Source=.;Initial Catalog=master;Integrated Security=true" 93 | /// 94 | /// Connection string to connect 95 | /// Database name to check 96 | /// Whether or not the database is exist 97 | public static bool DatabaseExists(string connectionString, string databaseName = null) 98 | { 99 | var builder = new SqlConnectionStringBuilder(connectionString); 100 | 101 | var isMaster = builder.InitialCatalog.Equals("master", StringComparison.OrdinalIgnoreCase); 102 | if (string.IsNullOrWhiteSpace(databaseName)) 103 | { 104 | if (isMaster) 105 | throw new InvalidOperationException($"If {nameof(databaseName)} hasn't value then current InitialCatalog shouldn't be 'master'"); 106 | 107 | databaseName = builder.InitialCatalog; 108 | builder.InitialCatalog = "master"; 109 | } 110 | else 111 | { 112 | if (!isMaster) 113 | throw new InvalidOperationException($"If {nameof(databaseName)} has value ({databaseName}) then current InitialCatalog should be 'master'"); 114 | } 115 | 116 | var command = "select count(*) from master.dbo.sysdatabases where name=@database"; 117 | using (var sqlConnection = new SqlConnection(builder.ConnectionString)) 118 | { 119 | using (var sqlCommand = new SqlCommand(command, sqlConnection)) 120 | { 121 | sqlCommand.Parameters.Add("@database", System.Data.SqlDbType.NVarChar).Value = databaseName; 122 | sqlConnection.Open(); 123 | return Convert.ToInt32(sqlCommand.ExecuteScalar()) == 1; 124 | } 125 | } 126 | } 127 | 128 | /// 129 | /// Create database 130 | /// Example 1 : databaseName: null(optional) and connectionString: "Data Source=.;Initial Catalog=MyDatabaseName;Integrated Security=true" 131 | /// Example 1 : databaseName: "MyDatabaseName" and connectionString: "Data Source=.;Initial Catalog=master;Integrated Security=true" 132 | /// 133 | /// Connection string to connect 134 | /// Database name to create 135 | /// Folder path to create database 136 | public static void CreateDatabase(string connectionString, string databaseName = null, string folderPath = null) 137 | { 138 | var builder = new SqlConnectionStringBuilder(connectionString); 139 | 140 | var isMaster = builder.InitialCatalog.Equals("master", StringComparison.OrdinalIgnoreCase); 141 | if (string.IsNullOrWhiteSpace(databaseName)) 142 | { 143 | if (isMaster) 144 | throw new InvalidOperationException($"If {nameof(databaseName)} hasn't value then current InitialCatalog shouldn't be 'master'"); 145 | 146 | databaseName = builder.InitialCatalog; 147 | builder.InitialCatalog = "master"; 148 | } 149 | else 150 | { 151 | if (!isMaster) 152 | throw new InvalidOperationException($"If {nameof(databaseName)} has value ({databaseName}) then current InitialCatalog should be 'master'"); 153 | } 154 | 155 | var command = $"CREATE DATABASE {databaseName}"; 156 | if (string.IsNullOrWhiteSpace(folderPath) == false && Directory.Exists(folderPath)) 157 | command += $" ON PRIMARY ( NAME = {databaseName}, FILENAME = '{Path.Combine(folderPath, databaseName + ".mdf")}' )"; 158 | 159 | #region More info 160 | //https://stackoverflow.com/questions/39499810/how-to-create-database-if-not-exist-in-c-sharp-winforms 161 | //https://www.codeproject.com/Questions/666651/How-to-create-a-database-using-csharp-code-in-net 162 | //https://support.microsoft.com/en-us/help/307283/how-to-create-a-sql-server-database-programmatically-by-using-ado-net 163 | 164 | // ConnectionString examples 165 | //"server=(local)\\SQLEXPRESS;Trusted_Connection=yes" 166 | //"Server=localhost;Integrated security=SSPI;database=master" 167 | 168 | //var command = $"CREATE DATABASE {"MyDatabase"} ON PRIMARY " + 169 | // $"(NAME = {"MyDatabase_Data"}, " + 170 | // $"FILENAME = '{"C:\\MyDatabaseData.mdf"}', " + 171 | // $"SIZE = {2}MB, " + 172 | // $"MAXSIZE = {10}MB, " + 173 | // $"FILEGROWTH = {10}%) " + 174 | // $"LOG ON (NAME = {"MyDatabase_Log"}, " + 175 | // $"FILENAME = '{"C:\\MyDatabaseLog.ldf"}', " + 176 | // $"SIZE = {1}MB, " + 177 | // $"MAXSIZE = {5}MB, " + 178 | // $"FILEGROWTH = {10}%)"; 179 | #endregion 180 | 181 | using (var sqlConnection = new SqlConnection(builder.ConnectionString)) 182 | { 183 | #pragma warning disable CA2100 // Review SQL queries for security vulnerabilities 184 | using (var sqlCommand = new SqlCommand(command, sqlConnection)) 185 | #pragma warning restore CA2100 // Review SQL queries for security vulnerabilities 186 | { 187 | sqlConnection.Open(); 188 | sqlCommand.ExecuteNonQuery(); 189 | } 190 | } 191 | } 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/SqlInMemory.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0;net40;net45;net461; 5 | latest 6 | SqlInMemory 7 | SqlInMemory 8 | SqlInMemory 9 | SqlInMemory 10 | 1.0.6 11 | 1.0.6 12 | 1.0.6 13 | Mohammad Javad Ebrahimi 14 | Mohammad Javad Ebrahimi 15 | Copyright © Mohammad Javad Ebrahimi 2020 16 | SqlInMemory is a library for creating SqlServer database on Memory instead of hard disk, at last Drops and Disposes database when you're done with it. This is useful for Integration Testing. 17 | InMemory SqlServer Database 18 | MIT 19 | https://github.com/mjebrahimi/SqlInMemory 20 | https://github.com/mjebrahimi/SqlInMemory 21 | git 22 | true 23 | false 24 | SqlInMemory.png 25 | 26 | 27 | true 28 | 29 | true 30 | 31 | embedded 32 | 33 | 34 | 35 | true 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /src/SqlInMemory.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mjebrahimi/SqlInMemory/8303f46fcc7a13932dd178729a0e460daaa170a7/src/SqlInMemory.png -------------------------------------------------------------------------------- /src/SqlInMemoryDb.cs: -------------------------------------------------------------------------------- 1 | using RamDisk; 2 | using System; 3 | 4 | namespace SqlInMemory 5 | { 6 | /// 7 | /// SqlInMemoryDb 8 | /// 9 | public static class SqlInMemoryDb 10 | { 11 | /// 12 | /// Mounts a drive on system memory and creates SQL database there. (drops database if exists first) 13 | /// 14 | /// Connection string to SQL database 15 | /// Size of ram drive in mega bytes 16 | /// 17 | /// 18 | public static IDisposable Create(string connectionString, int sizeMegaByte = 256, char drive = 'Z') 19 | { 20 | if (string.IsNullOrWhiteSpace(connectionString)) 21 | throw new ArgumentNullException(nameof(connectionString)); 22 | 23 | RamDrive.Mount(sizeMegaByte, RamDisk.FileSystem.NTFS, drive, "SqlInMemory"); 24 | SqlHelper.DropDatabaseAndRecreate(connectionString, null, $"{drive}:\\", force: true); 25 | 26 | return new Releaser(connectionString, drive); 27 | } 28 | 29 | private readonly struct Releaser : IDisposable 30 | { 31 | private readonly string _connectionString; 32 | private readonly char _drive; 33 | 34 | public Releaser(string connectionString, char drive) 35 | { 36 | _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); 37 | _drive = drive; 38 | } 39 | 40 | public void Dispose() 41 | { 42 | SqlHelper.DropDatabase(_connectionString, force: true); 43 | RamDrive.Unmount(_drive); 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /test/SqlInMemory.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /test/SqlInMemoryDbTests.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using System; 3 | 4 | namespace SqlInMemory.Tests 5 | { 6 | public class SqlInMemoryDbTests 7 | { 8 | private string _connectionString; 9 | private string _connectionStringMaster; 10 | private string _databaseName; 11 | private string _driveLetter; 12 | private IDisposable _releaser; 13 | 14 | [OneTimeSetUp] 15 | public void OneTimeSetUp() 16 | { 17 | _connectionString = "Data Source=.;Initial Catalog=TestDb;Integrated Security=true"; 18 | _connectionStringMaster = "Data Source=.;Initial Catalog=master;Integrated Security=true"; 19 | _databaseName = "TestDb"; 20 | _driveLetter = "Z:\\"; 21 | 22 | void action() => _releaser = SqlInMemoryDb.Create(_connectionString); 23 | Assert.DoesNotThrow(action); 24 | } 25 | 26 | [OneTimeTearDown] 27 | public void OneTimeTearDown() 28 | { 29 | void action() => _releaser.Dispose(); 30 | Assert.DoesNotThrow(action); 31 | } 32 | 33 | [Test, Order(1)] 34 | public void DatabaseExists_Should_Exists() 35 | { 36 | var exists = SqlHelper.DatabaseExists(_connectionString); 37 | Assert.IsTrue(exists); 38 | } 39 | 40 | [Test, Order(2)] 41 | public void DatabaseExists_WithName_Should_Exists() 42 | { 43 | var exists = SqlHelper.DatabaseExists(_connectionStringMaster, _databaseName); 44 | Assert.IsTrue(exists); 45 | } 46 | 47 | [Test, Order(3)] 48 | public void DropDatabase_Should_Drops_Database() 49 | { 50 | void action() => SqlHelper.DropDatabase(_connectionString); 51 | Assert.DoesNotThrow(action); 52 | 53 | var exists = SqlHelper.DatabaseExists(_connectionString); 54 | Assert.IsFalse(exists); 55 | } 56 | 57 | [Test, Order(4)] 58 | public void CreateDatabase_Should_Creates_Database() 59 | { 60 | void action() => SqlHelper.CreateDatabase(_connectionString, folderPath: _driveLetter); 61 | Assert.DoesNotThrow(action); 62 | 63 | var exists = SqlHelper.DatabaseExists(_connectionString); 64 | Assert.IsTrue(exists); 65 | } 66 | 67 | [Test, Order(5)] 68 | public void DropDatabase_WithName_Should_Drops_Database() 69 | { 70 | void action() => SqlHelper.DropDatabase(_connectionStringMaster, _databaseName, true); 71 | Assert.DoesNotThrow(action); 72 | 73 | var exists = SqlHelper.DatabaseExists(_connectionStringMaster, _databaseName); 74 | Assert.IsFalse(exists); 75 | } 76 | 77 | [Test, Order(6)] 78 | public void CreateDatabase_WithName_Should_Creates_Database() 79 | { 80 | void action() => SqlHelper.CreateDatabase(_connectionStringMaster, _databaseName, _driveLetter); 81 | Assert.DoesNotThrow(action); 82 | 83 | var exists = SqlHelper.DatabaseExists(_connectionStringMaster, _databaseName); 84 | Assert.IsTrue(exists); 85 | } 86 | 87 | [Test, Order(7)] 88 | public void DropDatabaseAndRecreate_ShouldBe_OK() 89 | { 90 | //Database already exists. first drop then recreate it. 91 | void action() => SqlHelper.DropDatabaseAndRecreate(_connectionString, folderPath: _driveLetter, force: true); 92 | Assert.DoesNotThrow(action); 93 | 94 | var exists = SqlHelper.DatabaseExists(_connectionString); 95 | Assert.IsTrue(exists); 96 | } 97 | 98 | [Test, Order(8)] 99 | public void DropDatabaseAndRecreate_WithName_ShouldBe_OK() 100 | { 101 | //Database already exists. first drop then recreate it. 102 | void action() => SqlHelper.DropDatabaseAndRecreate(_connectionStringMaster, _databaseName, _driveLetter, true); 103 | Assert.DoesNotThrow(action); 104 | 105 | var exists = SqlHelper.DatabaseExists(_connectionStringMaster, _databaseName); 106 | Assert.IsTrue(exists); 107 | } 108 | 109 | [Test, Order(9)] 110 | public void CreateDatabaseIfNotExists_ShouldBe_OK() 111 | { 112 | //Database already exists. therefore does not create 113 | void action1() => SqlHelper.CreateDatabaseIfNotExists(_connectionString, folderPath: _driveLetter); 114 | Assert.DoesNotThrow(action1); 115 | 116 | var exists1 = SqlHelper.DatabaseExists(_connectionString); 117 | Assert.IsTrue(exists1); 118 | 119 | SqlHelper.DropDatabase(_connectionString, force: true); 120 | 121 | void action2() => SqlHelper.CreateDatabaseIfNotExists(_connectionString, folderPath: _driveLetter); 122 | Assert.DoesNotThrow(action2); 123 | 124 | var exists2 = SqlHelper.DatabaseExists(_connectionString); 125 | Assert.IsTrue(exists2); 126 | } 127 | 128 | [Test, Order(10)] 129 | public void CreateDatabaseIfNotExists_WithName_ShouldBe_OK() 130 | { 131 | //Database already exists. therefore does not create 132 | void action1() => SqlHelper.CreateDatabaseIfNotExists(_connectionStringMaster, _databaseName, folderPath: _driveLetter); 133 | Assert.DoesNotThrow(action1); 134 | 135 | var exists1 = SqlHelper.DatabaseExists(_connectionStringMaster, _databaseName); 136 | Assert.IsTrue(exists1); 137 | 138 | SqlHelper.DropDatabase(_connectionStringMaster, _databaseName, force: true); 139 | 140 | void action2() => SqlHelper.CreateDatabaseIfNotExists(_connectionStringMaster, _databaseName, folderPath: _driveLetter); 141 | Assert.DoesNotThrow(action2); 142 | 143 | var exists2 = SqlHelper.DatabaseExists(_connectionString); 144 | Assert.IsTrue(exists2); 145 | } 146 | } 147 | } --------------------------------------------------------------------------------