Skip to content

Commit

Permalink
feat: follow base SDK update
Browse files Browse the repository at this point in the history
  • Loading branch information
zoedsoupe committed Aug 30, 2024
1 parent 26cc513 commit bcdcc5a
Show file tree
Hide file tree
Showing 13 changed files with 170 additions and 168 deletions.
11 changes: 11 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## Problem

<!-- what problem is the PR is trying to solve? -->

## Solution

<!-- how is the PR solving the problem? -->

## Rationale

<!-- why was it implemented the way it was? -->
40 changes: 40 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: ci

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
lint:
runs-on: ubuntu-latest

strategy:
matrix:
elixir: [1.17.0]
otp: [27.0]

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Elixir
uses: erlef/setup-beam@v1
with:
elixir-version: ${{ matrix.elixir }}
otp-version: ${{ matrix.otp }}

- name: Install dependencies
run: mix deps.get

- name: Clean build
run: mix clean

- name: Check code formatting
run: mix format --check-formatted

- name: Run Credo
run: mix credo --strict
30 changes: 30 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: release

on:
push:
tags:
- '*'

env:
MIX_ENV: prod

jobs:
publish:
runs-on: ubuntu-latest
strategy:
matrix:
elixir: [1.17.0]
otp: [27.0]
steps:
- uses: actions/checkout@v3
- name: Set up Elixir
uses: erlef/setup-beam@v1
with:
elixir-version: ${{ matrix.elixir }}
otp-version: ${{ matrix.otp }}
- name: Publish to Hex
uses: synchronal/hex-publish-action@v3
with:
name: supabase_potion
key: ${{ secrets.HEX_PM_KEY }}
tag-release: true
14 changes: 4 additions & 10 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright 2023 zoedsoupe <[email protected]>

Copyright (C) 2023 Zoey Pessanha <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

0. You just DO WHAT THE FUCK YOU WANT TO.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8 changes: 4 additions & 4 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions flake.nix
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
description = "Supabase PostgREST SDK for Elixir";
description = "Supabase SDK for Elixir";

inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-23.11";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-parts.url = "github:hercules-ci/flake-parts";
systems.url = "github:nix-systems/default";
};
Expand All @@ -19,9 +19,9 @@
system,
...
}: let
inherit (pkgs.beam.interpreters) erlangR26;
inherit (pkgs.beam.interpreters) erlang_27;
inherit (pkgs.beam) packagesWith;
beam = packagesWith erlangR26;
beam = packagesWith erlang_27;
in {
_module.args.pkgs = import inputs.nixpkgs {
inherit system;
Expand All @@ -31,7 +31,7 @@
mkShell {
name = "postgrest-ex";
packages = with pkgs;
[beam.elixir_1_16]
[beam.elixir_1_17]
++ lib.optional stdenv.isLinux [inotify-tools]
++ lib.optional stdenv.isDarwin [
darwin.apple_sdk.frameworks.CoreServices
Expand Down
162 changes: 37 additions & 125 deletions lib/supabase/postgrest.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ defmodule Supabase.PostgREST do

import Kernel, except: [not: 1, and: 2, or: 2, in: 2]

import Supabase.Client, only: [is_client: 1]

alias Supabase.Client
alias Supabase.PostgREST.Error
alias Supabase.PostgREST.FilterBuilder
alias Supabase.PostgREST.QueryBuilder
Expand All @@ -34,7 +33,7 @@ defmodule Supabase.PostgREST do
- Supabase documentation on initializing queries: https://supabase.com/docs/reference/javascript/from
"""
@impl true
def from(client, table) when is_client(client) do
def from(%Client{} = client, table) do
QueryBuilder.new(table, client)
end

Expand Down Expand Up @@ -102,10 +101,12 @@ defmodule Supabase.PostgREST do
@impl true
def insert(%QueryBuilder{} = q, data, opts \\ []) do
on_conflict = Keyword.get(opts, :on_conflict)
on_conflict = if on_conflict, do: "on_conflict=#{on_conflict}"
upsert = if on_conflict, do: "resolution=merge-duplicates"
returning = Keyword.get(opts, :returning, :representation)
count = Keyword.get(opts, :count, :exact)
prefer = Enum.join([upsert, "return=#{returning}", "count=#{count}"], ",")
prefer = ["return=#{returning}", "count=#{count}", on_conflict, upsert]
prefer = Enum.join(Enum.reject(prefer, &is_nil/1), ",")

case Jason.encode(data) do
{:ok, body} ->
Expand Down Expand Up @@ -703,8 +704,7 @@ defmodule Supabase.PostgREST do
def overlaps(%FilterBuilder{} = f, column, values)
when is_list(values) do
values
|> Enum.map(&"%##{&1}")
|> Enum.join(",")
|> Enum.map_join(",", &"%##{&1}")
|> then(&FilterBuilder.add_param(f, column, "{#{&1}}"))
end

Expand Down Expand Up @@ -830,7 +830,7 @@ defmodule Supabase.PostgREST do
"""
@impl true
def single(%FilterBuilder{} = f) do
FilterBuilder.add_header(f, "accept", "application/vnd.pgrst,object+json")
FilterBuilder.add_header(f, "accept", "application/vnd.pgrst.object+json")
end

@doc """
Expand Down Expand Up @@ -896,19 +896,19 @@ defmodule Supabase.PostgREST do
def execute_to(%FilterBuilder{} = f, schema) when is_atom(schema) do
with {:ok, body} <- execute(f.client, f.method, f.body, f.table, f.headers, f.params) do
if is_list(body) do
Enum.map(body, &struct(schema, &1))
{:ok, Enum.map(body, &struct(schema, &1))}
else
struct(schema, body)
{:ok, struct(schema, body)}
end
end
end

def execute_to(%QueryBuilder{} = q, schema) when is_atom(schema) do
with {:ok, body} <- execute(q.client, q.method, q.body, q.table, q.headers, q.params) do
if is_list(body) do
Enum.map(body, &struct(schema, &1))
{:ok, Enum.map(body, &struct(schema, &1))}
else
struct(schema, body)
{:ok, struct(schema, body)}
end
end
end
Expand All @@ -929,35 +929,35 @@ defmodule Supabase.PostgREST do
- Supabase query execution: https://supabase.com/docs/reference/javascript/performing-queries
"""
@impl true
def execute_to_finch_request(%mod{} = q) when Kernel.in(mod, [FilterBuilder, QueryBuilder]) do
with {:ok, %Supabase.Client{} = client} = Supabase.Client.retrieve_client(q.client) do
base_url = Path.join([client.conn.base_url, @api_path, q.table])
accept_profile = {"accept-profile", client.db.schema}
content_profile = {"content-profile", client.db.schema}
additional_headers = Map.to_list(q.headers) ++ [accept_profile, content_profile]
headers = Supabase.Fetcher.apply_client_headers(client, nil, additional_headers)
query = URI.encode_query(q.params)
url = URI.new!(base_url) |> URI.append_query(query)

Supabase.Fetcher.new_connection(q.method, url, q.body, headers)
end
def execute_to_finch_request(%mod{client: client} = q)
when Kernel.in(mod, [FilterBuilder, QueryBuilder]) do
base_url = Path.join([client.conn.base_url, @api_path, q.table])
headers = apply_headers(client, q.headers)
query = URI.encode_query(q.params)
url = URI.new!(base_url) |> URI.append_query(query)

Supabase.Fetcher.new_connection(q.method, url, q.body, headers)
end

defp execute(client, method, body, table, headers, params) do
with {:ok, %Supabase.Client{} = client} = Supabase.Client.retrieve_client(client) do
base_url = Path.join([client.conn.base_url, @api_path, table])
accept_profile = {"accept-profile", client.db.schema}
content_profile = {"content-profile", client.db.schema}
additional_headers = Map.to_list(headers) ++ [accept_profile, content_profile]
headers = Supabase.Fetcher.apply_client_headers(client, nil, additional_headers)
query = URI.encode_query(params)
url = URI.new!(base_url) |> URI.append_query(query)
request = request_fun_from_method(method)

url
|> request.(body, headers)
|> parse_response()
end
base_url = Path.join([client.conn.base_url, @api_path, table])
headers = apply_headers(client, headers)
query = URI.encode_query(params)
url = URI.new!(base_url) |> URI.append_query(query)
request = request_fun_from_method(method)

url
|> request.(body, headers)
|> parse_response()
end

defp apply_headers(client, headers) do
accept_profile = {"accept-profile", client.db.schema}
content_profile = {"content-profile", client.db.schema}
content_type = {"content-type", "application/json"}
additional_headers = Map.to_list(headers) ++ [accept_profile, content_profile, content_type]

Supabase.Fetcher.apply_client_headers(client, nil, additional_headers)
end

defp request_fun_from_method(:get), do: &Supabase.Fetcher.get/3
Expand All @@ -984,92 +984,4 @@ defmodule Supabase.PostgREST do
defp success_resp?(status) do
Kernel.in(status, 200..399)
end

defmacrop wrap_postgrest_functions do
quote unquote: false, bind_quoted: [module: __MODULE__] do
for {fun, arity} <- module.__info__(:functions) do
cond do
fun == :from ->
quote do
@doc """
Check `Supabase.PostgREST.#{unquote(fun)}/#{unquote(arity)}`
"""
def unquote(fun)(schema) do
apply(unquote(module), unquote(fun), [@client, schema])
end
end

arity == 1 ->
quote do
@doc """
Check `Supabase.PostgREST.#{unquote(fun)}/#{unquote(arity)}`
"""
def unquote(fun)(data) do
apply(unquote(module), unquote(fun), [data])
end
end

true ->
args = for idx <- 1..arity, do: Macro.var(:"arg#{idx}", module)

quote do
@doc """
Check `Supabase.PostgREST.#{unquote(fun)}/#{unquote(arity)}`
"""
def unquote(fun)(unquote_splicing(args)) do
args = [unquote_splicing(args)]
apply(unquote(module), unquote(fun), args)
end
end
end
end
end
end

defmacro __using__([{:client, client} | opts]) do
config = Macro.escape(Keyword.get(opts, :config, %{}))

quote location: :keep do
@client unquote(client)

def child_spec(opts) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [opts]},
type: :supervisor
}
end

def start_link(opts \\ []) do
manage_clients? = Application.get_env(:supabase_potion, :manage_clients, true)

if manage_clients? do
Supabase.init_client(unquote(client), unquote(config))
else
base_url =
Application.get_env(:supabase_potion, :supabase_base_url) ||
raise Supabase.MissingSupabaseConfig, :url

api_key =
Application.get_env(:supabase_potion, :supabase_api_key) ||
raise Supabase.MissingSupabaseConfig, :key

config =
unquote(config)
|> Map.put(:conn, %{base_url: base_url, api_key: api_key})
|> Map.put(:name, unquote(client))

opts = [name: unquote(client), client_info: config]
Supabase.Client.start_link(opts)
end
|> then(fn
{:ok, pid} -> {:ok, pid}
{:error, {:already_started, pid}} -> {:ok, pid}
err -> err
end)
end

unquote(wrap_postgrest_functions())
end
end
end
2 changes: 2 additions & 0 deletions lib/supabase/postgrest/error.ex
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
defmodule Supabase.PostgREST.Error do
@moduledoc false

@derive Jason.Encoder
defstruct [:hint, :details, :code, :message]

Expand Down
2 changes: 2 additions & 0 deletions lib/supabase/postgrest/filter_builder.ex
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
defmodule Supabase.PostgREST.FilterBuilder do
@moduledoc false

alias Supabase.PostgREST.QueryBuilder

defstruct [:method, :body, :table, :headers, :params, :client]
Expand Down
Loading

0 comments on commit bcdcc5a

Please sign in to comment.