Encountered an issue while attempting to write to SQLite, error code 6 is

I'm working on a project that involves writing to a SQLite Database from a cross-platform app built with AngularJS, Monaca, and Onsen UI.

Within my app, there's a view where users input their username and password. I store these details in a Service for later retrieval using getters and setters.

However, when attempting to write the stored values to the SQLite database, I encounter an Error Code 6. As per THIS, Error Code 6 indicates that the database is locked. Why might the database be locked and how can I write data to it despite being locked or unlock it?

In my code, I create the table if it doesn't already exist before attempting to write to it. Could this initialization be what's causing the database blockage? Below is my app.js snippet showcasing the database procedures.

var db;
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    db = window.openDatabase("myDB", "1.0", "My DB", 200000);
    db.transaction(createDB, errorCB, successCB);
}

function createDB(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS tb_remember_me (id INTEGER PRIMARY KEY, name)');
}

// User clicks the "login" button to save details to Database
$scope.validateLogin = function () {
    // Open DB and write to it
    db = window.openDatabase("myDB", "1.0", "My DB", 200000);
    db.transaction(goInsert, errorCB, successCB);
};

function goInsert() {
    db = window.openDatabase("myDB", "1.0", "My DB", 200000);
    db.transaction(insertDB, errorCB, successCB);
}

function insertDB(tx) {
    // Retrieve user-entered details from Shared Service    
    $userID = SharedProperties.getUserID(); 
    $userPIN = SharedProperties.getUserPIN(); 

    tx.executeSql('INSERT INTO tb_remember_me (id, name) VALUES (?,?)', [$userID, $userPIN]); // Error occurs here
}

// Transaction error callback
function errorCB(err) {
    alert("Error processing SQL with ERROR CODE: " + err.code);
}

// Transaction success callback
function successCB() {
    return true;
}

Answer №1

It appears that the issue lies in attempting to define two transactions within each other, which is causing a conflict with my common sense.

The problem arises when you reserve a transaction from the database on this specific line of code:

function goInsert() {
   db = window.openDatabase("myDB", "1.0", "My DB", 200000);
   db.transaction(insertDB, errorCB, successCB);  <--- this line!!
}

And then proceed to try to initiate another transaction within it:

// called inside previous function.
function goInsert() {
   db = window.openDatabase("myDB", "1.0", "My DB", 200000);
   db.transaction(insertDB, errorCB, successCB); <-- right here, within the call another transaction is being created.
}

As a result, the initial transaction reserves the database on the first db.transaction line, while the inner function causes a blockage when another db.transaction is attempted within it.

Answer №2

Having faced a challenge with SQLite in the past while developing a web app, I would like to share an excerpt from the SQLite documentation and provide some insights on it.

In order to write to a database in SQLite, a process needs to acquire a SHARED lock first, followed by obtaining a RESERVED lock indicating its intention to write to the database in the future. While only one process can hold a RESERVED lock at a time, other processes can still read from the database concurrently.

It is worth noting that SQLite does not support simultaneous write transactions, which can result in the database being locked (potentially permanently requiring file copying as a workaround).

Therefore, creating a multi-user app using the same SQLite file is not feasible. If each user has their own file, a mechanism should be implemented to wait for a transaction to complete before initiating a new one.

You can refer to the full documentation here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an 'Uncaught TypeError' with Tumblr API due to undefined property 'type' not being read

I have multiple feeds on my website, each fetching posts from various tags. The first feed is functioning properly, but the 2nd and 3rd feeds are displaying the following error: Uncaught TypeError: Cannot read property 'type' of undefined All ...

Learn the process of flipping an element when a button is clicked!

I want to use the jquery flip.js library to flip an element. However, I only want the element to flip when I click on a specific flip button, and then flip back again when another button is clicked. Any suggestions on how to achieve this functionality? ...

Smooth scrolling feature for Wordpress websites

I am currently in the process of converting an HTML5 template into a Wordpress theme. One specific feature I'd like to add is a custom scroll for Wordpress using the code: <script src="jquery.nicescroll.js"></script> DEPENDENCIES This cod ...

Refresh the vuex store values in real-time on the displayed page without the need

I am currently working on displaying variables from my backend that update automatically. To achieve this, I am utilizing Vuex store and nuxt.config.js for transferring the variables. API calls are used to modify the variables in the backend. However, I am ...

