diff --git a/nix/mysql.nix b/nix/mysql.nix index 288abae1..92d3f389 100644 --- a/nix/mysql.nix +++ b/nix/mysql.nix @@ -43,6 +43,19 @@ in ''; }; + initialScript = lib.mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Initial SQL commands to run after `initialDatabases` and `ensureUsers`. This can be multiple + SQL expressions separated by a semi-colon. + ''; + example = '' + CREATE USER foo IDENTIFIED BY 'password@123'; + CREATE USER bar; + ''; + }; + initialDatabases = lib.mkOption { type = types.listOf (types.submodule { options = { @@ -199,6 +212,9 @@ in exec ${config.package}/bin/mysqld ${mysqldOptions} ''; + runInitialScript = lib.optionalString (config.initialScript != null) ''echo ${lib.escapeShellArg config.initialScript} | MYSQL_PWD="" ${config.package}/bin/mysql -u root -N +''; + configureScript = pkgs.writeShellScriptBin "configure-mysql" '' PATH="${lib.makeBinPath [config.package pkgs.coreutils]}:$PATH" set -euo pipefail @@ -242,6 +258,8 @@ in ) | MYSQL_PWD="" ${config.package}/bin/mysql -u root -N '') config.ensureUsers} + + ${runInitialScript} ''; in diff --git a/nix/mysql_test.nix b/nix/mysql_test.nix index bc2f7a66..4c2d5077 100644 --- a/nix/mysql_test.nix +++ b/nix/mysql_test.nix @@ -1,6 +1,12 @@ { pkgs, config, ... }: { - services.mysql.m1.enable = true; - services.mysql.m1.initialDatabases = [{ name = "test_database"; }]; + services.mysql.m1 = { + enable = true; + initialDatabases = [{ name = "test_database"; }]; + initialScript = '' + CREATE USER foo IDENTIFIED BY 'password@123'; + CREATE USER bar; + ''; + }; services.mysql.m1.ensureUsers = [ { name = "test_database"; @@ -13,7 +19,7 @@ settings.processes.test = { command = pkgs.writeShellApplication { - runtimeInputs = [ config.services.mysql.m1.package pkgs.gnugrep ]; + runtimeInputs = [ config.services.mysql.m1.package pkgs.gnugrep pkgs.coreutils ]; text = '' rows=$(echo "SHOW DATABASES LIKE 'test_database';" | MYSQL_PWD="" mysql -h 127.0.0.1 | wc -l) if [ "$rows" -eq 0 ]; then @@ -22,6 +28,13 @@ fi echo 'SELECT VERSION();' | MYSQL_PWD="" mysql -h 127.0.0.1 echo 'SELECT VERSION();' | MYSQL_PWD="" mysql -h 127.0.0.1 -P 3308 + + echo "Checking if users foo and bar are present: " + isFooPresent=$(echo "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'foo');" | MYSQL_PWD="" mysql -h 127.0.0.1 -u root | tail -n1) + isBarPresent=$(echo "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'bar');" | MYSQL_PWD="" mysql -h 127.0.0.1 -u root | tail -n1) + echo "$isFooPresent" | grep 1 + echo "$isBarPresent" | grep 1 + ''; name = "mysql-test"; };