I encounter Error [Error: attempt to write a readonly database (code 1032 SQLITE_READONLY_DBMOVED)] using expo-sqlite

1.7k Views Asked by At
export async function insertAttempt() {
    const db = await openDatabase()
    try {
        return await new Promise((resolve, reject) => {
            db.transaction(
                (tx) => {
                    tx.executeSql("INSERT INTO Attempt (attempt_date)
                    VALUES (?)", [Date.now()])
                    tx.executeSql(query.selectAttempt, [], (transaction, resultSet) => {
                        console.log(resultSet)
                    })
                },
                reject,
                resolve
            )
        })
    } catch (e) {
        console.log("Error: ", e)
    }
}

I'm calling the above in a react hook component, like so:

    useEffect(() => {
        async function example() {
            await insertAttempt()
        }

        example()
    }, [])
Error:  [Error: attempt to write a readonly database (code 1032 SQLITE_READONLY_DBMOVED)]

I don't have this problem with select sql operations, only with inserts.

1

There are 1 best solutions below

1
On

If you are using a Pre-populated database in your App, go to your openDatabase() function, you may need to access the private attribute _db of WebSQLDatabase and close it with available method, you will end up with something similar to below.

export default async function openDatabase() {

  const database = SQLite.openDatabase("myDb.db")
  database._db.close()
  
    if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory + "SQLite")).exists) {
      await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + "SQLite");
    }

    await FileSystem.downloadAsync(
      Asset.fromModule(require("../assets/www/myDb.db")).uri,
      FileSystem.documentDirectory + "SQLite/myDb.db"
    );
    
    return SQLite.openDatabase("myDb.db");
}