Struggling to implement sparklines for real-time data in the AngularJS adaptation of the SmartAdmin template

Currently, I am embarking on a project that involves utilizing the AngularJS version of the SmartAdmin Bootstrap template foundhere. Within this project scope, I am required to integrate sparklines into various pages. I have successfully implemented them ...

What is the method for adding/removing the 'hidden' attribute within a <p hidden> element

What is the best way to toggle the visibility of 'hidden' in the element <p hidden>My Text</p>? I attempted removing the attribute and setting it to false, but unfortunately, neither method seemed to work. let paragraphElements = d ...

Using Node.js, securely encode data using a private key into a base64 format that can only be decoded on the server side

Here is my specific situation: An http request arrives at the server for a login action A user token needs to be created. This token consists of a Json object composed of different fields. It is then converted to a string and encoded in Base64. const ...

Tips for accurately measuring the height of a single table cell

I am facing an issue with a table that I have set up. Here is the code: <table> <tr> <td id='tdleftcontent' style='border:1px solid red;'> <asp:Label ID='lbl' runat="server"></asp:Label> < ...

Issue encountered while appending new rows to the tbody of a table

I'm encountering an issue with the append function within a for loop in my code. The string being passed to the function isn't parsing correctly and results in an error. How can I go about resolving this problem? Thanks! function getDetailPopUp ...

Anomaly in Date String Comparison within Angular Controller

Having a puzzling issue when attempting to compare two date strings within my Angular Controller. It seems that the comparison is yielding unexpected results. To explain, I first convert today's date to a string ("2/5/2016") and then proceed to use it ...

Instructions for creating a slush machine

Today, I tried to create a slush generator but ran into some issues. Even after following tutorials online and double-checking my work, the generator doesn't seem to be functioning properly. If anyone can identify what I might have done wrong, please ...

How can you modify the default empty table message in a datatable using DTOptions?

I've come across several questions similar to this lately. Here is an example, but all the answers seem to involve using jquery. I'm trying to find a way to achieve this using DTOptions instead. This is how my code looks like at the moment : ...

Live streaming updates directly from Firebase

In order to achieve real-time updates from Firebase, my objective is to retrieve comments from Firebase and display them on this.note. I seem to have made a mistake in the update() function. Here is the tutorial I followed: link. methods: { update(){ db.c ...

The PHP application encountered an error when trying to use an object of the mysqli_result type as an array

In my section, I have a straightforward display of data sourced from the database. Upon clicking options like construction and selecting countries like Algeria, the displayed values are [251, 211,712]. Similarly, for selections like Power in Egypt, the ou ...

Access all the properties of an object within a mongoose record

My database contains a collection of documents that are structured using the mongoose and express frameworks. Each document follows this schema: const userSchema = new Schema({ firstName: { type: String }, lastName: { type: String }, email: { t ...

Steps to automatically launch a URL upon button click and executing PHP script

I have a Joomla website and I am facing a challenge in automatically triggering a modal window that displays a web page based on parameters passed through the URL. The scenario on my website is as follows: A trip leader selects a trip and schedules it by ...

What is the best way to utilize Regular Expressions in ng-pattern to filter out specific special characters?

I need to create an ng-pattern that avoids certain special characters, such as %, ;, :, ', ", , <, and >. ng-pattern="/^[^%;:\x27\x22,<>]*$/" Is there a way to achieve this in ng-pattern? Update: <input type="text" class ...

Extract form input to utilize in nodemailer

Currently I am working on a form implementation where I intend to utilize nodemailer for sending test emails to myself. My goal is to have the email inputted into the form dynamically appear in both the "to" and "subject" fields when the user submits the f ...

Possible rewrite: "Unable to use jQuery to add elements to data fetched through AJAX requests."

I am looking to add a button to copy code inside every div that has a class starting with language. The code is functioning properly, however, after attempting to retrieve data from the database using Ajax, the button no longer appears in the div as it did ...

What steps can I take to stop a browser from triggering a ContextMenu event when a user performs a prolonged touch

While touch events are supported by browsers and may trigger mouse events, in certain industrial settings, it is preferred to handle all touch events as click events. Is there a way to globally disable context menu events generated by the browser? Alternat ...