Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional database initialization to allow for things like procedures #13

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 54 additions & 37 deletions MySql.Server/Library/MySqlServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace MySql.Server
Expand Down Expand Up @@ -190,63 +191,38 @@ private void extractMySqlFiles()
/// <summary>
/// Starts the server and creates all files and folders necessary
/// </summary>
public void StartServer()
/// <param name="initialze">Whether to initialize the database or not</param>
public void StartServer(bool initialze = false)
{
//The process is still running, don't create a new
if (_process != null && !_process.HasExited)
return;

//Cleaning up any precedented processes
this.KillPreviousProcesses();
KillPreviousProcesses();

createDirs();
extractMySqlFiles();

this._process = new Process();

var arguments = new[]
if (initialze)
{
"--standalone",
"--console",
string.Format("--basedir=\"{0}\"",_mysqlDirectory),
string.Format("--lc-messages-dir=\"{0}\"",_mysqlDirectory),
string.Format("--datadir=\"{0}\"",_dataDirectory),
"--skip-grant-tables",
"--enable-named-pipe",
string.Format("--port={0}", _serverPort.ToString()),
// "--skip-networking",
"--innodb_fast_shutdown=2",
"--innodb_doublewrite=OFF",
"--innodb_log_file_size=1048576",
"--innodb_data_file_path=ibdata1:10M;ibdata2:10M:autoextend"
};

_process.StartInfo.FileName = string.Format("\"{0}\\mysqld.exe\"", _mysqlDirectory);
_process.StartInfo.Arguments = string.Join(" ", arguments);
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.CreateNoWindow = true;

System.Console.WriteLine("Running " + _process.StartInfo.FileName + " " + String.Join(" ", arguments));

try {
_process.Start();
File.WriteAllText(_runningInstancesFile, _process.Id.ToString());
}
catch(Exception e){
throw new Exception("Could not start server process: " + e.Message);
var initProcess = StartMysqlProcess(new[] { "--initialize" });
initProcess.WaitForExit();
}

this.waitForStartup();
_process = StartMysqlProcess(null);
waitForStartup();
}

/// <summary>
/// Start the server on a specified port number
/// </summary>
/// <param name="serverPort">The port on which the server should listen</param>
public void StartServer(int serverPort)
/// <param name="initialze">Whether to initialize the database or not</param>
public void StartServer(int serverPort, bool initialze = false)
{
_serverPort = serverPort;
StartServer();
StartServer(initialze);
}

/// <summary>
Expand All @@ -267,7 +243,7 @@ private void waitForStartup()

while (!_testConnection.State.Equals(System.Data.ConnectionState.Open))
{
if (totalWaitTime > 10000)
if (totalWaitTime > 100000)
throw new Exception("Server could not be started." + lastException.Message);

totalWaitTime = totalWaitTime + sleepTime;
Expand Down Expand Up @@ -345,5 +321,46 @@ public void ShutDown()

removeDirs(10);
}

private Process StartMysqlProcess(string[] additionalArgs)
{
var process = new Process();

var arguments = new[]
{
"--standalone",
"--console",
$"--basedir=\"{_mysqlDirectory}\"",
$"--lc-messages-dir=\"{_mysqlDirectory}\"",
$"--datadir=\"{_dataDirectory}\"",
"--skip-grant-tables",
"--enable-named-pipe",
$"--port={_serverPort.ToString()}",
"--innodb_fast_shutdown=2",
"--innodb_doublewrite=OFF",
"--innodb_log_file_size=1048576",
"--innodb_data_file_path=ibdata1:10M;ibdata2:10M:autoextend"
};
var allArgs = additionalArgs?.Concat(arguments).ToArray() ?? arguments;

process.StartInfo.FileName = $"\"{_mysqlDirectory}\\mysqld.exe\"";
process.StartInfo.Arguments = string.Join(" ", allArgs);
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;

System.Console.WriteLine("Running " + process.StartInfo.FileName + " " + String.Join(" ", allArgs));

try
{
process.Start();
File.WriteAllText(_runningInstancesFile, process.Id.ToString());

return process;
}
catch (Exception e)
{
throw new Exception("Could not start server process: " + e.Message);
}
}
}
}
14 changes: 7 additions & 7 deletions MySql.Server/MySql.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -68,22 +68,22 @@
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ItemGroup>
<Resource Include="MySqlServer\mysqld.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Resource>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup />
<ItemGroup>
<Content Include="MySqlServer\mysqld.exe" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup Condition=" '$(OS)' == 'Windows_NT' ">
<PostBuildEvent>"C:\Nuget\NuGet.exe pack $(ProjectDir)MySql.Server.csproj -Prop Configuration=Release"</PostBuildEvent>
</PropertyGroup>
</PropertyGroup>
<PropertyGroup>
<PostBuildEvent />
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
Expand Down
Binary file modified MySql.Server/MySqlServer/mysqld.exe
Binary file not shown.
4 changes: 2 additions & 2 deletions MySql.Server/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyFileVersion("1.1.0")]
[assembly: AssemblyVersion("1.2.0")]
[assembly: AssemblyFileVersion("1.2.0")]
2 changes: 1 addition & 1 deletion MySql.Server/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ MySql standalone server for C# unit tests
Download with [NuGet](https://www.nuget.org/packages/MySql.Server/), or download the [release](https://github.com/stumpdk/Mysql.Server/releases) and include **Mysql.Server.dll** as a reference in your project.

## How it works
Mysql.Server is simply running a minimal instance of MySql (currently version 5.6.26). Necessary data and log files are created at run time (and are cleaned up afterwards).
Mysql.Server is simply running a minimal instance of MySql (currently version 5.7.20). Necessary data and log files are created at run time (and are cleaned up afterwards).

Mysql.Server makes it possible to create and run unit tests on a real MySql server without spending time on server setup.

Expand Down Expand Up @@ -53,9 +53,9 @@ See [Example.cs](https://github.com/stumpdk/MySql.Server/blob/master/MySql.Serve
## API
* **MySqlServer.Instance**: Retrieves an Instance of the server API.

* **MySqlServer.StartServer()**: Starts the server.
* **MySqlServer.StartServer(bool initialze = false)**: Starts the server. Can also initialize the database before use if required.

* **MySqlServer.StartServer(int serverPort)**: Starts the server at a specified port. Nice to have if you have a real MySql server running on the test machine.
* **MySqlServer.StartServer(int serverPort, bool initialze = false)**: Starts the server at a specified port. Nice to have if you have a real MySql server running on the test machine. Can also initialize the database before use if required.

* **MySqlServer.ShutDown()**: Shuts down the server.

Expand Down