vite-plugin-postgres-import 0.1.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/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2025 CT
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,169 @@
1
+ # vite-plugin-postgres-import
2
+
3
+ Ever wanted to ditch those ORMs and finally learn SQL?
4
+
5
+ If you use PostgreSQL and Vite - this plugin is right for you!
6
+
7
+ Start importing `.sql` files with sqlc-style annotations right into your JavaScript code today!
8
+
9
+ ## Usage
10
+
11
+ `module.sql`:
12
+
13
+ ```sql
14
+ -- name: Query :one
15
+ select id
16
+ from t
17
+ where id = :id;
18
+
19
+ -- name: UpdateQuery :execrows
20
+ update t
21
+ set foo = :newFoo
22
+ where id = :id;
23
+
24
+ -- name: QueryMany :many
25
+ select *
26
+ from t;
27
+
28
+ -- name: MultiStatement :many
29
+ select *
30
+ from t;
31
+ -- :one
32
+ select something
33
+ from t
34
+ limit 1;
35
+ -- :execrows
36
+ delete from t
37
+ where foo = :foo;
38
+ ```
39
+
40
+ `usage.js`:
41
+
42
+ ```js
43
+ import { Pool } from "pg";
44
+ import { Query, UpdateQuery, QueryMany, MultiStatement } from "./module.sql";
45
+
46
+ const pool = new Pool('...');
47
+
48
+ const { id } = await Query(pool, { id: 1 });
49
+
50
+ const rowsUpdated = await UpdateQuery(pool, { id: 1, newFoo: "bar" });
51
+
52
+ const array = await QueryMany(pool);
53
+
54
+ // array, object, number respectively
55
+ const [all, something, deleted] = await MultiStatement(pool, { foo: "bar" });
56
+ ```
57
+
58
+ > ### **Note**
59
+ >
60
+ > Postgres does _NOT_ allow using parameters in multi-statement queries.
61
+ >
62
+ > The current implementation for them is a hackaround that involes injecting escaped values into the SQL string.
63
+
64
+ ## Annotations
65
+
66
+ The only 3 sqlc annotations that are available are the following:
67
+
68
+ - `:execresult` - default if neither of the 3 below are provided, returns `QueryResult`.
69
+
70
+ ex: `Query<R extends QueryResultRow = { ... }>(c): Promise<QueryResult<R>>`
71
+
72
+ - `:one` - returns template argument, or the default-parsed ones from the select/returning clause.
73
+
74
+ ex: `Query<R = { ... }>(c): Promise<R>`
75
+
76
+ - `:many` - returns template argument as an array, or the default-parsed ones from the select/returning clause.
77
+
78
+ ex: `Query<R = { ... }>(c): Promise<R[]>`
79
+
80
+ - `:execrows` - returns number of affected rows.
81
+
82
+ ex: `Query(c): Promise<number>`
83
+
84
+ 2 additional annotations not found in sqlc are available:
85
+
86
+ - `:prepare` - prepares the statement by passing query's name to query config.
87
+
88
+ > ### **Warning**
89
+ >
90
+ > Similarly to parameters, Postgres does _NOT_ allow preparing multi-statement queries. Using `:prepare` on a multi-statement query will result in an error. I warned you!
91
+
92
+ > ### **Warning**
93
+ >
94
+ > Don't use identical names for prepared queries, regardless whether they're in different `.sql` modules or not:
95
+ >
96
+ > `one.sql`:
97
+ >
98
+ > ```sql
99
+ > -- name: One :one :prepare
100
+ > select *
101
+ > from t
102
+ > ```
103
+ >
104
+ > `another-one.sql`:
105
+ >
106
+ > ```sql
107
+ > -- name: One :one :prepare
108
+ > select id
109
+ > from t
110
+ > where id = :id;
111
+ > ```
112
+ >
113
+ > `script.js`:
114
+ >
115
+ > ```js
116
+ > import { One } from "./one.sql";
117
+ > import { One as AnotherOne } from "./another-one.sql";
118
+ >
119
+ > // definitely don't do this
120
+ > await One(c);
121
+ > await AnotherOne(c, { id: ... });
122
+ > ```
123
+ >
124
+ > At best, you'd get an error in the provided example, due to mismatch in provided values, and at worst, assuming different examples, you'd be getting obscure bugs related to incorrect data.
125
+
126
+ - `:array` - sets `rowMode` to `'array'`. Modifies to type declarations accordingly:
127
+
128
+ ex. `:execresult`: `Query<R extends any[] = [ ... ]>(c): Promise<QueryArrayResult<R>>`
129
+
130
+ ex. `:one`: `Query<R = [ ... ]>(c): Promise<R>`
131
+
132
+ ex. `:many`: `Query<R = [ ... ]>(c): Promise<R[]>`
133
+
134
+ ## Configuring
135
+
136
+ ### `typesFolder`
137
+
138
+ Path to a folder where all declaration are kept relative to `rootFolder`, i.e.
139
+ a file at path `src/sql/module.sql` will have its `.d.ts` file generated into `${typesFolder}/src/sql/module.sql.d.ts`.
140
+ Make sure you include this one in your `tsconfig.json` as `"${typesFolder}/**/*.sql.d.ts"`.
141
+
142
+ _default:_ `'node_modules/@types/vite-plugin-postgres-import/'`
143
+
144
+ ### `modulePrefix`
145
+
146
+ **CURRENTLY DISABLED**. This one changes the type declaration generation strategy to generate everything as `declare module` statements.
147
+
148
+ ### `rootFolder`
149
+
150
+ Root folder relative to which path calculation will be happening. May be useful for some I guess.
151
+
152
+ _default:_ `process.cwd()`
153
+
154
+ ## What this plugin does NOT do
155
+
156
+ This plugin does not connect to the database or scan a schema folder, instead naively
157
+ parsing select or returning clauses to figure out potential response types.
158
+
159
+ In a real TypeScript project you should probably still roll your own types?
160
+
161
+ And JavaScript projects still get the benefits of completions.
162
+
163
+ ## SvelteKit use case
164
+
165
+ I primarily use this in a SvelteKit project. The only thing I modify is setting `typesFolder` to `'.svelte-kit/types'` directory, and adding a `".svelte-kit/types/**/*.sql.d.ts"` record to my `include` array in `tsconfig.json`.
166
+
167
+ ## License
168
+
169
+ MIT.
package/index.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { Plugin } from "vite";
2
+
3
+ export default function postgres(opts?: {
4
+ /**
5
+ * Path to a folder where all declaration are kept relative to `rootFolder`, i.e. a file at path `src/sql/module.sql` will have its `.d.ts` file generated into `${typesFolder}/src/sql/module.sql.d.ts`. Make sure you include this one in your `tsconfig.json`.
6
+ *
7
+ * @default "node_modules/@types/vite-plugin-postgres-import/"
8
+ */
9
+ typesFolder?: string;
10
+ /**
11
+ * **CURRENTLY DISABLED**. This one changes the type declaration generation strategy to generate everything as `declare module` statements.
12
+ */
13
+ modulePrefix?: string;
14
+ /**
15
+ * Root folder relative to which path calculation will be happening. May be useful for some I guess.
16
+ *
17
+ * @default process.cwd()
18
+ */
19
+ rootFolder?: string;
20
+ }): Plugin;
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "vite-plugin-postgres-import",
3
+ "description": "Vite plugin for importing SQL files as JS modules with sqlc-style annotations",
4
+ "version": "0.1.0",
5
+ "main": "plugin.js",
6
+ "type": "module",
7
+ "author": "SirKostya009",
8
+ "license": "MIT",
9
+ "repository": "github:sirkostya009/vite-plugin-postgres-import",
10
+ "files": [
11
+ "index.d.ts",
12
+ "parse.js"
13
+ ],
14
+ "keywords": [
15
+ "vite",
16
+ "postgres",
17
+ "import",
18
+ "sql",
19
+ "sqlc"
20
+ ],
21
+ "devDependencies": {
22
+ "vite": "^6"
23
+ },
24
+ "peerDependencies": {
25
+ "pg": "*"
26
+ },
27
+ "engines": {
28
+ "node": ">=22.0.0"
29
+ }
30
+ }
package/parse.js ADDED
@@ -0,0 +1,204 @@
1
+ const annotationRegex = /--\s*name:\s*(?<name>[a-zA-Z][\w_]*)\s*(?<tags>(:\w+\s*)*)?\r?\n/g;
2
+
3
+ export function* parseModule(/** @type {string} */ sql) {
4
+ annotationRegex.lastIndex = 0;
5
+
6
+ /** @type {RegExpMatchArray[]} */
7
+ const matches = sql.matchAll(annotationRegex).toArray();
8
+
9
+ for (let i = 0; i < matches.length; ++i) {
10
+ const rema = matches[i];
11
+ const [first, ...rest] = sql
12
+ .substring(rema.index, i + 1 < matches.length ? matches[i + 1].index : sql.length)
13
+ .split(";")
14
+ .map((s) => s.trim())
15
+ .filter(Boolean);
16
+ if (rest.length > 0) {
17
+ const firstMeta = metadata(first);
18
+ yield [firstMeta, ...rest.map((r) => metadata(r, firstMeta))];
19
+ } else {
20
+ yield metadata(first);
21
+ }
22
+ }
23
+ }
24
+
25
+ function metadata(/** @type {string} */ s, /** @type {ReturnType<typeof metadata>} */ firstMeta = undefined) {
26
+ annotationRegex.lastIndex = 0;
27
+ const match = firstMeta ? /--\s*(?<tags>(:\w+\s*)*)\r?\n/.exec(s) : annotationRegex.exec(s);
28
+ const meta = match?.groups;
29
+ const query = s.substring(match[0].length).trim();
30
+
31
+ return {
32
+ name: firstMeta?.name || meta?.name,
33
+ execution: /:one|:many|:execrows/.exec(meta?.tags)?.[0] || ":execresult",
34
+ prepared: meta?.tags?.includes(":prepare"),
35
+ mode: /:cursor|:iterable/.exec(meta?.tags)?.[0],
36
+ rowArray: meta?.tags?.includes(":array"),
37
+ query,
38
+ params: new Set(query.matchAll(/(?<![\w_\\:]):[\w_]+/g).map((m) => m?.[0]?.substring(1))),
39
+ selectFields: selectList(/(with.*\))?\s*select\s+(?<select>.*)/ms.exec(query)?.groups?.select)
40
+ .map((s) => s.trim())
41
+ .map((s) => {
42
+ while (s.startsWith("(") && s.endsWith(")")) {
43
+ // unwrap
44
+ s = s.substring(1, s.length - 1).trim();
45
+ }
46
+ const gotDatAs = /as ([_\w"]+)$/.exec(s)?.[1];
47
+ if (gotDatAs) return gotDatAs.endsWith('"') && gotDatAs.includes(" ") ? `'${gotDatAs}'` : gotDatAs;
48
+ const uncCall = /^([\w_]+)[\(\[].*[\)\]]$/.exec(s)?.[1];
49
+ if (uncCall) return uncCall;
50
+ const subselect = /^select\s+([\w_]+)[,]?.*$/.exec(s)?.[1];
51
+ if (subselect) return subselect;
52
+ const word = /(^|\.)[a-zA-Z]+$/.exec(s)?.[0];
53
+ if (word) return word[0] === "." ? word.substring(1) : word;
54
+ const star = /^\*$/.exec(s)?.[0];
55
+ if (star) return "[column: string]";
56
+ return '"?column?"'; // ???
57
+ })
58
+ .toArray(),
59
+ returningClause: /(with.*)?(update|delete|insert).*returning\s+(?<returning>.*)$/
60
+ .exec(query)
61
+ ?.groups?.returning?.split(",")
62
+ ?.filter(Boolean),
63
+ };
64
+
65
+ function* selectList(/** @type {string=} */ select) {
66
+ if (!select) return;
67
+ let index = 0;
68
+ let nestingLevel = 0;
69
+ let inString = null;
70
+ for (const token of select.matchAll(/([:\w_]+)|[\(\)'("")]|[,]|\*/g)) {
71
+ if (token[0] === inString) inString = null;
72
+ else if (token[0] === "'" || token[0] === "$$") inString = token[0];
73
+ if (token[0] === ")") nestingLevel--;
74
+ else if (token[0] === "(") nestingLevel++;
75
+ else if (token[0] === "," && nestingLevel === 0 && !inString) {
76
+ yield select.substring(index, token.index + token[0].length - 1);
77
+ index = token.index + token[0].length + 1;
78
+ } else if (token[0] === "from" && nestingLevel === 0 && !inString) {
79
+ yield select.substring(index, token.index);
80
+ return;
81
+ }
82
+ }
83
+ yield select.substring(index);
84
+ }
85
+ }
86
+
87
+ export function codegen(
88
+ /** @type {Iterable<ReturnType<typeof metadata> | ReturnType<typeof metadata>[]>} */ modules,
89
+ /** @type {string} */ filename,
90
+ /** @type {string} */ modulePrefix
91
+ ) {
92
+ let dts = [
93
+ // `declare module '${modulePrefix}${filename}.sql' {`
94
+ `import type { Pool, ClientBase, QueryResultRow, QueryResult, QueryArrayResult } from 'pg';`,
95
+ ];
96
+ let js = [`import { escapeLiteral } from 'pg';`];
97
+
98
+ for (let module of modules) {
99
+ module = Array.isArray(module)
100
+ ? {
101
+ ...module[0],
102
+ query: module.flatMap((m) => m.query).join(";\n\n"),
103
+ params: new Set(module.flatMap((m) => [...m.params])),
104
+ execution: module.map((m) => m.execution),
105
+ returnSymbols: module.map((m) => (m.returningClause?.length ? m.returningClause : m.selectFields)),
106
+ multiStatement: true,
107
+ }
108
+ : {
109
+ ...module,
110
+ execution: [module.execution],
111
+ returnSymbols: [module.returningClause?.length ? module.returningClause : module.selectFields],
112
+ multiStatement: "",
113
+ };
114
+
115
+ if (!module.rowArray) {
116
+ module.returnSymbols = module.returnSymbols.map((rs) => [...new Set(rs)]);
117
+ }
118
+
119
+ const keys = module.params
120
+ .values()
121
+ .map((k) => `'${k}'`)
122
+ .toArray()
123
+ .join(" | ");
124
+
125
+ dts.push(`/**
126
+ * ${"```"}sql
127
+ ${module.query}
128
+ * ${"```"}
129
+ */
130
+ export function ${module.name}<${module.returnSymbols
131
+ .map((r, i) =>
132
+ module.rowArray
133
+ ? `R${i + 1} extends any[] = ${
134
+ r.find((k) => k.startsWith("[column: string]"))
135
+ ? `unknown[]`
136
+ : `[ ${r?.map(() => `unknown`)?.join(", ") ?? ""} ]`
137
+ }`
138
+ : `R${i + 1} extends QueryResultRow = {${r.length > 3 ? "\n\t" : " "}${
139
+ r?.map((r) => `${r}: unknown`)?.join(r.length > 3 ? ";\n\t" : "; ") ?? ""
140
+ }${r.length > 3 ? "\n" : " "}}`
141
+ )
142
+ .join(", ")}>(
143
+ tx: Pool | ClientBase | Promise<ClientBase>,${keys.length ? `\n\tparams: Record<${keys}, unknown>` : ``}
144
+ ): Promise<${module.multiStatement && "["}${module.returnSymbols
145
+ .map((_, i) =>
146
+ module.execution[i] === ":execresult"
147
+ ? `Query${module.rowArray ? "Array" : ""}Result<R${i + 1}>`
148
+ : module.execution[i] === ":one"
149
+ ? `R${i + 1}`
150
+ : module.execution[i] === ":many"
151
+ ? `R${i + 1}[]`
152
+ : module.execution[i] === ":execrows"
153
+ ? `number`
154
+ : "unknown"
155
+ )
156
+ .join(", ")}${module.multiStatement && "]"}>;`);
157
+
158
+ const paramsString = module.params
159
+ .values()
160
+ .reduce((curr, p) => [...curr, p], [])
161
+ .join();
162
+
163
+ module.query = module.query.replaceAll("`", "\\`");
164
+
165
+ module.params.values().forEach(
166
+ (param, i) =>
167
+ (module.query = module.query.replaceAll(
168
+ new RegExp(`(?<![\w_]):${param}(?![\w_])`, "gi"),
169
+ module.multiStatement ? `\${escapeLiteral(${param})}` : `$${i + 1}` // the escapists
170
+ ))
171
+ );
172
+
173
+ if (module.prepared && module.execution.size > 1) {
174
+ console.warn(
175
+ "Postgres does not support preparing multi-statement queries. You will get an error, just sayin'"
176
+ );
177
+ }
178
+
179
+ js.push(
180
+ `export const ${module.name} = async (tx, { ${paramsString} } = {}) => (await tx).query({
181
+ ${module.prepared ? `name: "${module.name}",` : ""}
182
+ text: \`${module.multiStatement ? module.query : module.query}\`,
183
+ values: [ ${module.multiStatement || paramsString} ],
184
+ ${module.rowArray ? `rowMode: "array",` : ""}
185
+ }).then((${module.multiStatement && "["}${module.returnSymbols.map((_, i) => `r${i + 1}`).join()}${
186
+ module.multiStatement && "]"
187
+ }) => ${module.multiStatement && "["}${module.returnSymbols
188
+ .map(
189
+ (_, i) =>
190
+ `r${i + 1}` +
191
+ (module.execution[i] === ":one"
192
+ ? `.rows[0]`
193
+ : module.execution[i] === ":many"
194
+ ? `.rows`
195
+ : module.execution[i] === ":execrows"
196
+ ? `.rowCount`
197
+ : "")
198
+ )
199
+ .join()}${module.multiStatement && "]"});`
200
+ );
201
+ }
202
+
203
+ return { js: js.join("\n"), dts: dts.join("\n\n") + "\n" };
204
+ }
package/plugin.js ADDED
@@ -0,0 +1,53 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { codegen, parseModule } from "./parse.js";
4
+
5
+ /** @returns {import('vite').Plugin} */
6
+ export default function postgres({
7
+ typesFolder = "node_modules/@types/vite-plugin-postgres-import/",
8
+ modulePrefix = "",
9
+ rootFolder = process.cwd(),
10
+ } = {}) {
11
+ return {
12
+ name: "vite-plugin-sql-postgres",
13
+ resolveId(id) {
14
+ if (id.endsWith(".sql")) {
15
+ return id;
16
+ }
17
+ },
18
+ load,
19
+ async configureServer(server) {
20
+ server.watcher.on("add", load);
21
+
22
+ await walkdir(rootFolder);
23
+
24
+ async function walkdir(/** @type {string} */ p) {
25
+ for await (const entry of await fs.opendir(p)) {
26
+ if (entry.isFile()) {
27
+ await load(path.relative(rootFolder, path.join(entry.parentPath, entry.name)));
28
+ } else if (entry.isDirectory()) {
29
+ await walkdir(path.join(entry.parentPath, entry.name));
30
+ }
31
+ }
32
+ }
33
+ },
34
+ handleHotUpdate({ modules }) {
35
+ return modules;
36
+ },
37
+ };
38
+
39
+ async function load(/** @type {string} */ id) {
40
+ if (!id.endsWith(".sql")) return null;
41
+ const sql = await fs.readFile(id, "utf8");
42
+
43
+ const filename = path.basename(id, ".sql");
44
+
45
+ const { js, dts } = codegen(parseModule(sql), filename, modulePrefix);
46
+
47
+ const dtsFolder = path.join(typesFolder, path.relative(rootFolder, path.dirname(id)));
48
+ await fs.mkdir(dtsFolder, { recursive: true });
49
+ await fs.writeFile(path.join(dtsFolder, filename + ".sql.d.ts"), dts);
50
+
51
+ return js;
52
+ }
53
+ }