• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

supabase / realtime / 5ae92f9cd1fa29ac5c674c15324e5cae8dd48ba0

03 Jul 2025 07:52AM UTC coverage: 84.906% (-0.005%) from 84.911%
5ae92f9cd1fa29ac5c674c15324e5cae8dd48ba0

push

github

web-flow
fix: expose metrics rpc timeout & compress metrics (#1447)

5 of 7 new or added lines in 2 files covered. (71.43%)

1 existing line in 1 file now uncovered.

1952 of 2299 relevant lines covered (84.91%)

1395.96 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.39
/lib/extensions/postgres_cdc_rls/subscriptions.ex
1
defmodule Extensions.PostgresCdcRls.Subscriptions do
2
  @moduledoc """
3
  This module consolidates subscriptions handling
4
  """
5
  use Realtime.Logs
6

7
  import Postgrex, only: [transaction: 2, query: 3, rollback: 2]
8

9
  @type conn() :: Postgrex.conn()
10

11
  @filter_types ["eq", "neq", "lt", "lte", "gt", "gte", "in"]
12

13
  @spec create(conn(), String.t(), [map()], pid(), pid()) ::
14
          {:ok, Postgrex.Result.t()}
15
          | {:error, Exception.t() | :malformed_subscription_params | {:subscription_insert_failed, map()}}
16
  def create(conn, publication, params_list, manager, caller) do
17
    sql = "with sub_tables as (
17✔
18
        select
19
        rr.entity
20
        from
21
        pg_publication_tables pub,
22
        lateral (
23
        select
24
        format('%I.%I', pub.schemaname, pub.tablename)::regclass entity
25
        ) rr
26
        where
27
        pub.pubname = $1
28
        and pub.schemaname like (case $2 when '*' then '%' else $2 end)
29
        and pub.tablename like (case $3 when '*' then '%' else $3 end)
30
     )
31
     insert into realtime.subscription as x(
32
        subscription_id,
33
        entity,
34
        filters,
35
        claims
36
      )
37
      select
38
        $4::text::uuid,
39
        sub_tables.entity,
40
        $6,
41
        $5
42
      from
43
        sub_tables
44
        on conflict
45
        (subscription_id, entity, filters)
46
        do update set
47
        claims = excluded.claims,
48
        created_at = now()
49
      returning
50
         id"
51

52
    transaction(conn, fn conn ->
17✔
53
      Enum.map(params_list, fn %{id: id, claims: claims, params: params} ->
17✔
54
        case parse_subscription_params(params) do
35✔
55
          {:ok, [schema, table, filters]} ->
56
            case query(conn, sql, [publication, schema, table, id, claims, filters]) do
30✔
57
              {:ok, %{num_rows: num} = result} when num > 0 ->
58
                send(manager, {:subscribed, {caller, id}})
26✔
59
                result
26✔
60

61
              {:ok, _} ->
62
                msg =
4✔
63
                  "Unable to subscribe to changes with given parameters. Please check Realtime is enabled for the given connect parameters: [#{params_to_log(params)}]"
4✔
64

65
                rollback(conn, msg)
4✔
66

67
              {:error, exception} ->
68
                msg =
×
69
                  "Unable to subscribe to changes with given parameters. An exception happened so please check your connect parameters: [#{params_to_log(params)}]. Exception: #{Exception.message(exception)}"
×
70

71
                rollback(conn, msg)
×
72
            end
73

74
          {:error, reason} ->
75
            rollback(conn, reason)
5✔
76
        end
77
      end)
78
    end)
79
  end
80

81
  defp params_to_log(map) do
82
    map
83
    |> Map.to_list()
84
    |> Enum.map_join(", ", fn {k, v} -> "#{k}: #{to_log(v)}" end)
4✔
85
  end
86

87
  @spec delete(conn(), String.t()) :: any()
88
  def delete(conn, id) do
89
    Logger.debug("Delete subscription")
1✔
90
    sql = "delete from realtime.subscription where subscription_id = $1"
1✔
91
    # TODO: connection can be not available
92
    {:ok, _} = query(conn, sql, [id])
1✔
93
  end
94

95
  @spec delete_all(conn()) :: {:ok, Postgrex.Result.t()} | {:error, Exception.t()}
96
  def delete_all(conn) do
97
    Logger.debug("Delete all subscriptions")
8✔
98
    query(conn, "delete from realtime.subscription;", [])
8✔
99
  end
100

101
  @spec delete_multi(conn(), [Ecto.UUID.t()]) ::
102
          {:ok, Postgrex.Result.t()} | {:error, Exception.t()}
103
  def delete_multi(conn, ids) do
104
    Logger.debug("Delete multi ids subscriptions")
3✔
105
    sql = "delete from realtime.subscription where subscription_id = ANY($1::uuid[])"
3✔
106
    query(conn, sql, [ids])
3✔
107
  end
108

109
  @spec maybe_delete_all(conn()) :: {:ok, Postgrex.Result.t()} | {:error, Exception.t()}
110
  def maybe_delete_all(conn) do
111
    query(
9✔
112
      conn,
113
      "do $$
114
        begin
115
          if exists (
116
            select 1
117
            from pg_tables
118
            where schemaname = 'realtime'
119
              and tablename  = 'subscription'
120
          )
121
          then
122
            delete from realtime.subscription;
123
          end if;
124
      end $$",
125
      []
126
    )
