@pgxsinkit/pgwasm
Version:
84 lines (79 loc) • 2.79 kB
JavaScript
// @bun
import {
parseType
} from "./chunk-d82gg1hx.js";
import {
RowDescriptionMessage,
ParameterDescriptionMessage,
CommandCompleteMessage,
DataRowMessage
} from "./chunk-74gcrk47.js";
// packages/pgwasm/src/core/names.ts
function toPostgresName(input) {
if (input.startsWith('"') && input.endsWith('"') && input.length >= 2) {
return input.slice(1, -1);
}
return input.toLowerCase();
}
function quoteIdentifier(name) {
return `"${name.replaceAll('"', '""')}"`;
}
function randomId() {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
// packages/pgwasm/src/core/parse.ts
function parseResults(messages, defaultParsers, options, blob) {
const resultSets = [];
let current = { rows: [], fields: [] };
let affectedRows = 0;
const parsers = { ...defaultParsers, ...options?.parsers };
for (const message of messages) {
if (message instanceof RowDescriptionMessage) {
current.fields = message.fields.map((field) => ({ name: field.name, dataTypeID: field.dataTypeID }));
} else if (message instanceof DataRowMessage) {
const fields = current.fields;
const typeOf = (index) => fields[index]?.dataTypeID ?? 0;
if (options?.rowMode === "array") {
current.rows.push(message.fields.map((value, index) => parseType(value, typeOf(index), parsers)));
} else {
const row = {};
message.fields.forEach((value, index) => {
row[fields[index]?.name ?? String(index)] = parseType(value, typeOf(index), parsers);
});
current.rows.push(row);
}
} else if (message instanceof CommandCompleteMessage) {
const parts = message.text.split(" ");
const command = parts[0] ?? "";
const rowCount = Number.parseInt(parts[parts.length - 1] ?? "", 10);
switch (command) {
case "INSERT":
case "UPDATE":
case "DELETE":
case "COPY":
case "MERGE":
affectedRows += rowCount;
break;
}
const result = { ...current, command, affectedRows };
if (!Number.isNaN(rowCount))
result.rowCount = rowCount;
if (blob)
result.blob = blob;
resultSets.push(result);
current = { rows: [], fields: [] };
}
}
if (resultSets.length === 0) {
resultSets.push({ affectedRows: 0, rows: [], fields: [] });
}
return resultSets;
}
function parseDescribeStatementResults(messages) {
const message = messages.find((msg) => msg instanceof ParameterDescriptionMessage);
return message ? message.dataTypeIDs : [];
}
export { toPostgresName, quoteIdentifier, randomId, parseResults, parseDescribeStatementResults };
//# debugId=C407675D55809A7C64756E2164756E21