Skip to content

Commit

Permalink
create db
Browse files Browse the repository at this point in the history
  • Loading branch information
Giovanni Visciano committed Aug 13, 2021
1 parent 225fb1d commit f021321
Show file tree
Hide file tree
Showing 10 changed files with 99 additions and 18 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ In your app supervisor, start `Postgrex` and then the `ExqlMigration.Task`.

children = [
{Postgrex, postgres_conf},
{ExqlMigration.Supervisor, [
{ExqlMigration.Migration, [
db_conn: postgres_conn,
migrations_dir: migrations_dir,
timeout: 5_000, # default :infinity
Expand All @@ -57,13 +57,14 @@ if you have multiple DBs to setup:
```elixir
children = [
Supervisor.child_spec({Postgrex, db_A_conf}, id: :postgrex_A),
Supervisor.child_spec({ExqlMigration.Supervisor, [db_conn: db_A_conn, migrations_dir: db_A_migrations_dir]}, id: :exql_db_A),
Supervisor.child_spec({ExqlMigration.Migration, [db_conn: db_A_conn, migrations_dir: db_A_migrations_dir]}, id: :exql_db_A),
Supervisor.child_spec({Postgrex, db_B_conf}, id: :postgrex_B),
Supervisor.child_spec({ExqlMigration.Supervisor, [db_conn: db_B_conn, migrations_dir: db_B_migrations_dir]}, id: :exql_db_B)
Supervisor.child_spec({ExqlMigration.Migration, [db_conn: db_B_conn, migrations_dir: db_B_migrations_dir]}, id: :exql_db_B)
]
```

Check the sample app under `./sample_app`.
`ExqlMigration.CreateDB` can be included in the supervision tree to create (if not exists) a database.
Check the sample app under `./sample_app` for more details.

# Development

Expand Down
17 changes: 17 additions & 0 deletions lib/exql_migration.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,23 @@ defmodule ExqlMigration do
require Logger
alias ExqlMigration.{Log, Schema}

@spec create_db(Postgrex.conn(), String.t()) :: :ok
def create_db(conn, name) do
case Postgrex.query(conn, "create database #{name}", []) do
{:ok, _} ->
Logger.info("Create DB #{inspect(name)}")
:ok

{:error, %Postgrex.Error{postgres: %{code: :duplicate_database}}} ->
:ok

error ->
# coveralls-ignore-start
raise "#{inspect(error)}"
# coveralls-ignore-end
end
end

@spec migrate(Postgrex.conn(), Path.t(), timeout(), boolean()) :: :ok
def migrate(conn, migrations_dir, timeout, transactional) do
Schema.setup(conn)
Expand Down
36 changes: 36 additions & 0 deletions lib/exql_migration/create_db.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# coveralls-ignore-start

defmodule ExqlMigration.CreateDB do
@moduledoc "Migration runner Supervisor"

use Supervisor

require Logger

@type opts :: [{:db_conn, Postgrex.conn()} | {:db_name, String.t()}]

@spec start_link(opts()) :: Supervisor.on_start()
def start_link(opts) do
db_conn = Keyword.fetch!(opts, :db_conn)
db_name = Keyword.fetch!(opts, :db_name)

Supervisor.start_link(__MODULE__, {db_conn, db_name})
end

@impl Supervisor
@spec init({Postgrex.conn(), String.t()}) :: :ignore
def init({db_conn, db_name}) do
ExqlMigration.create_db(db_conn, db_name)

:ignore
rescue
exc ->
Logger.emergency("Create DB failed")
Logger.emergency(Exception.message(exc))
Logger.emergency("#{inspect(exc)}")

:init.stop()
end
end

# coveralls-ignore-stop
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# coveralls-ignore-start

defmodule ExqlMigration.Supervisor do
defmodule ExqlMigration.Migration do
@moduledoc "Migration runner Supervisor"

use Supervisor
Expand Down
7 changes: 7 additions & 0 deletions sample_app/config/config.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import Config

config :example, :db_postgres, name: :db_postgres

config :example, :db_mydb,
name: :db_mydb,
migration_dir: "priv/migrations/mydb"
13 changes: 8 additions & 5 deletions sample_app/config/runtime.exs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import Config

config :postgrex,
name: :db,
config :example, :db_postgres,
hostname: "localhost",
username: "postgres",
password: "postgres",
database: "postgres",
pool_size: 5
pool_size: 1

config :exql_migration,
migration_dir: "priv/migrations"
config :example, :db_mydb,
hostname: "localhost",
username: "postgres",
password: "postgres",
database: "mydb",
pool_size: 5
15 changes: 10 additions & 5 deletions sample_app/lib/example.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@ defmodule Example do
use Application

def start(_type, _args) do
postgrex_conf = Application.get_all_env(:postgrex)
db_conn = Application.fetch_env!(:postgrex, :name)
migrations_dir = Application.fetch_env!(:exql_migration, :migration_dir)
db_postgres_conf = Application.fetch_env!(:example, :db_postgres)
db_mydb_conf = Application.fetch_env!(:example, :db_mydb)

children = [
{Postgrex, postgrex_conf},
{ExqlMigration.Supervisor, [db_conn: db_conn, migrations_dir: migrations_dir]}
# database "postgres" connection
Supervisor.child_spec({Postgrex, db_postgres_conf}, id: :db_postgres),
# create "mydb", connecting to "postgres" database
{ExqlMigration.CreateDB, [db_conn: db_postgres_conf[:name], db_name: db_mydb_conf[:database]]},
# database "mydb" connection
Supervisor.child_spec({Postgrex, db_mydb_conf}, id: :db_mydb),
# database "mydb" schema migrations
{ExqlMigration.Migration, [db_conn: db_mydb_conf[:name], migrations_dir: db_mydb_conf[:migration_dir]]}
]

opts = [strategy: :one_for_one]
Expand Down
1 change: 0 additions & 1 deletion sample_app/priv/migrations/001.sql

This file was deleted.

1 change: 1 addition & 0 deletions sample_app/priv/migrations/mydb/001.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
perform 1;
16 changes: 14 additions & 2 deletions test/exql_migration_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ defmodule ExqlMigrationTest do

setup do
on_exit(fn ->
Postgrex.query!(@postgrex_conn, "DROP SCHEMA IF EXISTS exql_migration CASCADE", [])
Postgrex.query!(@postgrex_conn, "DROP SCHEMA IF EXISTS test CASCADE", [])
Postgrex.query!(@postgrex_conn, "drop schema if exists exql_migration cascade", [])
Postgrex.query!(@postgrex_conn, "drop schema if exists test cascade", [])
end)

:ok
Expand Down Expand Up @@ -54,4 +54,16 @@ defmodule ExqlMigrationTest do
ExqlMigration.migrate(@postgrex_conn, "test/all_migrations", @timeout, true)
assert ^all = ExqlMigration.Log.migrations(@postgrex_conn)
end

test "create DB" do
on_exit(fn ->
Postgrex.query!(@postgrex_conn, "drop database test_db", [])
end)

ExqlMigration.create_db(@postgrex_conn, "test_db")
ExqlMigration.create_db(@postgrex_conn, "test_db")

res = Postgrex.query!(@postgrex_conn, "select true from pg_database where datname = $1", ["test_db"])
assert %Postgrex.Result{num_rows: 1} = res
end
end

0 comments on commit f021321

Please sign in to comment.