0

Query D1 Database

by
Published today

Run a SQL statement against a D1 database. Use ? placeholders and pass their values in params.

Script cloudflare Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 3 hours ago
1
//native
2

3
export type DynSelect_database_id = string
4

5
// Dropdown of the account's D1 databases, by name.
6
export async function database_id(auth: RT.Cloudflare) {
7
  const response = await fetch(
8
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/d1/database?per_page=100`,
9
    {
10
      headers: {
11
        Authorization: `Bearer ${auth.token}`,
12
        Accept: "application/json",
13
      },
14
    }
15
  )
16
  if (!response.ok) {
17
    throw new Error(`${response.status} ${await response.text()}`)
18
  }
19
  const { result } = (await response.json()) as {
20
    result: { uuid: string; name: string }[]
21
  }
22
  return result.map((d) => ({ value: d.uuid, label: d.name }))
23
}
24

25
/**
26
 * Query D1 Database
27
 * Run a SQL statement against a D1 database. Use ? placeholders and pass their values in params.
28
 */
29
export async function main(
30
  auth: RT.Cloudflare,
31
  database_id: DynSelect_database_id,
32
  sql: string,
33
  params: string[] | undefined
34
) {
35
  const response = await fetch(
36
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/d1/database/${database_id}/query`,
37
    {
38
      method: "POST",
39
      headers: {
40
        Authorization: `Bearer ${auth.token}`,
41
        "Content-Type": "application/json",
42
        Accept: "application/json",
43
      },
44
      body: JSON.stringify({ sql, params: params ?? [] }),
45
    }
46
  )
47

48
  if (!response.ok) {
49
    throw new Error(`${response.status} ${await response.text()}`)
50
  }
51

52
  return await response.json()
53
}
54