@happyvertical/sql 0.112.0 → 0.112.2
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/AGENT.md +65 -3
- package/README.md +146 -19
- package/dist/aggregate-expression.d.ts +77 -3
- package/dist/aggregate-expression.d.ts.map +1 -1
- package/dist/aggregate.d.ts +3 -2
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/chunks/{duckdb-CpeXdf0i.js → duckdb-DCV4JFWK.js} +23 -52
- package/dist/chunks/duckdb-DCV4JFWK.js.map +1 -0
- package/dist/chunks/{postgres-dialect-DIy5f5YR.js → postgres-dialect-CaNhva-C.js} +28 -328
- package/dist/chunks/postgres-dialect-CaNhva-C.js.map +1 -0
- package/dist/chunks/query-Dz0TZ0pY.js +970 -0
- package/dist/chunks/query-Dz0TZ0pY.js.map +1 -0
- package/dist/chunks/{schema-manager-tfASrb_b.js → schema-manager-psLzQ2yh.js} +471 -18
- package/dist/chunks/schema-manager-psLzQ2yh.js.map +1 -0
- package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js → sqlite-connection-cache-BycfrYfi.js} +2 -2
- package/dist/chunks/{sqlite-connection-cache-C_7rVisQ.js.map → sqlite-connection-cache-BycfrYfi.js.map} +1 -1
- package/dist/chunks/{sqlite-BdM-nAQD.js → sqlite-nNhv0FMq.js} +22 -22
- package/dist/chunks/sqlite-nNhv0FMq.js.map +1 -0
- package/dist/chunks/{sqlite-native-DngobJtv.js → sqlite-native-CZGNm9zh.js} +40 -37
- package/dist/chunks/sqlite-native-CZGNm9zh.js.map +1 -0
- package/dist/doctor.d.ts.map +1 -1
- package/dist/duckdb.d.ts.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +44 -77
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts.map +1 -1
- package/dist/pglite.js +2 -2
- package/dist/query.d.ts +3 -0
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +3 -3
- package/dist/schema-manager.d.ts.map +1 -1
- package/dist/shared/alter-utils.d.ts +43 -7
- package/dist/shared/alter-utils.d.ts.map +1 -1
- package/dist/shared/duckdb-schema-utils.d.ts.map +1 -1
- package/dist/shared/postgres-dialect.d.ts.map +1 -1
- package/dist/shared/types.d.ts +1 -0
- package/dist/shared/types.d.ts.map +1 -1
- package/dist/shared/utils.d.ts +12 -1
- package/dist/shared/utils.d.ts.map +1 -1
- package/dist/sqlite-native.d.ts.map +1 -1
- package/dist/sqlite.d.ts.map +1 -1
- package/metadata.json +4 -4
- package/package.json +4 -4
- package/dist/chunks/duckdb-CpeXdf0i.js.map +0 -1
- package/dist/chunks/postgres-dialect-DIy5f5YR.js.map +0 -1
- package/dist/chunks/query-i6IIkNhF.js +0 -564
- package/dist/chunks/query-i6IIkNhF.js.map +0 -1
- package/dist/chunks/schema-manager-tfASrb_b.js.map +0 -1
- package/dist/chunks/sqlite-BdM-nAQD.js.map +0 -1
- package/dist/chunks/sqlite-native-DngobJtv.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as
|
|
1
|
+
import { C as validateColumnNames, _ as quoteLiteralIdentifier, d as escapeStringLiteral, g as quoteDuckDBColumnName, i as formatDbError, n as buildAdapterWhere, o as raw, r as buildWhere, s as resolveInsertColumns, t as DatabaseSchemaManager, u as wrapDatabaseError } from "./chunks/schema-manager-psLzQ2yh.js";
|
|
2
|
+
import { a as NestedTransactionError, c as bucketExpr, d as renderExpression, i as validateColumnName, l as buildAggregate, n as syncSchema, o as resolveSchemas, r as tableExists, s as convertUniqueIndexesToInlineConstraints, t as escapeSqlValue, u as ExpressionError } from "./chunks/query-Dz0TZ0pY.js";
|
|
3
3
|
import { a as dropPostgresDatabase, c as postgresEnvFromUrl, i as databaseNameFromUrl, l as redactDatabaseUrl, n as assertCanImportDatabase, o as dumpPostgresDatabase, r as createPostgresDatabase, s as isLocalDatabaseUrl, t as assertCanExportDatabase, u as restorePostgresDatabase } from "./chunks/postgres-cli-DzZcXSIG.js";
|
|
4
|
-
import {
|
|
4
|
+
import { a as createVectorCapabilities, c as createTransactionLock, d as validateDatabaseCacheOptions, i as createTransactionErrorTracker, l as ConnectionCache, n as createGetTableSchema, o as normalizePostgresRawQuery, r as createPostgresDialect, t as createAlterTable, u as enableCachedValidation } from "./chunks/postgres-dialect-CaNhva-C.js";
|
|
5
5
|
import { n as createDuckDBResourceCloser, r as throwWithDuckDBCleanup, t as serializeDuckDBStatements } from "./chunks/duckdb-statement-queue-BJ6-PQRr.js";
|
|
6
6
|
import { t as redactDatabaseUrl$1 } from "./chunks/redact-database-url-CfMDvSdy.js";
|
|
7
7
|
import { DatabaseError, loadEnvConfig } from "@happyvertical/utils";
|
|
@@ -107,12 +107,12 @@ function checkUniqueColumn(spec) {
|
|
|
107
107
|
return async ({ db, tables }) => {
|
|
108
108
|
if (!tables.has(spec.table)) return [];
|
|
109
109
|
return (await db.query(`
|
|
110
|
-
SELECT ${
|
|
111
|
-
FROM ${
|
|
112
|
-
WHERE NULLIF(trim(${
|
|
113
|
-
GROUP BY ${
|
|
110
|
+
SELECT ${quoteLiteralIdentifier(spec.column)} AS value, count(*)::text AS count
|
|
111
|
+
FROM ${quoteLiteralIdentifier(spec.table)}
|
|
112
|
+
WHERE NULLIF(trim(${quoteLiteralIdentifier(spec.column)}::text), '') IS NOT NULL
|
|
113
|
+
GROUP BY ${quoteLiteralIdentifier(spec.column)}
|
|
114
114
|
HAVING count(*) > 1
|
|
115
|
-
ORDER BY count DESC, ${
|
|
115
|
+
ORDER BY count DESC, ${quoteLiteralIdentifier(spec.column)}
|
|
116
116
|
`)).rows.map((row) => ({
|
|
117
117
|
level: "fail",
|
|
118
118
|
message: `Duplicate ${spec.label} "${String(row.value)}" in ${spec.table} (${countValueFromRow(row.count)} rows).`
|
|
@@ -131,11 +131,11 @@ function checkRelationship(spec) {
|
|
|
131
131
|
const parentColumn = spec.parentColumn ?? "id";
|
|
132
132
|
const orphanCount = countValueFromRow((await db.query(`
|
|
133
133
|
SELECT count(*)::text AS count
|
|
134
|
-
FROM ${
|
|
135
|
-
LEFT JOIN ${
|
|
136
|
-
ON parent.${
|
|
137
|
-
WHERE NULLIF(trim(child.${
|
|
138
|
-
AND parent.${
|
|
134
|
+
FROM ${quoteLiteralIdentifier(spec.childTable)} child
|
|
135
|
+
LEFT JOIN ${quoteLiteralIdentifier(spec.parentTable)} parent
|
|
136
|
+
ON parent.${quoteLiteralIdentifier(parentColumn)} = child.${quoteLiteralIdentifier(spec.childColumn)}
|
|
137
|
+
WHERE NULLIF(trim(child.${quoteLiteralIdentifier(spec.childColumn)}::text), '') IS NOT NULL
|
|
138
|
+
AND parent.${quoteLiteralIdentifier(parentColumn)} IS NULL
|
|
139
139
|
`)).rows[0]?.count);
|
|
140
140
|
if (orphanCount === "0") return [];
|
|
141
141
|
return [{
|
|
@@ -148,9 +148,6 @@ async function listPublicTables(db) {
|
|
|
148
148
|
const result = await db.query("SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename");
|
|
149
149
|
return new Set(result.rows.map((row) => String(row.tablename ?? "")));
|
|
150
150
|
}
|
|
151
|
-
function quoteIdentifier(value) {
|
|
152
|
-
return `"${value.replace(/"/gu, "\"\"")}"`;
|
|
153
|
-
}
|
|
154
151
|
function countValueFromRow(value) {
|
|
155
152
|
if (typeof value === "string") return value;
|
|
156
153
|
if (typeof value === "number" || typeof value === "bigint") return String(value);
|
|
@@ -463,7 +460,7 @@ async function loadJSONTables(connection, dataDir, providedSchemas = {}, pending
|
|
|
463
460
|
}
|
|
464
461
|
else {
|
|
465
462
|
if (eagerLoadTables) try {
|
|
466
|
-
await connection.run(`CREATE TABLE IF NOT EXISTS
|
|
463
|
+
await connection.run(`CREATE TABLE IF NOT EXISTS ${quoteDuckDBColumnName(tableName, true)} AS SELECT * FROM read_json_auto('${escapeStringLiteral(filePath)}')`);
|
|
467
464
|
inferredSchemaTables.add(tableName);
|
|
468
465
|
console.log(`[json-adapter] Eagerly created ${tableName} with inferred schema (no UNIQUE constraints)`);
|
|
469
466
|
} catch (error) {
|
|
@@ -556,7 +553,7 @@ async function createTableFromSchema(connection, tableName, schema) {
|
|
|
556
553
|
await connection.run(createTableSQL);
|
|
557
554
|
let existingColumns = /* @__PURE__ */ new Set();
|
|
558
555
|
try {
|
|
559
|
-
const columns = (await connection.runAndReadAll(`DESCRIBE ${tableName}`)).getRowObjects();
|
|
556
|
+
const columns = (await connection.runAndReadAll(`DESCRIBE ${quoteDuckDBColumnName(tableName, true)}`)).getRowObjects();
|
|
560
557
|
existingColumns = new Set(columns.map((col) => col.column_name.toLowerCase()));
|
|
561
558
|
console.log(`[json-adapter] Created ${tableName} with schema:`, { columns: columns.map((col) => ({
|
|
562
559
|
name: col.column_name,
|
|
@@ -573,7 +570,7 @@ async function createTableFromSchema(connection, tableName, schema) {
|
|
|
573
570
|
if (!existingColumns.has(columnName)) {
|
|
574
571
|
const sqlType = fieldDef?.type || "TEXT";
|
|
575
572
|
try {
|
|
576
|
-
await connection.run(`ALTER TABLE ${tableName} ADD COLUMN
|
|
573
|
+
await connection.run(`ALTER TABLE ${quoteDuckDBColumnName(tableName, true)} ADD COLUMN ${quoteDuckDBColumnName(fieldName, true)} ${sqlType}`);
|
|
577
574
|
console.log(`[json-adapter] Added missing column '${fieldName}' (${sqlType}) to ${tableName}`);
|
|
578
575
|
} catch (alterError) {
|
|
579
576
|
console.warn(`[json-adapter] Could not add column '${fieldName}' to ${tableName}: ${alterError instanceof Error ? alterError.message : String(alterError)}`);
|
|
@@ -694,7 +691,8 @@ async function insertRecordsWithCast(connection, tableName, records) {
|
|
|
694
691
|
}
|
|
695
692
|
}).join(", ")})`;
|
|
696
693
|
}).join(", ");
|
|
697
|
-
const
|
|
694
|
+
const columnList = columnNames.map((name) => quoteDuckDBColumnName(name, true)).join(", ");
|
|
695
|
+
const sql = `INSERT INTO ${quoteDuckDBColumnName(tableName, true)} (${columnList}) VALUES ${placeholders}`;
|
|
698
696
|
try {
|
|
699
697
|
await connection.run(sql, values);
|
|
700
698
|
} catch (e) {
|
|
@@ -821,7 +819,7 @@ async function createJSONDatabase(options) {
|
|
|
821
819
|
}
|
|
822
820
|
}).join(", ")})`;
|
|
823
821
|
}).join(", ");
|
|
824
|
-
const sql = `INSERT INTO "${table}" (${keys.join(", ")}) VALUES ${placeholders}`;
|
|
822
|
+
const sql = `INSERT INTO "${table}" (${keys.map((key) => quoteDuckDBColumnName(key)).join(", ")}) VALUES ${placeholders}`;
|
|
825
823
|
try {
|
|
826
824
|
await connection.run(sql, values);
|
|
827
825
|
const affected = records.length;
|
|
@@ -849,7 +847,7 @@ async function createJSONDatabase(options) {
|
|
|
849
847
|
*/
|
|
850
848
|
const get = async (table, where) => {
|
|
851
849
|
validateTableName(table);
|
|
852
|
-
const { sql: whereClause, values } =
|
|
850
|
+
const { sql: whereClause, values } = buildAdapterWhere(where, 1, "json");
|
|
853
851
|
const sql = `SELECT * FROM "${table}" ${whereClause} LIMIT 1`;
|
|
854
852
|
try {
|
|
855
853
|
const rows = (await connection.runAndReadAll(sql, values)).getRowObjects();
|
|
@@ -873,7 +871,7 @@ async function createJSONDatabase(options) {
|
|
|
873
871
|
*/
|
|
874
872
|
const list = async (table, where) => {
|
|
875
873
|
validateTableName(table);
|
|
876
|
-
const { sql: whereClause, values } =
|
|
874
|
+
const { sql: whereClause, values } = buildAdapterWhere(where, 1, "json");
|
|
877
875
|
const sql = `SELECT * FROM "${table}" ${whereClause}`;
|
|
878
876
|
try {
|
|
879
877
|
return convertBigInts((await connection.runAndReadAll(sql, values)).getRowObjects());
|
|
@@ -903,8 +901,8 @@ async function createJSONDatabase(options) {
|
|
|
903
901
|
});
|
|
904
902
|
const keys = Object.keys(data);
|
|
905
903
|
validateColumnNames(keys);
|
|
906
|
-
const setClause = keys.map((key, idx) => `${key} = $${idx + 1}`).join(", ");
|
|
907
|
-
const { sql: whereClause, values: whereValues } =
|
|
904
|
+
const setClause = keys.map((key, idx) => `${quoteDuckDBColumnName(key)} = $${idx + 1}`).join(", ");
|
|
905
|
+
const { sql: whereClause, values: whereValues } = buildAdapterWhere(where, keys.length + 1, "json");
|
|
908
906
|
const dataValues = keys.map((key) => {
|
|
909
907
|
const value = data[key];
|
|
910
908
|
return value instanceof Date ? value.toISOString() : value;
|
|
@@ -949,16 +947,16 @@ async function createJSONDatabase(options) {
|
|
|
949
947
|
return `$${paramIdx.value++}`;
|
|
950
948
|
};
|
|
951
949
|
const executeNullAwareJSONUpsert = async (table, conflictColumns, data) => {
|
|
952
|
-
const conflictWhere = Object.fromEntries(conflictColumns.map((col) => [col, data[col]]));
|
|
953
|
-
if (!await get(table, conflictWhere)) return insert(table, data);
|
|
950
|
+
const conflictWhere = Object.fromEntries(conflictColumns.map((col) => [quoteDuckDBColumnName(col, true), data[col]]));
|
|
951
|
+
if (!await get(table, conflictWhere)) return insert(table, Object.fromEntries(Object.entries(data).map(([key, value]) => [quoteDuckDBColumnName(key, true), value])));
|
|
954
952
|
const keys = Object.keys(data);
|
|
955
953
|
const values = [];
|
|
956
954
|
const paramIdx = { value: 1 };
|
|
957
955
|
const assignments = keys.map((key) => {
|
|
958
956
|
const valueExpr = buildJSONValueExpression(data[key], values, paramIdx);
|
|
959
|
-
return
|
|
957
|
+
return `${quoteDuckDBColumnName(key, true)} = ${valueExpr}`;
|
|
960
958
|
});
|
|
961
|
-
const { sql: whereClause, values: whereValues } =
|
|
959
|
+
const { sql: whereClause, values: whereValues } = buildAdapterWhere(conflictWhere, paramIdx.value, "json");
|
|
962
960
|
const sql = `UPDATE "${table}" SET ${assignments.join(", ")} ${whereClause}`;
|
|
963
961
|
try {
|
|
964
962
|
await connection.run(sql, [...values, ...whereValues]);
|
|
@@ -1030,41 +1028,10 @@ async function createJSONDatabase(options) {
|
|
|
1030
1028
|
values.push(value);
|
|
1031
1029
|
paramIdx++;
|
|
1032
1030
|
}
|
|
1033
|
-
const
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
if (value === null) updateSetParts.push(`${key} = NULL`);
|
|
1038
|
-
else if (value === "" && typeof value === "string") {
|
|
1039
|
-
updateSetParts.push(`${key} = CAST($${paramIdx} AS TEXT)`);
|
|
1040
|
-
values.push(value);
|
|
1041
|
-
paramIdx++;
|
|
1042
|
-
} else if (value instanceof Date) {
|
|
1043
|
-
updateSetParts.push(`${key} = CAST($${paramIdx} AS TIMESTAMP)`);
|
|
1044
|
-
values.push(value.toISOString());
|
|
1045
|
-
paramIdx++;
|
|
1046
|
-
} else if (Array.isArray(value)) {
|
|
1047
|
-
updateSetParts.push(`${key} = CAST($${paramIdx} AS JSON)`);
|
|
1048
|
-
values.push(JSON.stringify(value));
|
|
1049
|
-
paramIdx++;
|
|
1050
|
-
} else if (typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype) {
|
|
1051
|
-
updateSetParts.push(`${key} = CAST($${paramIdx} AS JSON)`);
|
|
1052
|
-
values.push(JSON.stringify(value));
|
|
1053
|
-
paramIdx++;
|
|
1054
|
-
} else {
|
|
1055
|
-
updateSetParts.push(`${key} = $${paramIdx}`);
|
|
1056
|
-
values.push(value);
|
|
1057
|
-
paramIdx++;
|
|
1058
|
-
}
|
|
1059
|
-
}
|
|
1060
|
-
const conflict = conflictCols.map((col) => `"${escapeQuotedIdentifier(col)}"`).join(", ");
|
|
1061
|
-
const quotedKeys = keys.map((key) => `"${escapeQuotedIdentifier(key)}"`).join(", ");
|
|
1062
|
-
const quotedUpdateSetParts = keys.map((key, i) => {
|
|
1063
|
-
const part = updateSetParts[i];
|
|
1064
|
-
const valueExpr = part.substring(part.indexOf("=") + 1).trim();
|
|
1065
|
-
return `"${escapeQuotedIdentifier(key)}" = ${valueExpr}`;
|
|
1066
|
-
});
|
|
1067
|
-
const sql = `INSERT INTO "${table}" (${quotedKeys}) VALUES (${placeholders.join(", ")}) ON CONFLICT(${conflict}) DO UPDATE SET ${quotedUpdateSetParts.join(", ")}`;
|
|
1031
|
+
const updateIndex = { value: paramIdx };
|
|
1032
|
+
const quotedUpdateSetParts = keys.map((key) => `${quoteDuckDBColumnName(key, true)} = ${buildJSONValueExpression(record[key], values, updateIndex)}`);
|
|
1033
|
+
const conflict = conflictCols.map((col) => quoteDuckDBColumnName(col, true)).join(", ");
|
|
1034
|
+
const sql = `INSERT INTO "${table}" (${keys.map((key) => quoteDuckDBColumnName(key, true)).join(", ")}) VALUES (${placeholders.join(", ")}) ON CONFLICT(${conflict}) DO UPDATE SET ${quotedUpdateSetParts.join(", ")}`;
|
|
1068
1035
|
try {
|
|
1069
1036
|
await connection.run(sql, values);
|
|
1070
1037
|
if (writeStrategy === "immediate") await persistTableToJSON(table);
|
|
@@ -1126,7 +1093,7 @@ async function createJSONDatabase(options) {
|
|
|
1126
1093
|
writeStrategy
|
|
1127
1094
|
});
|
|
1128
1095
|
if (Object.keys(where).length === 0) throw new DatabaseError("DELETE requires at least one WHERE condition to prevent accidental deletion of all records", { table });
|
|
1129
|
-
const { sql: whereClause, values } =
|
|
1096
|
+
const { sql: whereClause, values } = buildAdapterWhere(where, 1, "json");
|
|
1130
1097
|
const sql = `DELETE FROM "${table}" ${whereClause}`;
|
|
1131
1098
|
try {
|
|
1132
1099
|
await connection.run(sql, values);
|
|
@@ -1159,7 +1126,7 @@ async function createJSONDatabase(options) {
|
|
|
1159
1126
|
const rows = (await connection.runAndReadAll(`SELECT COUNT(*) as count FROM "${table}"`)).getRowObjects();
|
|
1160
1127
|
return Number(rows[0]?.count) || 0;
|
|
1161
1128
|
}
|
|
1162
|
-
const { sql: whereClause, values } =
|
|
1129
|
+
const { sql: whereClause, values } = buildAdapterWhere(where, 1, "json");
|
|
1163
1130
|
const sql = `SELECT COUNT(*) as count FROM "${table}" ${whereClause}`;
|
|
1164
1131
|
const rows = (await connection.runAndReadAll(sql, values)).getRowObjects();
|
|
1165
1132
|
return Number(rows[0]?.count) || 0;
|
|
@@ -1216,12 +1183,12 @@ async function createJSONDatabase(options) {
|
|
|
1216
1183
|
}
|
|
1217
1184
|
const columnInfo = (await connection.runAndReadAll(`SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '${table}' ORDER BY ordinal_position`)).getRowObjects();
|
|
1218
1185
|
if (columnInfo.length === 0) {
|
|
1219
|
-
await connection.run(`COPY (SELECT * FROM "${table}") TO '${filePath}' (FORMAT JSON, ARRAY true)`);
|
|
1186
|
+
await connection.run(`COPY (SELECT * FROM "${table}") TO '${escapeStringLiteral(filePath)}' (FORMAT JSON, ARRAY true)`);
|
|
1220
1187
|
return;
|
|
1221
1188
|
}
|
|
1222
1189
|
const sql = `COPY (SELECT ${columnInfo.map(({ column_name, data_type }) => {
|
|
1223
1190
|
const upperType = data_type.toUpperCase();
|
|
1224
|
-
if (upperType === "JSON" || upperType.startsWith("STRUCT")) return
|
|
1191
|
+
if (upperType === "JSON" || upperType.startsWith("STRUCT")) return quoteDuckDBColumnName(column_name, true);
|
|
1225
1192
|
if ([
|
|
1226
1193
|
"DOUBLE",
|
|
1227
1194
|
"REAL",
|
|
@@ -1237,10 +1204,10 @@ async function createJSONDatabase(options) {
|
|
|
1237
1204
|
"UINTEGER",
|
|
1238
1205
|
"USMALLINT",
|
|
1239
1206
|
"UTINYINT"
|
|
1240
|
-
].some((t) => upperType.includes(t))) return
|
|
1241
|
-
if (upperType === "BOOLEAN" || upperType === "BOOL") return
|
|
1242
|
-
return `CAST(
|
|
1243
|
-
}).join(", ")} FROM "${table}") TO '${filePath}' (FORMAT JSON, ARRAY true)`;
|
|
1207
|
+
].some((t) => upperType.includes(t))) return quoteDuckDBColumnName(column_name, true);
|
|
1208
|
+
if (upperType === "BOOLEAN" || upperType === "BOOL") return quoteDuckDBColumnName(column_name, true);
|
|
1209
|
+
return `CAST(${quoteDuckDBColumnName(column_name, true)} AS TEXT) AS ${quoteDuckDBColumnName(column_name, true)}`;
|
|
1210
|
+
}).join(", ")} FROM "${table}") TO '${escapeStringLiteral(filePath)}' (FORMAT JSON, ARRAY true)`;
|
|
1244
1211
|
await connection.run(sql);
|
|
1245
1212
|
};
|
|
1246
1213
|
const persistTableToJSON = (table) => trackJSONSourceWrite(db, table, () => exportTableToJSON(connection, table, url));
|
|
@@ -1305,7 +1272,7 @@ async function createJSONDatabase(options) {
|
|
|
1305
1272
|
const { constants } = await import("node:fs");
|
|
1306
1273
|
await access(filePath, constants.F_OK);
|
|
1307
1274
|
console.log(`[json-adapter] Inferring schema for ${tableName} from JSON file`);
|
|
1308
|
-
await connection.run(`CREATE TABLE
|
|
1275
|
+
await connection.run(`CREATE TABLE ${quoteDuckDBColumnName(tableName, true)} AS SELECT * FROM read_json_auto('${escapeStringLiteral(filePath)}')`);
|
|
1309
1276
|
pendingJSONFiles.delete(tableName);
|
|
1310
1277
|
console.log(`[json-adapter] Created ${tableName} with inferred schema (no UNIQUE constraints)`);
|
|
1311
1278
|
} catch (error) {
|
|
@@ -1520,7 +1487,7 @@ async function createJSONDatabase(options) {
|
|
|
1520
1487
|
const createTableMatch = transformedDDL.match(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?(\w+)["']?/i);
|
|
1521
1488
|
const tableName = createTableMatch ? createTableMatch[1] : null;
|
|
1522
1489
|
if (tableName && inferredSchemaTables.has(tableName)) try {
|
|
1523
|
-
await connection.run(`DROP TABLE IF EXISTS
|
|
1490
|
+
await connection.run(`DROP TABLE IF EXISTS ${quoteDuckDBColumnName(tableName, true)}`);
|
|
1524
1491
|
inferredSchemaTables.delete(tableName);
|
|
1525
1492
|
console.log(`[json-adapter] Dropped inferred-schema table ${tableName} for schema upgrade`);
|
|
1526
1493
|
} catch (error) {
|
|
@@ -2367,8 +2334,8 @@ async function getDatabase(options = {}) {
|
|
|
2367
2334
|
if (!options.type && (options.url?.startsWith("file:") || options.url === ":memory:")) options.type = "sqlite";
|
|
2368
2335
|
if (options.type === "postgres") return (await Promise.resolve().then(() => postgres_exports)).getDatabase(options);
|
|
2369
2336
|
if (options.type === "pglite") return (await import("./pglite.js")).getDatabase(options);
|
|
2370
|
-
if (options.type === "sqlite") return (await import("./chunks/sqlite-
|
|
2371
|
-
if (options.type === "duckdb") return (await import("./chunks/duckdb-
|
|
2337
|
+
if (options.type === "sqlite") return (await import("./chunks/sqlite-nNhv0FMq.js")).getDatabase(options);
|
|
2338
|
+
if (options.type === "duckdb") return (await import("./chunks/duckdb-DCV4JFWK.js")).getDatabase(options);
|
|
2372
2339
|
if (options.type === "json") return (await Promise.resolve().then(() => json_exports)).getDatabase(options);
|
|
2373
2340
|
throw new Error("Invalid database type");
|
|
2374
2341
|
}
|
|
@@ -2382,6 +2349,6 @@ var src_default = {
|
|
|
2382
2349
|
/** @internal */
|
|
2383
2350
|
var PACKAGE_VERSION_INITIALIZED = true;
|
|
2384
2351
|
//#endregion
|
|
2385
|
-
export { DatabaseSchemaManager, NestedTransactionError, PACKAGE_VERSION_INITIALIZED, assertCanExportDatabase, assertCanImportDatabase, bucketExpr, buildAggregate, buildWhere, checkExpectedTables, checkRelationship, checkUniqueColumn, clearConnectionCache, clearPostgresConnectionCache, convertUniqueIndexesToInlineConstraints, createPostgresDatabase, databaseNameFromUrl, src_default as default, dropPostgresDatabase, dumpPostgresDatabase, escapeSqlValue, formatDbError, getDatabase, isLocalDatabaseUrl, postgresEnvFromUrl, raw, redactDatabaseUrl, resolveSchemas, restorePostgresDatabase, runDoctor, syncSchema, tableExists, validateColumnName };
|
|
2352
|
+
export { DatabaseSchemaManager, ExpressionError, NestedTransactionError, PACKAGE_VERSION_INITIALIZED, assertCanExportDatabase, assertCanImportDatabase, bucketExpr, buildAggregate, buildWhere, checkExpectedTables, checkRelationship, checkUniqueColumn, clearConnectionCache, clearPostgresConnectionCache, convertUniqueIndexesToInlineConstraints, createPostgresDatabase, databaseNameFromUrl, src_default as default, dropPostgresDatabase, dumpPostgresDatabase, escapeSqlValue, formatDbError, getDatabase, isLocalDatabaseUrl, postgresEnvFromUrl, raw, redactDatabaseUrl, renderExpression, resolveSchemas, restorePostgresDatabase, runDoctor, syncSchema, tableExists, validateColumnName };
|
|
2386
2353
|
|
|
2387
2354
|
//# sourceMappingURL=index.js.map
|