|
| 1 | +defmodule Mix.Tasks.Txid.Postgres do |
| 2 | + use Mix.Task |
| 3 | + |
| 4 | + @shortdoc "Manage the in-memory PostgreSQL database for txid_match" |
| 5 | + |
| 6 | + def run(args) do |
| 7 | + {_, [action], _} = OptionParser.parse(args, strict: []) |
| 8 | + |
| 9 | + case action do |
| 10 | + "up" -> postgres_up() |
| 11 | + "down" -> postgres_down() |
| 12 | + _ -> Mix.raise("Unknown action: #{action}. Use 'up' or 'down'.") |
| 13 | + end |
| 14 | + end |
| 15 | + |
| 16 | + defp postgres_up do |
| 17 | + Mix.shell().info("Starting PostgreSQL in-memory database...") |
| 18 | + db_config = Application.get_env(:txid_match, TxidMatch.Postgrex, []) |
| 19 | + |
| 20 | + {:ok, database} = Keyword.fetch(db_config, :database) |
| 21 | + {:ok, host} = Keyword.fetch(db_config, :hostname) |
| 22 | + {:ok, port} = Keyword.fetch(db_config, :port) |
| 23 | + {:ok, username} = Keyword.fetch(db_config, :username) |
| 24 | + {:ok, password} = Keyword.fetch(db_config, :password) |
| 25 | + |
| 26 | + System.put_env("PGPASSWORD", password) |
| 27 | + data_dir = data_dir() |
| 28 | + # 2 GB |
| 29 | + disk_size = 2 * 1024 * 1024 * 1024 |
| 30 | + |
| 31 | + File.mkdir_p!(data_dir) |
| 32 | + user = System.get_env("USER") || raise "$USER not present" |
| 33 | + |
| 34 | + {_, 0} = System.cmd("sudo", ~w(modprobe brd rd_nr=1 rd_size=#{disk_size})) |
| 35 | + {_, 0} = System.cmd("sudo", ~w(mkfs.xfs /dev/ram0)) |
| 36 | + {_, 0} = System.cmd("sudo", ~w(mount /dev/ram0 #{data_dir})) |
| 37 | + {_, 0} = System.cmd("sudo", ~w(chown #{user} #{data_dir})) |
| 38 | + |
| 39 | + File.write!("#{data_dir}/postgresql.conf", """ |
| 40 | + listen_addresses = '*' |
| 41 | + wal_level = logical |
| 42 | + max_replication_slots = 100 |
| 43 | + max_connections = 1000 |
| 44 | + fsync = off |
| 45 | + """) |
| 46 | + |
| 47 | + {_, 0} = System.cmd("pg_ctrl", ~w[init -D #{data_dir}]) |
| 48 | + {_, 0} = System.cmd("pg_ctrl", ~w[start -D #{data_dir}]) |
| 49 | + end |
| 50 | + |
| 51 | + defp postgres_down do |
| 52 | + Mix.shell().info("Stopping PostgreSQL in-memory database...") |
| 53 | + data_dir = data_dir() |> dbg |
| 54 | + |
| 55 | + {_, _} = System.cmd("pg_ctl", ~w[stop -D #{data_dir}]) |
| 56 | + {_, 0} = System.cmd("sudo", ~w(umount #{data_dir})) |
| 57 | + {_, 0} = System.cmd("sudo", ~w(rmmod brd)) |
| 58 | + |
| 59 | + File.rm_rf!(data_dir) |
| 60 | + end |
| 61 | + |
| 62 | + defp data_dir do |
| 63 | + System.get_env("PGDATA", Path.expand("tmp/pgdata", File.cwd!())) |
| 64 | + end |
| 65 | +end |
0 commit comments