Write an Elixir module that acts as a Poolboy worker, handling database connections.
- User
Write an Elixir module that acts as a
Poolboyworker, handling database connections. Assistant
Write an Elixir module that acts as a Poolboy worker, handling database connections.
1. Understand the Goal: The user wants an Elixir module that functions as a Poolboy worker for handling database connections.
Identify Key Components:
GenServer) that does the actual work.Determine the Architecture:
GenServer because Poolboy expects workers to implement the :poolboy_worker behavior (which effectively means being a GenServer with specific initialization).Postgrex) but wrap it in a try/rescue block or explain that it needs to be in mix.exs. Actually, the cleanest way is to write the worker to wrap a generic state, and show how the start_link function takes connection info.Drafting the Worker Module (DatabaseWorker):
GenServer.start_link/1: This is crucial for Poolboy. It usually takes a map or keyword list of args (pool config) and calls GenServer.start_link.init/1: Where the database connection is established.
Postgrex.start_link.DB.Connection or similar) but comment on where to put Postgrex or MyXQL.query, transaction).handle_call/3: Handle the queries. Use the state (the DB connection PID/Ref).Drafting the Supervisor/Pool Setup:
name, worker_module, size, max_overflow.Refining the Worker Implementation Details:
Step-by-Step Code Construction:
Step 1: Dependencies. Mention {:poolboy, "~> 1.5"} and a DB driver (e.g., {:postgrex, "~> 0.16"}).
Step 2: The Worker Module.
defmodule MyApp.DbWorker do
use GenServer
def start_link(args) do
GenServer.start_link(__MODULE__, args)
end
# ... init (connect to DB) ...
# ... handle_call (execute query) ...
end
Step 3: The Pool Configuration.
pool_options = [
name: {:local, :db_pool},
worker_module: MyApp.DbWorker,
size: 5,
max_overflow: 2
]
# children = [:poolboy.child_spec(:db_pool, pool_options, db_args)]
Step 4: Usage Example.
:poolboy.transaction(:db_pool, fn pid ->
MyApp.DbWorker.query(pid, "SELECT * FROM users")
end)
Addressing Specific "Poolboy" Requirements:
start_link with the args passed to child_spec.Writing the Code (Mental Draft & Refinement):
Postgrex as the concrete example because it's the most common use case in Elixir. It makes the code understandable immediately.%Postgrex.Connection{} or just the PID returned by Postgrex.start_link.Postgrex itself is a GenServer. If I wrap it in another GenServer, I have double the processes (The Worker GenServer + The Connection GenServer).
:poolboy_worker directly, but it doesn't quite fit the pattern easily without a wrapper, and often we want custom logic (retries, logging) inside the worker.init and holds the PID.Finalizing the Example:
DatabaseWorker.start_link/1, query/2.init/1 connects to DB. handle_call proxies query to the DB connection.Review against User Prompt: "Write an Elixir module that acts as a Poolboy worker".
Constructing the Response:
mix.exs.(Self-Correction during coding): Ensure to handle the case where the DB connection fails in init. If init returns {:stop, reason}, the pool won't fill up, which is correct behavior.
Detailed Code Structure:
MyApp.DBWorkerinit/1: Connects to DB. Returns {:ok, %{conn: pid}}.handle_call({:query, sql}, _from, state): Calls Postgrex.query(state.conn, sql).terminate/2: Close connection cleanly? Postgrex handles this mostly, but good practice to mention.Let's refine the example to be generic enough but realistic. I'll use a placeholder for the actual database driver logic to ensure the code is copy-paste runnable (as a mock) but show exactly where Postgrex/MyXQL fits in.
Actually, sticking to a specific library (Postgrex) is usually more helpful for learning than abstract pseudo-code. I'll use Postgrex but clearly label it.
Formatting: Use markdown code blocks.
Let's write the actual code logic.
defmodule MyApp.DatabaseWorker do
use GenServer
def start_link(args) do
GenServer.start_link(__MODULE__, args)
end
def query(pid, query) do
GenServer.call(pid, {:query, query})
end
@impl true
def init(args) do
# Connect to DB here
# Case :ok | :stop
end
...
end
Poolboy integration:
children = [
:poolboy.child_spec(:db_pool, pool_opts, worker_opts)
]
Wait, :poolboy.child_spec returns a tuple {id, start, restart, shutdown, type, modules}.
In a Supervisor init, we usually pass a list of maps or tuples. :poolboy.child_spec generates a valid child spec tuple (or map in newer versions?). Poolboy is old school, it usually returns a tuple. Modern Elixir Supervisors expect maps or tuples. We need to ensure compatibility. Using Supervisor.init handles tuples fine.
Final Polish: Add comments explaining the "Overflow" and "Size" concepts briefly.
Self-Correction: The user specifically asked for the module. I will focus primarily on the module, but provide the setup as "glue" code.
Code Plan:
DBWorker.start_link takes connection opts.init starts DB link.handle_call executes query.handle_info checks for connection death (optional but good).Let's produce the response. Here is a complete example of an Elixir module acting as a Poolboy worker.
To make this example realistic but runnable without an actual database server, I have implemented a "Mock" database client inside the worker. In a production scenario, you would replace the Mock logic with your actual database driver (like Postgrex or MyXQL).
DbWorker)This module implements the :poolboy_worker behaviour. It is a GenServer that holds a single database connection as its state.
defmodule DbWorker do
@behaviour :poolboy_worker
use GenServer
# --- Client API ---
def start_link(args) do
GenServer.start_link(__MODULE__, args)
end
# Example public function to run a query via the worker
def run_query(worker_pid, query) do
GenServer.call(worker_pid, {:query, query})
end
# --- Server Callbacks ---
@impl true
def init(args) do
# In a real app, you would connect to the DB here using args (host, user, pass)
# e.g., {:ok, conn} = Postgrex.start_link(args)
IO.puts("[DbWorker] Starting connection...")
# We simulate a connection process
Process.sleep(100)
# We store the "connection" in state. Here we just store a mock reference.
state = %{
conn: :mock_db_connection,
config: args
}
{:ok, state}
end
@impl true
def handle_call({:query, sql_query}, _from, state) do
# 1. Use the connection in state to execute the query
# result = MyXQL.query!(state.conn, sql_query)
IO.puts("[DbWorker] Executing: #{sql_query}")
# Simulate database latency
Process.sleep(50)
# 2. Return result
{:reply, {:ok, "Result for: #{sql_query}"}, state}
end
@impl true
def terminate(_reason, _state) do
# Clean up the database connection here if necessary
IO.puts("[DbWorker] Closing connection.")
:ok
end
end
You typically define the pool in your application.ex or a specific supervisor. We use :poolboy.child_spec to generate the specification.
defmodule MyApp.Application do
use Application
def start(_type, _args) do
# Poolboy Configuration
pool_args = [
name: {:local, :db_pool}, # Name of the pool
worker_module: DbWorker, # The module we defined above
size: 5, # Number of permanent connections
max_overflow: 2 # Temporary connections if pool is empty
]
# Arguments passed to DbWorker.init/1
worker_args = [
host: "localhost",
database: "my_app_db",
username: "postgres"
]
children = [
# Add the pool to the supervision tree
:poolboy.child_spec(:db_pool, pool_args, worker_args)
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
Now you can execute database commands using the pool. You do not need to start DbWorker manually; Poolboy manages that.
defmodule MyApp.QueryRunner do
def get_user_data(user_id) do
# :poolboy.transaction takes the pool name and a function
# that receives the pid of an available worker.
:poolboy.transaction(:db_pool, fn worker_pid ->
case DbWorker.run_query(worker_pid, "SELECT * FROM users WHERE id=#{user_id}") do
{:ok, result} -> result
{:error, _} -> :error
end
end)
end
end
@behaviour :poolboy_worker: This tells the compiler (and Poolboy) that this module is intended to be a worker.start_link/1: Poolboy expects the worker to accept a single argument (a list or map of configuration) and return {:ok, pid}.poolboy.transaction: This blocks until a worker is available, runs your function with the worker's PID, and then returns the worker to the pool.