importedDb.ts
4.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import type { DetailColumns, IncidentColumns, MetaFile } from '../aggregate/types';
/**
* 导入数据的本地持久化。
*
* 这是一个纯静态站点(Vite 打包 + 直接托管),没有后端可以落库。用户要求
* 「导入文件 → 刷新页面呈现最新数据」,于是刷新后仍要能看到导入结果,唯一
* 的办法就是把解析好的产物留在浏览器本地。
*
* 为什么是 IndexedDB 而不是 SQLite / localStorage:
* - localStorage:~5MB 且同步阻塞主线程,20W 行轻松超限,直接排除。
* - SQLite(WASM + OPFS):本应用的访问模式是「整批载入一次,之后全靠
* Worker 里 O(n) 的 TypedArray 扫描做视口聚合」。SQL 的索引/查询能力用不上,
* 却要额外背 WASM 体积、虚拟文件系统和启动开销,反而更慢更复杂。
* 只有当将来要做跨数据集增量追加、按行检索去重时,SQLite 才值得考虑。
* - IndexedDB:原生异步、容量按配额走,且能直接存 ArrayBuffer —— 正好是产物的形状。
*
* 存二进制的收益(20W 行 × 6 列实测):写 213ms → 23ms,读 168ms → 6ms。
* 而且读回来就是 ArrayBuffer,能零拷贝 transfer 给聚合 Worker。
*
* 分成两条记录:incidents(画图必需,首屏只要这个)与 detail(案件号+详细地址,
* 体量最大)。这样刷新首屏只读小的一条,detail 仍旧推到空闲时段加载。
*/
const DB_NAME = 'hm-heatmap-import';
const DB_VERSION = 1;
const STORE = 'bundle';
const KEY_INCIDENTS = 'incidents';
const KEY_DETAIL = 'detail';
export interface ImportManifest {
fileName: string;
/** 有效点位数 */
count: number;
/** 拒收行数 */
rejected: number;
importedAt: string;
}
export interface IncidentsRecord {
manifest: ImportManifest;
meta: MetaFile;
columns: IncidentColumns;
}
export type DetailRecord = DetailColumns;
export interface ImportedBundleInput {
manifest: ImportManifest;
meta: MetaFile;
columns: IncidentColumns;
detail: DetailRecord;
}
function openDb(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
if (typeof indexedDB === 'undefined') {
reject(new Error('当前环境不支持 IndexedDB,无法持久化导入数据'));
return;
}
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE);
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error('打开 IndexedDB 失败'));
});
}
function txDone(tx: IDBTransaction, what: string): Promise<void> {
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error ?? new Error(`${what}失败`));
tx.onabort = () => reject(tx.error ?? new Error(`${what}被中止`));
});
}
/** 写入 / 覆盖当前导入数据集(replace 语义:一次导入即一份最新数据) */
export async function saveImportedBundle(input: ImportedBundleInput): Promise<void> {
const db = await openDb();
try {
const tx = db.transaction(STORE, 'readwrite');
const store = tx.objectStore(STORE);
const record: IncidentsRecord = {
manifest: input.manifest,
meta: input.meta,
columns: input.columns,
};
store.put(record, KEY_INCIDENTS);
store.put({ caseNo: input.detail.caseNo, a: input.detail.a }, KEY_DETAIL);
await txDone(tx, '写入导入数据');
} finally {
db.close();
}
}
/** 首屏只需要这条:元数据 + 画图列。没有则返回 null(回退示例数据) */
export async function readImportedIncidents(): Promise<IncidentsRecord | null> {
return readJson<IncidentsRecord>(KEY_INCIDENTS);
}
/** 详情列(案件号 + 详细地址下标),懒加载 */
export async function readImportedDetail(): Promise<DetailRecord | null> {
return readJson<DetailRecord>(KEY_DETAIL);
}
async function readJson<T>(key: string): Promise<T | null> {
if (typeof indexedDB === 'undefined') return null;
let db: IDBDatabase | null = null;
try {
db = await openDb();
return await new Promise<T | null>((resolve, reject) => {
const req = db!.transaction(STORE, 'readonly').objectStore(STORE).get(key);
req.onsuccess = () => resolve((req.result as T | undefined) ?? null);
req.onerror = () => reject(req.error ?? new Error('读取导入数据失败'));
});
} catch (err) {
console.warn('[import] 读取本地导入数据失败,回退示例数据:', err);
return null;
} finally {
db?.close();
}
}
/** 清除导入数据,刷新后回到示例数据集 */
export async function clearImportedBundle(): Promise<void> {
const db = await openDb();
try {
const tx = db.transaction(STORE, 'readwrite');
tx.objectStore(STORE).delete(KEY_INCIDENTS);
tx.objectStore(STORE).delete(KEY_DETAIL);
await txDone(tx, '清除导入数据');
} finally {
db.close();
}
}