seedMergeTest.js
6.2 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { DB_FILE, RECORDS_TABLE_COLUMNS, TABLE_NAME } from './constants.js'
import { getCurrentPackageRoot, getDefaultPackageRoots } from './pathResolver.js'
import { logInfo, logError, waitForPlus } from './log.js'
const SEED_DB_NAME = 'zyzs_seed_merge_manual'
const SEED_DB_FILE = '_zyzs_seed_merge_manual_.db'
const SEED_DB_PATH = `_doc/${SEED_DB_FILE}`
function toFileUrl(path) {
if (!path) return path
const p = String(path).trim()
if (p.startsWith('file://')) return p
if (p.startsWith('_')) return p
if (p.startsWith('/')) return `file://${p}`
return `file:///${p}`
}
function normalizeNoTrailingSlash(path) {
if (!path) return ''
return String(path).trim().replace(/^file:\/\//, '').replace(/\/+$/, '')
}
function openDb(name, path) {
return new Promise((resolve, reject) => {
const isOpen = plus.sqlite.isOpenDatabase({ name, path })
if (isOpen) {
resolve(true)
return
}
plus.sqlite.openDatabase({
name,
path,
success: resolve,
fail: e => {
if (e && e.code === -1402) {
resolve(e)
return
}
reject(e)
}
})
})
}
function closeDb(name) {
return new Promise(resolve => {
try {
plus.sqlite.closeDatabase({
name,
success: resolve,
fail: () => resolve()
})
} catch (_) {
resolve()
}
})
}
function execSql(name, sql) {
return new Promise((resolve, reject) => {
plus.sqlite.executeSql({
name,
sql,
success: resolve,
fail: reject
})
})
}
function removeDocRelative(relativePath) {
const path = relativePath.startsWith('_doc/') ? relativePath : `_doc/${relativePath}`
return new Promise(resolve => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(path),
entry => entry.remove(() => resolve(true), () => resolve(false)),
() => resolve(false)
)
})
}
function ensureDirForFile(absoluteFilePath) {
const abs = normalizeNoTrailingSlash(absoluteFilePath)
const idx = abs.lastIndexOf('/')
const dir = idx > 0 ? abs.substring(0, idx) : abs
const parentIdx = dir.lastIndexOf('/')
const parent = parentIdx > 0 ? dir.substring(0, parentIdx) : '/'
const leaf = parentIdx > 0 ? dir.substring(parentIdx + 1) : ''
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(parent),
parentEntry => {
if (!leaf) {
resolve(parentEntry)
return
}
parentEntry.getDirectory(
leaf,
{ create: true },
entry => resolve(entry),
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
})
}
function copyDocDbToAbsolute(absoluteTargetFilePath) {
const abs = normalizeNoTrailingSlash(absoluteTargetFilePath)
const idx = abs.lastIndexOf('/')
const fileName = idx >= 0 ? abs.substring(idx + 1) : DB_FILE
return new Promise(async (resolve, reject) => {
try {
await ensureDirForFile(abs)
} catch (e) {
reject(e)
return
}
plus.io.resolveLocalFileSystemURL(
toFileUrl(SEED_DB_PATH),
srcEntry => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(abs.substring(0, idx)),
dirEntry => {
srcEntry.copyTo(
dirEntry,
fileName,
entry => resolve(entry.fullPath),
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
})
}
async function createSeedDbWithOneRecord(recordId) {
await waitForPlus()
await removeDocRelative(SEED_DB_FILE)
await openDb(SEED_DB_NAME, SEED_DB_PATH)
const createSql = `CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (${RECORDS_TABLE_COLUMNS.join(', ')})`
await execSql(SEED_DB_NAME, createSql)
const escapedId = String(recordId).replace(/'/g, "''")
const insertSql = `INSERT INTO ${TABLE_NAME} (id, staffUuid, staffName, receptionStatus) VALUES ('${escapedId}', 'seed-merge', '手动写入合并测试', 1)`
await execSql(SEED_DB_NAME, insertSql)
await closeDb(SEED_DB_NAME)
}
function pickNonCurrentRoots(currentRoot) {
const current = normalizeNoTrailingSlash(currentRoot)
const roots = (getDefaultPackageRoots() || []).map(r => normalizeNoTrailingSlash(r)).filter(Boolean)
const unique = [...new Set(roots)]
const nonCurrent = unique.filter(r => r && r !== current)
// 优先外置 Android/data(更直观且常用于迁移)
nonCurrent.sort((a, b) => {
const ak = a.includes('/Android/data/') ? 0 : 1
const bk = b.includes('/Android/data/') ? 0 : 1
if (ak !== bk) return ak - bk
return a.localeCompare(b)
})
return nonCurrent
}
/**
* 一键生成一条 records,并把 zyzs.db 放到“非当前”包根(自动挑可写的那个)。
* 适合在自定义基座(io.dcloud.HBuilder)下模拟迁移合并。
*/
export async function seedOneRecordToNonCurrentPath() {
const plusRef = await waitForPlus()
const osName = plusRef?.os?.name
if (!plusRef || (osName !== 'Android' && osName !== 'android')) {
logInfo('写入测试库跳过:非 Android')
return { ok: false, reason: 'not-android' }
}
const currentRoot = await getCurrentPackageRoot()
const candidates = pickNonCurrentRoots(currentRoot)
if (!candidates.length) {
logError('写入测试库失败:没有可用的非当前路径')
return { ok: false, reason: 'no-non-current' }
}
const recordId = `__merge_seed_${Date.now()}_${Math.random().toString(36).slice(2, 8)}__`
await createSeedDbWithOneRecord(recordId)
const errors = []
for (const root of candidates) {
const target = `${root}/${DB_FILE}`
try {
const written = await copyDocDbToAbsolute(target)
logInfo(`测试库已写入非当前路径:${written}`, { 记录id: recordId })
return { ok: true, target: written, recordId }
} catch (e) {
errors.push({ target, error: e?.message || String(e) })
}
}
logError('写入测试库失败:所有候选路径均不可写', { 失败详情: errors })
return { ok: false, reason: 'all-failed', errors }
}