127
  end
128

129
  @spec fetch_publication_tables(conn(), String.t()) ::
130
          %{
131
            {<<_::1>>} => [integer()],
132
            {String.t()} => [integer()],
133
            {String.t(), String.t()} => [integer()]
134
          }
135
          | %{}
136
  def fetch_publication_tables(conn, publication) do
137
    sql = "select
30✔
138
    schemaname, tablename, format('%I.%I', schemaname, tablename)::regclass as oid
139
    from pg_publication_tables where pubname = $1"
140

141
    case query(conn, sql, [publication]) do
30✔
142
      {:ok, %{columns: ["schemaname", "tablename", "oid"], rows: rows}} ->
143
        Enum.reduce(rows, %{}, fn [schema, table, oid], acc ->
144
          if String.contains?(table, " ") do
198✔
145
            log_error(
×
146
              "TableHasSpacesInName",
147
              "Table name cannot have spaces: \"#{schema}\".\"#{table}\""
×
148
            )
149
          end
150

151
          Map.put(acc, {schema, table}, [oid])
152
          |> Map.update({schema}, [oid], &[oid | &1])
132✔
153
          |> Map.update({"*"}, [oid], &[oid | &1])
198✔
154
        end)
155
        |> Enum.reduce(%{}, fn {k, v}, acc -> Map.put(acc, k, Enum.sort(v)) end)
30✔
156

157
      _ ->
UNCOV
158
        %{}
×
159
    end
160
  end
161

162
  @doc """
163
  Parses subscription filter parameters into something we can pass into our `create_subscription` query.
164

165
  We currently support the following filters: 'eq', 'neq', 'lt', 'lte', 'gt', 'gte', 'in'
166

167
  ## Examples
168

169
      iex> params = %{"schema" => "public", "table" => "messages", "filter" => "subject=eq.hey"}
170
      iex> Extensions.PostgresCdcRls.Subscriptions.parse_subscription_params(params)
171
      {:ok, ["public", "messages", [{"subject", "eq", "hey"}]]}
172

173
  `in` filter:
174

175
      iex> params = %{"schema" => "public", "table" => "messages", "filter" => "subject=in.(hidee,ho)"}
176
      iex> Extensions.PostgresCdcRls.Subscriptions.parse_subscription_params(params)
177
      {:ok, ["public", "messages", [{"subject", "in", "{hidee,ho}"}]]}
178

179
  An unsupported filter will respond with an error tuple:
180

181
      iex> params = %{"schema" => "public", "table" => "messages", "filter" => "subject=like.hey"}
182
      iex> Extensions.PostgresCdcRls.Subscriptions.parse_subscription_params(params)
183
      {:error, ~s(Error parsing `filter` params: ["like", "hey"])}
184

185
  Catch `undefined` filters:
186

187
      iex> params = %{"schema" => "public", "table" => "messages", "filter" => "undefined"}
188
      iex> Extensions.PostgresCdcRls.Subscriptions.parse_subscription_params(params)
189
      {:error, ~s(Error parsing `filter` params: ["undefined"])}
190

191
  """
192

193
  @spec parse_subscription_params(map()) :: {:ok, list} | {:error, binary()}
194
  def parse_subscription_params(params) do
195
    case params do
39✔
196
      %{"schema" => schema, "table" => table, "filter" => filter} ->
197
        with [col, rest] <- String.split(filter, "=", parts: 2),
4✔
198
             [filter_type, value] when filter_type in @filter_types <-
3✔
199
               String.split(rest, ".", parts: 2),
200
             {:ok, formatted_value} <- format_filter_value(filter_type, value) do
2✔
201
          {:ok, [schema, table, [{col, filter_type, formatted_value}]]}
202
        else
203
          {:error, msg} ->
×
204
            {:error, "Error parsing `filter` params: #{msg}"}
×
205

206
          e ->
2✔
207
            {:error, "Error parsing `filter` params: #{inspect(e)}"}
208
        end
209

210
      %{"schema" => schema, "table" => table} ->
1✔
211
        {:ok, [schema, table, []]}
212

213
      %{"schema" => schema} ->
29✔
214
        {:ok, [schema, "*", []]}
215

216
      %{"table" => table} ->
×
217
        {:ok, ["public", table, []]}
218

219
      map when is_map_key(map, "user_token") or is_map_key(map, "auth_token") ->
2✔
220
        {:error,
221
         "No subscription params provided. Please provide at least a `schema` or `table` to subscribe to: <redacted>"}
222

223
      error ->
3✔
224
        {:error,
225
         "No subscription params provided. Please provide at least a `schema` or `table` to subscribe to: #{inspect(error)}"}
226
    end
227
  end
228

229
  defp format_filter_value(filter, value) do
230
    case filter do
2✔
231
      "in" ->
232
        case Regex.run(~r/^\((.*)\)$/, value) do
1✔
233
          nil ->
×
234
            {:error, "`in` filter value must be wrapped by parentheses"}
235

236
          [_, new_value] ->
1✔
237
            {:ok, "{#{new_value}}"}
1✔
238
        end
239

240
      _ ->
1✔
241
        {:ok, value}
242
    end
243
  end
244
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc