From 280146a0cc44b9aae448ef111510adc0f1eda9d4 Mon Sep 17 00:00:00 2001 From: Alex de Sousa Date: Tue, 22 Oct 2024 19:36:13 +0200 Subject: [PATCH] :memo: Improve DuckDB documentation --- lib/ayesql/runner/duckdb.ex | 58 +++++++++++++++++++++++++++++++++++++ mix.exs | 3 +- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/lib/ayesql/runner/duckdb.ex b/lib/ayesql/runner/duckdb.ex index 745b1d2..f69a311 100644 --- a/lib/ayesql/runner/duckdb.ex +++ b/lib/ayesql/runner/duckdb.ex @@ -57,6 +57,64 @@ if Code.ensure_loaded?(Duckdbex) do iex> MyQueries.get_user([id: id], conn: connection) {:ok, ...} ``` + + ## Example + + Given the following AyeSQL file: + + ```sql + -- name: get_player_by_last_name + -- docs: Get players by their last name + SELECT * + FROM atp + WHERE name_last = :last_name + ``` + + And the following AyeSQL module: + + ```elixir + defmodule ATP do + use AyeSQL, + runner: AyeSQL.Runner.Duckdbex + + defqueries "./atp.sql" + end + ``` + + Then we can query a CSV file as follows: + + ```elixir + # Open a DuckDB connection + {:ok, db} = Duckdbex.open() + {:ok, conn} = Duckdbex.connection(db) + + # Fetch a remote CSV and copy its contents to the table `atp` + url = "https://raw.githubusercontent.com/duckdb-in-action/examples/refs/heads/main/ch05/atp/atp_players.csv" + {:ok, _res} = Duckdbex.query(conn, "INSTALL httpfs") + {:ok, _res} = Duckdbex.query(conn, "LOAD httpfs") + {:ok, _res} = Duckdbex.query(conn, "CREATE OR REPLACE TABLE atp AS FROM '\#{url}'") + + # Run our query to find a player by last name + ATP.get_player_by_last_name([last_name: "Federer"], conn: conn) + ``` + + This should get the following result: + + ```elixir + {:ok, + [ + %{ + player_id: 103819, + name_first: "Roger", + name_last: "Federer", + hand: "R", + dob: "19810808", + ioc: "SUI", + height: 185, + wikidata_id: "Q1426" + } + ]} + ``` """ use AyeSQL.Runner diff --git a/mix.exs b/mix.exs index b28fd08..1af465c 100644 --- a/mix.exs +++ b/mix.exs @@ -134,7 +134,8 @@ defmodule AyeSQL.MixProject do "AyeSQL runners": [ AyeSQL.Runner, AyeSQL.Runner.Ecto, - AyeSQL.Runner.Postgrex + AyeSQL.Runner.Postgrex, + AyeSQL.Runner.Duckdbex ] ] end