kern-db 0.0.0-stage → 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ilya Semenov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # kern-db
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ PostgreSQL database layer with ambient transactions, typed SQL queries, and test transactions.
4
+ It is the database layer of [kern-orm](https://github.com/IlyaSemenov/kern-orm), and it works without the ORM.
5
+
6
+ kern-db is in early development, and the API changes between minor versions.
7
+
8
+ See [Getting Started](https://ilyasemenov.github.io/kern-orm/database/getting-started) in the documentation.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install kern-db postgres
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ```ts
19
+ import { createDatabase } from "kern-db"
20
+ import { postgresJsDriver } from "kern-db/postgres-js"
21
+ import * as t from "kern-db/types"
22
+ import postgres from "postgres"
23
+
24
+ const database = createDatabase({
25
+ driver: postgresJsDriver(postgres(process.env.DATABASE_URL!)),
26
+ })
27
+
28
+ // Queries in the callback, including in called functions, join the transaction.
29
+ await database.transaction(async () => {
30
+ const id = await database.query`INSERT INTO form (name) VALUES (${"Survey"}) RETURNING id`.get(
31
+ t.uuid,
32
+ )
33
+ await database.query`UPDATE form SET published = true WHERE id = ${id}`
34
+ })
35
+ ```
@@ -0,0 +1,77 @@
1
+ import { o as defineType } from "./bytea-DNZ_ftio.mjs";
2
+ // src/type/builtins/array.ts
3
+ /**
4
+ * Creates a type of one-dimensional arrays of `element` values.
5
+ *
6
+ * A `NULL` element decodes to `null`; a nullable `element` type, such as `array(text.nullable())`, types such elements.
7
+ * Elements are separated by commas, as in arrays of all built-in types; a custom type with another delimiter, such as `box`, is not supported.
8
+ */
9
+ function array(element) {
10
+ const encodeElement = (value) => value === null ? null : element.encode(value);
11
+ return defineType({
12
+ sqlType: `${element.sqlType}[]`,
13
+ castType: `${element.castType}[]`
14
+ }).transform({
15
+ decode(text) {
16
+ const values = parseArray(text);
17
+ for (let index = 0; index < values.length; index++) {
18
+ const value = values[index];
19
+ values[index] = value === null ? null : element.decode(value);
20
+ }
21
+ return values;
22
+ },
23
+ encode: (values) => formatArray(values, encodeElement)
24
+ });
25
+ }
26
+ /** Parses a one-dimensional array literal, such as `{a,"b c",NULL}`, into the text representations of its elements. */
27
+ function parseArray(text) {
28
+ const start = text.startsWith("[") ? text.indexOf("=") + 1 : 0;
29
+ if (text[start] !== "{" || !text.endsWith("}")) throw new Error(`Unsupported array value "${text}"`);
30
+ const elements = [];
31
+ const end = text.length - 1;
32
+ if (start + 1 === end) return elements;
33
+ let index = start + 1;
34
+ while (true) {
35
+ if (text[index] === "{") throw new Error("Multidimensional arrays are not supported");
36
+ if (text[index] === "\"") {
37
+ let element = "";
38
+ index++;
39
+ while (index < end && text[index] !== "\"") {
40
+ if (text[index] === "\\") {
41
+ index++;
42
+ if (index === end) break;
43
+ }
44
+ element += text[index];
45
+ index++;
46
+ }
47
+ if (index === end) throw new Error(`Unterminated quoted element in array value "${text}"`);
48
+ elements.push(element);
49
+ index++;
50
+ } else {
51
+ let next = text.indexOf(",", index);
52
+ if (next === -1) next = end;
53
+ if (next === index) throw new Error(`Malformed array value "${text}"`);
54
+ const element = text.slice(index, next);
55
+ elements.push(element === "NULL" ? null : element);
56
+ index = next;
57
+ }
58
+ if (index === end) return elements;
59
+ if (text[index] !== ",") throw new Error(`Malformed array value "${text}"`);
60
+ index++;
61
+ }
62
+ }
63
+ /**
64
+ * Formats `values` as an array literal, such as `{"a","b c",NULL}`, of the text representations that `encodeElement` returns.
65
+ *
66
+ * It quotes every element other than `NULL`, so that it needs no scan for the characters that PostgreSQL requires to quote.
67
+ */
68
+ function formatArray(values, encodeElement) {
69
+ let text = "{";
70
+ for (let index = 0; index < values.length; index++) text += `${index === 0 ? "" : ","}${formatArrayElement(encodeElement(values[index]))}`;
71
+ return `${text}}`;
72
+ }
73
+ /** Formats the text representation of an array element, quoting it unless it is `NULL`. */
74
+ function formatArrayElement(element) {
75
+ return element === null ? "NULL" : `"${element.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
76
+ }
77
+ export { formatArray as n, array as t };
@@ -0,0 +1,4 @@
1
+ import { B as toMissingResult, D as encodeParameter, E as bindParameter, I as createFieldDecodeError, L as createResultDecodeError, N as ResultMode, R as isRecordKey, S as renderFragment, T as assertUntypedValue, V as toValueRows, _ as ParameterBinder, a as SqlQuery, c as StatementSource, l as startSqlQuery, v as SqlFragment, z as takeOnlyRow } from "./query-B8QCiInv.mjs";
2
+ /** Quotes `name` as a PostgreSQL identifier, which keeps its case and any characters in it. */
3
+ export declare function quoteIdentifier(name: string): string;
4
+ export { type ParameterBinder, type ResultMode, SqlFragment, SqlQuery, type StatementSource, assertUntypedValue, bindParameter, createFieldDecodeError, createResultDecodeError, encodeParameter, isRecordKey, renderFragment, startSqlQuery, takeOnlyRow, toMissingResult, toValueRows };
@@ -0,0 +1 @@
1
+ export { d as SqlFragment, t as SqlQuery, v as assertUntypedValue, y as bindParameter, a as createFieldDecodeError, o as createResultDecodeError, b as encodeParameter, s as isRecordKey, x as quoteIdentifier, g as renderFragment, n as startSqlQuery, c as takeOnlyRow, l as toMissingResult, u as toValueRows } from "./query-g8iaj0Fx.mjs";
@@ -0,0 +1,92 @@
1
+ // src/type/type.ts
2
+ /** Runtime mark of types, which tells them apart from other objects with the same members. */
3
+ const typeBrand = Symbol("kern-db.type");
4
+ /**
5
+ * Defines a type whose values are the PostgreSQL text representations as they are.
6
+ *
7
+ * `transform` converts them to other values, such as `number[]` for `vector`.
8
+ */
9
+ function defineType(options) {
10
+ if (isType(options)) throw new TypeError("defineType() of kern-db takes options, not a type");
11
+ if (options.castType === void 0 && options.sqlType.includes("(")) throw new TypeError(`Define the type parameters of "${options.sqlType}" using withParameters(), or set castType`);
12
+ return createType({
13
+ sqlType: options.sqlType,
14
+ castType: options.castType ?? options.sqlType,
15
+ encode: keepText,
16
+ decode: keepText,
17
+ isNullable: false,
18
+ formatSqlType: void 0
19
+ });
20
+ }
21
+ /** Tells whether `value` is a type, including an object that copies the members of one. */
22
+ function isType(value) {
23
+ return typeof value === "object" && value !== null && typeBrand in value;
24
+ }
25
+ function createType(state) {
26
+ const derive = (changes) => createType({
27
+ ...state,
28
+ ...changes
29
+ });
30
+ const { formatSqlType } = state;
31
+ const type = Object.freeze({
32
+ [typeBrand]: true,
33
+ sqlType: state.sqlType,
34
+ castType: state.castType,
35
+ isNullable: state.isNullable,
36
+ encode: state.encode,
37
+ decode: state.decode,
38
+ transform: ({ decode, encode }) => derive({
39
+ encode: encode ? (value) => state.encode(encode(value)) : state.encode,
40
+ decode: (text) => decode(state.decode(text))
41
+ }),
42
+ withParameters: (format) => derive({ formatSqlType: format }),
43
+ ...formatSqlType && { with: (...parameters) => derive({ sqlType: formatSqlType(...parameters) }) },
44
+ nullable: () => derive({ isNullable: true }),
45
+ of: () => type
46
+ });
47
+ return type;
48
+ }
49
+ /** Encodes and decodes a value that is its PostgreSQL text representation. */
50
+ function keepText(text) {
51
+ return text;
52
+ }
53
+ // src/type/builtins/boolean.ts
54
+ /** `boolean` values. */
55
+ const boolean = /* @__PURE__ */ defineType({ sqlType: "boolean" }).transform({
56
+ decode: decodeBoolean,
57
+ encode: encodeBoolean
58
+ });
59
+ /** Converts a Boolean value to its PostgreSQL text representation. */
60
+ function encodeBoolean(value) {
61
+ return value ? "t" : "f";
62
+ }
63
+ /** Converts the PostgreSQL text representation of a Boolean value, `t` or `f`, to the value. */
64
+ function decodeBoolean(text) {
65
+ return text === "t";
66
+ }
67
+ // src/type/builtins/bytea.ts
68
+ /** Binary data; PostgreSQL represents it in hex, which requires the default `bytea_output` setting. */
69
+ const bytea = /* @__PURE__ */ defineType({ sqlType: "bytea" }).transform({
70
+ decode: decodeBytea,
71
+ encode: encodeBytea
72
+ });
73
+ const hexDigits = "0123456789abcdef";
74
+ /** Encodes bytes as a hex `bytea` literal, such as `\\x00ff`. */
75
+ function encodeBytea(bytes) {
76
+ let text = "\\x";
77
+ for (const byte of bytes) text += hexDigits[byte >> 4] + hexDigits[byte & 15];
78
+ return text;
79
+ }
80
+ /** Decodes a hex `bytea` literal into bytes. */
81
+ function decodeBytea(text) {
82
+ if (!text.startsWith("\\x")) throw new Error("Unsupported bytea value; kern-db expects bytea_output hex");
83
+ const bytes = new Uint8Array((text.length - 2) / 2);
84
+ for (let index = 0; index < bytes.length; index++) bytes[index] = readHexDigit(text, 2 + index * 2) << 4 | readHexDigit(text, 3 + index * 2);
85
+ return bytes;
86
+ }
87
+ /** Reads the hex digit at `index`, in either case. */
88
+ function readHexDigit(text, index) {
89
+ const code = text.charCodeAt(index);
90
+ return code <= 57 ? code - 48 : (code | 32) - 87;
91
+ }
92
+ export { encodeBoolean as a, decodeBoolean as i, encodeBytea as n, defineType as o, boolean as r, isType as s, bytea as t };