@pgxsinkit/pgwasm-repl 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/repl.tsx ADDED
@@ -0,0 +1,234 @@
1
+ // Began as a copy of `@electric-sql/pglite-repl` (taken under PGlite's PostgreSQL License option,
2
+ // © ElectricSQL — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal.
3
+
4
+ import { defaultKeymap } from "@codemirror/commands";
5
+ import { PostgreSQL } from "@codemirror/lang-sql";
6
+ import { keymap } from "@codemirror/view";
7
+ import { githubDark, githubDarkInit, githubLight, githubLightInit } from "@uiw/codemirror-theme-github";
8
+ import type { CreateThemeOptions } from "@uiw/codemirror-themes";
9
+ import CodeMirror, { type Extension, type ReactCodeMirrorRef } from "@uiw/react-codemirror";
10
+ import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
11
+
12
+ import { ReplResponseView } from "./repl-response";
13
+ import { getSchema, runQuery } from "./run-query";
14
+ import { sqlSupport } from "./sql-support";
15
+ import { REPL_STYLES, REPL_STYLESHEET_ID } from "./styles";
16
+ import type { ReplDatabase, ReplResponse } from "./types";
17
+
18
+ // Enter runs the input, so it is taken out of the default keymap. Up and Down keep their default except
19
+ // on the first and last line, where they walk the history.
20
+ const baseKeymap = defaultKeymap.filter((binding) => binding.key !== "Enter");
21
+
22
+ export type ReplTheme = "light" | "dark" | "auto";
23
+
24
+ type ThemeInit = (options?: Partial<CreateThemeOptions>) => Extension;
25
+
26
+ export const defaultLightThemeInit: ThemeInit = githubLightInit;
27
+ export const defaultLightTheme: Extension = githubLight;
28
+ export const defaultDarkThemeInit: ThemeInit = githubDarkInit;
29
+ export const defaultDarkTheme: Extension = githubDark;
30
+
31
+ export interface ReplProps {
32
+ /** The database: a `Pgwasm`, or anything with its `query` and `exec` (`replAdapter(client)`). */
33
+ readonly pg: ReplDatabase;
34
+ /** An outer border. Defaults to false. */
35
+ readonly border?: boolean;
36
+ readonly lightTheme?: Extension;
37
+ readonly darkTheme?: Extension;
38
+ /** `auto` follows the system's colour scheme. Defaults to `auto`. */
39
+ readonly theme?: ReplTheme;
40
+ /** Show how long each input took. Defaults to false. */
41
+ readonly showTime?: boolean;
42
+ /** Do not re-read the tables for autocompletion after each input. Defaults to false. */
43
+ readonly disableUpdateSchema?: boolean;
44
+ }
45
+
46
+ const prefersDark = () => globalThis.matchMedia?.("(prefers-color-scheme: dark)").matches === true;
47
+
48
+ /** An interactive SQL prompt on a database: psql's `\d` commands, autocompletion, input history. */
49
+ export function Repl({
50
+ pg,
51
+ border = false,
52
+ lightTheme = defaultLightTheme,
53
+ darkTheme = defaultDarkTheme,
54
+ theme = "auto",
55
+ showTime = false,
56
+ disableUpdateSchema = false,
57
+ }: ReplProps) {
58
+ const [value, setValue] = useState("");
59
+ // What was typed before walking the history, and where in the history the input is (-1: not in it).
60
+ const [valueBeforeHistory, setValueBeforeHistory] = useState("");
61
+ const [historyPosition, setHistoryPosition] = useState(-1);
62
+ const [readyPg, setReadyPg] = useState<ReplDatabase | undefined>(undefined);
63
+ const loading = readyPg !== pg;
64
+ const [output, setOutput] = useState<ReplResponse[]>([]);
65
+ const outputRef = useRef<HTMLDivElement | null>(null);
66
+ const [schema, setSchema] = useState<Record<string, string[]>>({});
67
+ const editorRef = useRef<ReactCodeMirrorRef | null>(null);
68
+ const [systemDark, setSystemDark] = useState(prefersDark);
69
+ const themeToUse = theme === "dark" || (theme === "auto" && systemDark) ? darkTheme : lightTheme;
70
+ const [styles, setStyles] = useState<Record<string, string>>({});
71
+
72
+ const refreshSchema = useCallback(() => {
73
+ getSchema(pg).then(
74
+ setSchema,
75
+ // Autocompletion keeps the tables it had.
76
+ () => undefined,
77
+ );
78
+ }, [pg]);
79
+
80
+ // The editor's colours and borders, applied to the whole REPL.
81
+ const extractStyles = useCallback(() => {
82
+ const editor = editorRef.current?.editor?.querySelector(".cm-editor");
83
+ const gutters = editor?.querySelector(".cm-gutters");
84
+ if (!editor || !gutters) return;
85
+ const editorStyle = globalThis.getComputedStyle(editor);
86
+ const gutterStyle = globalThis.getComputedStyle(gutters);
87
+ const foreground = editorStyle.color;
88
+ const borderWidth = Number.parseInt(gutterStyle.borderRightWidth, 10) || 0;
89
+ const borderColor = borderWidth
90
+ ? gutterStyle.borderRightColor
91
+ : foreground.replace("rgb", "rgba").replace(")", ", 0.15)");
92
+ setStyles({
93
+ "--pgwasm-repl-foreground-color": foreground,
94
+ "--pgwasm-repl-background-color": editorStyle.backgroundColor,
95
+ "--pgwasm-repl-border": borderWidth ? gutterStyle.borderRight : `1px solid ${borderColor}`,
96
+ "--pgwasm-repl-gutter-border": gutterStyle.borderRight,
97
+ "--pgwasm-repl-border-color": borderColor,
98
+ });
99
+ }, []);
100
+
101
+ useEffect(() => {
102
+ let ignore = false;
103
+ (pg.waitReady ?? Promise.resolve()).then(
104
+ () => {
105
+ if (!ignore) setReadyPg(pg);
106
+ },
107
+ () => undefined,
108
+ );
109
+ return () => {
110
+ ignore = true;
111
+ };
112
+ }, [pg]);
113
+
114
+ // Follow the system's colour scheme.
115
+ useEffect(() => {
116
+ if (theme !== "auto") return;
117
+ const query = globalThis.matchMedia?.("(prefers-color-scheme: dark)");
118
+ if (query === undefined) return;
119
+ const listener = (event: MediaQueryListEvent) => setSystemDark(event.matches);
120
+ query.addEventListener("change", listener);
121
+ return () => query.removeEventListener("change", listener);
122
+ }, [theme]);
123
+
124
+ // Once a theme is applied, take its colours.
125
+ useEffect(() => {
126
+ const timer = setTimeout(extractStyles, 0);
127
+ return () => clearTimeout(timer);
128
+ }, [themeToUse, extractStyles]);
129
+
130
+ // Keep the latest response in view.
131
+ useEffect(() => {
132
+ const element = outputRef.current;
133
+ if (element) element.scrollTop = element.scrollHeight;
134
+ }, [output]);
135
+
136
+ const onChange = useCallback(
137
+ (next: string) => {
138
+ extractStyles();
139
+ setValue(next);
140
+ if (historyPosition === -1) setValueBeforeHistory(next);
141
+ },
142
+ [extractStyles, historyPosition],
143
+ );
144
+
145
+ const extensions = useMemo(() => {
146
+ const moveHistory = (step: number): boolean => {
147
+ const next = Math.max(-1, Math.min(output.length - 1, historyPosition + step));
148
+ if (next !== historyPosition) {
149
+ setHistoryPosition(next);
150
+ setValue(next === -1 ? valueBeforeHistory : (output[output.length - next - 1]?.query ?? ""));
151
+ }
152
+ return true;
153
+ };
154
+ return [
155
+ keymap.of([
156
+ {
157
+ key: "Enter",
158
+ preventDefault: true,
159
+ run: () => {
160
+ if (value.trim() === "") return false;
161
+ void runQuery(value, pg).then((response) => {
162
+ setOutput((previous) => [...previous, response]);
163
+ // New tables become autocompletion candidates.
164
+ if (!disableUpdateSchema) refreshSchema();
165
+ });
166
+ setHistoryPosition(-1);
167
+ setValueBeforeHistory("");
168
+ setValue("");
169
+ return true;
170
+ },
171
+ },
172
+ {
173
+ key: "ArrowUp",
174
+ run: (view) => {
175
+ const state = view.state;
176
+ if (state.doc.lineAt(state.selection.main.head).number !== 1) return false;
177
+ return moveHistory(1);
178
+ },
179
+ },
180
+ {
181
+ key: "ArrowDown",
182
+ run: (view) => {
183
+ const state = view.state;
184
+ if (state.doc.lineAt(state.selection.main.head).number !== state.doc.lines) return false;
185
+ return moveHistory(-1);
186
+ },
187
+ },
188
+ ...baseKeymap,
189
+ ]),
190
+ sqlSupport({
191
+ dialect: PostgreSQL,
192
+ schema,
193
+ tables: [{ label: "d", displayLabel: "\\d" }],
194
+ defaultSchema: "public",
195
+ }),
196
+ ];
197
+ }, [pg, schema, value, valueBeforeHistory, historyPosition, output, disableUpdateSchema, refreshSchema]);
198
+
199
+ return (
200
+ <div
201
+ className={border ? "pgwasm-repl-root pgwasm-repl-root-border" : "pgwasm-repl-root"}
202
+ style={styles as CSSProperties}
203
+ >
204
+ {/* React inserts this into the document's head once, however many REPLs render it. */}
205
+ <style href={REPL_STYLESHEET_ID} precedence="default">
206
+ {REPL_STYLES}
207
+ </style>
208
+ <div className="pgwasm-repl-output" ref={outputRef}>
209
+ {loading && <div className="pgwasm-repl-loading-msg">Loading...</div>}
210
+ {output.map((response, index) => (
211
+ // An input keeps its place in the history; the same text can be entered twice.
212
+ <div key={index}>
213
+ <ReplResponseView response={response} showTime={showTime} />
214
+ </div>
215
+ ))}
216
+ </div>
217
+ <CodeMirror
218
+ ref={editorRef}
219
+ className={loading ? "pgwasm-repl-input pgwasm-repl-input-loading" : "pgwasm-repl-input"}
220
+ width="100%"
221
+ value={value}
222
+ basicSetup={{ defaultKeymap: false }}
223
+ extensions={extensions}
224
+ theme={themeToUse}
225
+ onChange={onChange}
226
+ editable={!loading}
227
+ onCreateEditor={() => {
228
+ extractStyles();
229
+ refreshSchema();
230
+ }}
231
+ />
232
+ </div>
233
+ );
234
+ }
@@ -0,0 +1,104 @@
1
+ // Began as a copy of `@electric-sql/pglite-repl` (taken under PGlite's PostgreSQL License option,
2
+ // © ElectricSQL — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal.
3
+
4
+ import { describe } from "psql-describe";
5
+
6
+ import type { ReplDatabase, ReplResponse, ReplRows } from "./types";
7
+
8
+ const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error));
9
+
10
+ /** Rows asked for with `rowMode: "array"` are arrays; anything else is shown as one value. */
11
+ function asRows(result: { readonly rows: readonly unknown[]; readonly fields: ReplRows["fields"] }): ReplRows {
12
+ return { rows: result.rows.map((row) => (Array.isArray(row) ? row : [row])), fields: result.fields };
13
+ }
14
+
15
+ /**
16
+ * Run what was typed: psql's `\d` family of commands through psql-describe, anything else as SQL (every
17
+ * statement of it, rows as arrays). A failure is a response with its message, never a throw.
18
+ */
19
+ export async function runQuery(query: string, pg: ReplDatabase): Promise<ReplResponse> {
20
+ if (query.trim().startsWith("\\")) return await runDescribe(query, pg);
21
+ const start = performance.now();
22
+ try {
23
+ const results = await pg.exec(query, { rowMode: "array" });
24
+ return { query, results: results.map(asRows), time: performance.now() - start };
25
+ } catch (error) {
26
+ return { query, error: errorMessage(error), time: performance.now() - start };
27
+ }
28
+ }
29
+
30
+ /** The text type's OID: psql-describe hands its tables over as text. */
31
+ const TEXT_OID = 25;
32
+
33
+ /** A table psql-describe produced (its cells row by row), as rows to show. */
34
+ function describedTable(item: Record<string, unknown>): ReplRows | undefined {
35
+ const { title, headers, cells, footers, ncolumns } = item;
36
+ if (!Array.isArray(headers) || !Array.isArray(cells) || typeof ncolumns !== "number" || ncolumns < 1) {
37
+ return undefined;
38
+ }
39
+ const rows: unknown[][] = [];
40
+ for (let at = 0; at < cells.length; at += ncolumns) rows.push(cells.slice(at, at + ncolumns));
41
+ return {
42
+ rows,
43
+ fields: headers.map((name) => ({ name: String(name), dataTypeID: TEXT_OID })),
44
+ ...(typeof title === "string" ? { title } : {}),
45
+ ...(Array.isArray(footers) ? { footers: footers.map(String) } : {}),
46
+ };
47
+ }
48
+
49
+ /**
50
+ * Run a psql describe command (`\d`, `\dt`, `\df+ pattern`, …): each table psql-describe produces is a
51
+ * result, with its caption and footers; its messages are the response's text.
52
+ */
53
+ export async function runDescribe(query: string, pg: ReplDatabase): Promise<ReplResponse> {
54
+ const start = performance.now();
55
+ const items: (string | Record<string, unknown>)[] = [];
56
+ try {
57
+ const { promise } = describe(
58
+ query,
59
+ "postgres",
60
+ async (sql: string) => {
61
+ const [result] = await pg.exec(sql, { rowMode: "array" });
62
+ const rows = asRows(result ?? { rows: [], fields: [] });
63
+ return { rows: rows.rows, fields: rows.fields, rowCount: rows.rows.length };
64
+ },
65
+ (item) => {
66
+ items.push(item);
67
+ },
68
+ );
69
+ await promise;
70
+ } catch (error) {
71
+ return { query, error: errorMessage(error), time: performance.now() - start };
72
+ }
73
+ const time = performance.now() - start;
74
+ const texts = items.filter((item) => typeof item === "string");
75
+ const error = texts.find((text) => text.startsWith("ERROR:"));
76
+ if (error !== undefined) return { query, error, time };
77
+ const results = items.flatMap((item) => {
78
+ const table = typeof item === "string" ? undefined : describedTable(item);
79
+ return table === undefined ? [] : [table];
80
+ });
81
+ if (texts.length === 0 && results.length === 0) return { query, error: "No output", time };
82
+ return {
83
+ query,
84
+ ...(texts.length > 0 ? { text: texts.join("\n") } : {}),
85
+ ...(results.length > 0 ? { results } : {}),
86
+ time,
87
+ };
88
+ }
89
+
90
+ /** Every table's columns, by `schema.table`, for autocompletion. */
91
+ export async function getSchema(pg: ReplDatabase): Promise<Record<string, string[]>> {
92
+ const result = await pg.query(
93
+ `SELECT table_schema || '.' || table_name, column_name::text
94
+ FROM information_schema.columns
95
+ ORDER BY table_schema, table_name, ordinal_position`,
96
+ [],
97
+ { rowMode: "array" },
98
+ );
99
+ const schema: Record<string, string[]> = {};
100
+ for (const [table, column] of asRows(result).rows) {
101
+ if (typeof table === "string" && typeof column === "string") (schema[table] ??= []).push(column);
102
+ }
103
+ return schema;
104
+ }
@@ -0,0 +1,304 @@
1
+ // Began as a copy of `@electric-sql/pglite-repl` (taken under PGlite's PostgreSQL License option,
2
+ // © ElectricSQL — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal.
3
+
4
+ import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
5
+ import { keywordCompletionSource, PostgreSQL, schemaCompletionSource, type SQLConfig } from "@codemirror/lang-sql";
6
+ import { LanguageSupport } from "@codemirror/language";
7
+
8
+ /** psql's describe commands, offered after a backslash. */
9
+ const describeCompletions: readonly Completion[] = [
10
+ {
11
+ label: "\\d",
12
+ type: "function",
13
+ displayLabel: "\\d[S+] [ pattern ]",
14
+ detail: "PSQL Describe",
15
+ },
16
+ {
17
+ label: "\\da",
18
+ type: "function",
19
+ displayLabel: "\\da[S] [ pattern ]",
20
+ detail: "Lists aggregate functions",
21
+ },
22
+ {
23
+ label: "\\dA",
24
+ type: "function",
25
+ displayLabel: "\\dA[+] [ pattern ]",
26
+ detail: "Lists access methods",
27
+ },
28
+ {
29
+ label: "\\dAc",
30
+ type: "function",
31
+ displayLabel: "\\dAc[+] [access-method-pattern [input-type-pattern]]",
32
+ detail: "Lists operator classes",
33
+ },
34
+ {
35
+ label: "\\dAf",
36
+ type: "function",
37
+ displayLabel: "\\dAf[+] [access-method-pattern [input-type-pattern]]",
38
+ detail: "Lists operator families",
39
+ },
40
+ {
41
+ label: "\\dAo",
42
+ type: "function",
43
+ displayLabel: "\\dAo[+] [access-method-pattern [operator-family-pattern]]",
44
+ detail: "Lists operators associated with operator families",
45
+ },
46
+ {
47
+ label: "\\dAp",
48
+ type: "function",
49
+ displayLabel: "\\dAp[+] [access-method-pattern [operator-family-pattern]]",
50
+ detail: "Lists support functions associated with operator families",
51
+ },
52
+ {
53
+ label: "\\db",
54
+ type: "function",
55
+ displayLabel: "\\db[+] [ pattern ]",
56
+ detail: "Lists tablespaces",
57
+ },
58
+ {
59
+ label: "\\dc",
60
+ type: "function",
61
+ displayLabel: "\\dc[S+] [ pattern ]",
62
+ detail: "Lists conversions between character-set encodings",
63
+ },
64
+ {
65
+ label: "\\dconfig",
66
+ type: "function",
67
+ displayLabel: "\\dconfig[+] [ pattern ]",
68
+ detail: "Lists server configuration parameters and their values",
69
+ },
70
+ {
71
+ label: "\\dC",
72
+ type: "function",
73
+ displayLabel: "\\dC[+] [ pattern ]",
74
+ detail: "Lists type casts",
75
+ },
76
+ {
77
+ label: "\\dd",
78
+ type: "function",
79
+ displayLabel: "\\dd[S] [ pattern ]",
80
+ detail: "Shows the descriptions of objects of type constraint, operator class, operator family, rule, and trigger",
81
+ },
82
+ {
83
+ label: "\\dD",
84
+ type: "function",
85
+ displayLabel: "\\dD[S+] [ pattern ]",
86
+ detail: "Lists domains",
87
+ },
88
+ {
89
+ label: "\\ddp",
90
+ type: "function",
91
+ displayLabel: "\\ddp [ pattern ]",
92
+ detail: "Lists default access privilege settings",
93
+ },
94
+ {
95
+ label: "\\dE",
96
+ type: "function",
97
+ displayLabel: "\\dE[S+] [ pattern ]",
98
+ detail: "Lists foreign tables",
99
+ },
100
+ {
101
+ label: "\\di",
102
+ type: "function",
103
+ displayLabel: "\\di[S+] [ pattern ]",
104
+ detail: "Lists indexes",
105
+ },
106
+ {
107
+ label: "\\dm",
108
+ type: "function",
109
+ displayLabel: "\\dm[S+] [ pattern ]",
110
+ detail: "Lists materialized views",
111
+ },
112
+ {
113
+ label: "\\ds",
114
+ type: "function",
115
+ displayLabel: "\\ds[S+] [ pattern ]",
116
+ detail: "Lists sequences",
117
+ },
118
+ {
119
+ label: "\\dt",
120
+ type: "function",
121
+ displayLabel: "\\dt[S+] [ pattern ]",
122
+ detail: "Lists tables",
123
+ },
124
+ {
125
+ label: "\\dv",
126
+ type: "function",
127
+ displayLabel: "\\dv[S+] [ pattern ]",
128
+ detail: "Lists views",
129
+ },
130
+ {
131
+ label: "\\des",
132
+ type: "function",
133
+ displayLabel: "\\des[+] [ pattern ]",
134
+ detail: "Lists foreign servers",
135
+ },
136
+ {
137
+ label: "\\det",
138
+ type: "function",
139
+ displayLabel: "\\det[+] [ pattern ]",
140
+ detail: "Lists foreign tables",
141
+ },
142
+ {
143
+ label: "\\deu",
144
+ type: "function",
145
+ displayLabel: "\\deu[+] [ pattern ]",
146
+ detail: "Lists user mappings",
147
+ },
148
+ {
149
+ label: "\\dew",
150
+ type: "function",
151
+ displayLabel: "\\dew[+] [ pattern ]",
152
+ detail: "Lists foreign-data wrappers",
153
+ },
154
+ {
155
+ label: "\\df",
156
+ type: "function",
157
+ displayLabel: "\\df[anptwS+] [ pattern [ arg_pattern ... ] ]",
158
+ detail: "Lists functions",
159
+ },
160
+ {
161
+ label: "\\dF",
162
+ type: "function",
163
+ displayLabel: "\\dF[+] [ pattern ]",
164
+ detail: "Lists text search configurations",
165
+ },
166
+ {
167
+ label: "\\dFd",
168
+ type: "function",
169
+ displayLabel: "\\dFd[+] [ pattern ]",
170
+ detail: "Lists text search dictionaries",
171
+ },
172
+ {
173
+ label: "\\dFp",
174
+ type: "function",
175
+ displayLabel: "\\dFp[+] [ pattern ]",
176
+ detail: "Lists text search parsers",
177
+ },
178
+ {
179
+ label: "\\dFt",
180
+ type: "function",
181
+ displayLabel: "\\dFt[+] [ pattern ]",
182
+ detail: "Lists text search templates",
183
+ },
184
+ {
185
+ label: "\\dg",
186
+ type: "function",
187
+ displayLabel: "\\dg[S+] [ pattern ]",
188
+ detail: "Lists database roles",
189
+ },
190
+ {
191
+ label: "\\dl",
192
+ type: "function",
193
+ displayLabel: "\\dl[+] ",
194
+ detail: "List large objects",
195
+ },
196
+ {
197
+ label: "\\dL",
198
+ type: "function",
199
+ displayLabel: "\\dL[S+] [ pattern ]",
200
+ detail: "Lists procedural languages",
201
+ },
202
+ {
203
+ label: "\\dn",
204
+ type: "function",
205
+ displayLabel: "\\dn[S+] [ pattern ]",
206
+ detail: "Lists schemas",
207
+ },
208
+ {
209
+ label: "\\do",
210
+ type: "function",
211
+ displayLabel: "\\do[S+] [ pattern [ arg_pattern [ arg_pattern ] ] ]",
212
+ detail: "Lists operators with their operand and result types",
213
+ },
214
+ {
215
+ label: "\\dO",
216
+ type: "function",
217
+ displayLabel: "\\dO[S+] [ pattern ]",
218
+ detail: "Lists collations",
219
+ },
220
+ {
221
+ label: "\\dp",
222
+ type: "function",
223
+ displayLabel: "\\dp[S] [ pattern ]",
224
+ detail: "Lists tables, views and sequences with their associated access privileges",
225
+ },
226
+ {
227
+ label: "\\dP",
228
+ type: "function",
229
+ displayLabel: "\\dP[itn+] [ pattern ]",
230
+ detail: "Lists partitioned relations",
231
+ },
232
+ {
233
+ label: "\\drds",
234
+ type: "function",
235
+ displayLabel: "\\drds [ role-pattern [ database-pattern ] ]",
236
+ detail: "Lists defined configuration settings",
237
+ },
238
+ {
239
+ label: "\\drg",
240
+ type: "function",
241
+ displayLabel: "\\drg[S] [ pattern ]",
242
+ detail: "Lists information about each granted role membership",
243
+ },
244
+ {
245
+ label: "\\dRp",
246
+ type: "function",
247
+ displayLabel: "\\dRp[+] [ pattern ]",
248
+ detail: "Lists replication publications",
249
+ },
250
+ {
251
+ label: "\\dRs",
252
+ type: "function",
253
+ displayLabel: "\\dRs[+] [ pattern ]",
254
+ detail: "Lists replication subscriptions",
255
+ },
256
+ {
257
+ label: "\\dT",
258
+ type: "function",
259
+ displayLabel: "\\dT[S+] [ pattern ]",
260
+ detail: "Lists data types",
261
+ },
262
+ {
263
+ label: "\\du",
264
+ type: "function",
265
+ displayLabel: "\\du[S+] [ pattern ]",
266
+ detail: "Lists database roles",
267
+ },
268
+ {
269
+ label: "\\dx",
270
+ type: "function",
271
+ displayLabel: "\\dx[+] [ pattern ]",
272
+ detail: "Lists installed extensions",
273
+ },
274
+ {
275
+ label: "\\dX",
276
+ type: "function",
277
+ displayLabel: "\\dX [ pattern ]",
278
+ detail: "Lists extended statistics",
279
+ },
280
+ {
281
+ label: "\\dy",
282
+ type: "function",
283
+ displayLabel: "\\dy[+] [ pattern ]",
284
+ detail: "Lists event triggers",
285
+ },
286
+ ];
287
+
288
+ function describeCompletionSource(context: CompletionContext): CompletionResult | null {
289
+ const word = context.matchBefore(/\\\w*/);
290
+ if (!word || word.from === word.to) return null;
291
+ return { from: word.from, options: describeCompletions };
292
+ }
293
+
294
+ /**
295
+ * `sql()` from `@codemirror/lang-sql`, with one more completion source: psql's `\d` family of commands.
296
+ */
297
+ export function sqlSupport(config: SQLConfig = {}): LanguageSupport {
298
+ const dialect = config.dialect ?? PostgreSQL;
299
+ return new LanguageSupport(dialect.language, [
300
+ config.schema ? dialect.language.data.of({ autocomplete: schemaCompletionSource(config) }) : [],
301
+ dialect.language.data.of({ autocomplete: keywordCompletionSource(dialect, config.upperCaseKeywords === true) }),
302
+ dialect.language.data.of({ autocomplete: describeCompletionSource }),
303
+ ]);
304
+ }