Swift 数据迁移存在BUG
Through a deep analysis of the WCDB source code, I found the exact cause of the bug: the problem with the SQLCipher ATTACH mechanism. From MigrationInfo.cpp, we can see: MigrationDatabaseInfo::MigrationDatabaseInfo(...) { m_statementForAttachingSchema = StatementAttach().attach(m_sourcePath).as(m_schema); if (!cipher.empty()) { m_statementForAttachingSchema.key(BindParameter(1)); // Only if cipher is not empty, add the KEY } } Looking at the attach logic in MigratingHandleDecorator.cpp, we can see: bool MigratingHandleDecorator::attachDatabase(...) { const Data& cipher = attachInfo->getSourceCipher(); if (!cipher.empty()) { handleStatement.bindBLOB(cipher); // Only if cipher is not empty, bind the key } succeed = handleStatement.step(); } The logic for determining whether UnsafeData::empty() is m_size == 0. The problem chain is as follows:
- You pass sourceCipher: nil → cipher is empty (size=0) in C++ layer
- The ATTACH statement becomes: ATTACH DATABASE '/old.db' AS 'schema' (without the KEY clause)
- The SQLCipher rule: When ATTACH does not specify a KEY, the key from the main database is used to open the attached database
- Your target database is encrypted, and SQLCipher uses this key to decrypt the unencrypted source database → failure! The correct SQL should be: ATTACH DATABASE '/old.db' AS 'schema' KEY ''; -- empty key means plaintext
内容来源: Tencent/wcdb