This repository was archived by the owner on Jun 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.sql.ts
114 lines (97 loc) · 2.27 KB
/
query.sql.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import { Client } from 'pg';
const getAuthorQuery = `-- name: GetAuthor :one
SELECT * FROM authors
WHERE id = $1 LIMIT 1;`
export type GetAuthorParams = {
id: bigint | null;
}
export type GetAuthorRow = {
id: bigint;
name: string;
bio: string | null;
}
export async function getAuthor(client: Client, args: GetAuthorParams): Promise<GetAuthorRow | null> {
const result = await client.query({
text: getAuthorQuery,
values: [args.id],
rowMode: 'array',
})
if (result.rows.length !== 1) {
return null
}
const row = result.rows[0]
return {
id: row[0],
name: row[1],
bio: row[2],
}
}
const listAuthorsQuery = `-- name: ListAuthors :many
SELECT * FROM authors
ORDER BY name;
`
export type ListAuthorsRow = {
id: bigint;
name: string;
bio: string | null;
}
export async function listAuthors(client: Client): Promise<ListAuthorsRow[]> {
const result = await client.query({
text: listAuthorsQuery,
rowMode: 'array',
})
return result.rows.map(row => {
return {
id: row[0],
name: row[1],
bio: row[2],
}
})
}
const createAuthorQuery = `-- name: CreateAuthor :one
INSERT INTO authors (
name, bio
) VALUES (
$1, $2
)
RETURNING *;`
export type CreateAuthorParams = {
name: string | null;
bio: string | null;
}
export type CreateAuthorRow = {
id: bigint;
name: string;
bio: string | null;
}
export async function createAuthor(client: Client, args: CreateAuthorParams): Promise<CreateAuthorRow | null> {
const result = await client.query({
text: createAuthorQuery,
values: [args.name, args.bio],
rowMode: 'array',
})
if (result.rows.length !== 1) {
return null
}
const row = result.rows[0]
return {
id: row[0],
name: row[1],
bio: row[2],
}
}
const deleteAuthorQuery = `-- name: DeleteAuthor :exec
DELETE FROM authors
WHERE id = $1;`
export type DeleteAuthorParams = {
id: bigint | null;
}
export async function deleteAuthor(client: Client, args: DeleteAuthorParams): Promise<void> {
await client.query(deleteAuthorQuery, [args.id])
}
const deleteAllAuthorsQuery = `-- name: DeleteAllAuthors :exec
DELETE FROM authors
`
export async function deleteAllAuthors(client: Client): Promise<void> {
await client.query(deleteAllAuthorsQuery);
}