0
Upsert data
One script reply has been approved by the moderators Verified
Created by adam186 451 days ago Viewed 6336 times
0
Submitted by adam186 Deno
Verified 451 days ago
1
import {
2
  refreshAndRetryIfExpired,
3
  removeObjectEmptyFields,
4
} from "https://deno.land/x/windmill_helpers@v1.1.1/mod.ts";
5

6
/**
7
 * @param on_conflict Comma-separated UNIQUE column(s) to specify how duplicate
8
 * rows are determined. Two rows are duplicates if all the onConflict columns are equal.
9
 *
10
 * @param ignore_duplicates If true, duplicate rows are ignored. If false, duplicate
11
 * rows are merged with existing rows.
12
 *
13
 * @param token Supabase `access_token` and `refresh_token`. `expires_at` (optional) is a UNIX
14
 * timestamp in seconds.
15
 *
16
 * @param count Count algorithm to use to count rows in the table or view.
17
 * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the hood.
18
 * `"planned"`: Approximated but fast count algorithm. Uses the Postgres statistics under the hood.
19
 * `"estimated"`: Uses exact count for low numbers and planned count for high numbers.
20
 */
21
type Supabase = {
22
  url: string;
23
  key: string;
24
};
25
export async function main(
26
  auth: Supabase,
27
  table: string,
28
  values: any,
29
  on_conflict?: string,
30
  ignore_duplicates: boolean = true,
31
  return_updated: boolean = false,
32
  token?: {
33
    access: string;
34
    refresh: string;
35
    expires_at?: number;
36
  },
37
  count?: "exact" | "planned" | "estimated",
38
) {
39
  return await refreshAndRetryIfExpired(auth, token, async (client) => {
40
    let query: any = client
41
      .from(table)
42
      .upsert(
43
        values,
44
        removeObjectEmptyFields({ on_conflict, ignore_duplicates, count }),
45
      );
46
    if (return_updated) {
47
      query = query.select();
48
    }
49

50
    return query;
51
  });
52
}
53