Error 19: Constraint violation - duplicate entry detected

While trying to set up my app, create a local database, and insert the very first user who has logged in locally, I encountered an error message at a specific point in the code. Here's where it happened:

angular.module("greenApp")
    .service("dbService",['$q', function($q){

        var db;
        var promise = function(){
            var deferred = $q.defer();

            db = window.openDatabase('greenDB', '1.0', 'Green Database', 2*1024*1024);

            db.transaction(function(tx){
                tx.executeSql("CREATE TABLE IF NOT EXISTS user (user TEXT PRIMARY KEY) ")
            }, function(err){
                alert('Something went wrong... Error: DATABASE INIT ' + err);
            }, function(scc){
                deferred.resolve();
            })

            return deferred.promise;
        }
        promise();

        var query = function(sql, args) {
            var deferred = $q.defer();

            db.transaction(function(tx) {
                tx.executeSql(sql, args, function(tx, results) {
                    deferred.resolve(results);
                });
            }, function(err) {
                deferred.reject(err);
            });

            return deferred.promise;
        };

        var insert_into = function(args) {
            var queryPromise = query("INSERT INTO user (user) VALUES (?)", args);
            console.log("in insert_into", queryPromise) // This is where the error occurs
            return queryPromise;
        };

        return {
            promise: promise,
            insert_into: insert_into,
        };
    }]);
    

At the point where args is simply ["user-name-string"], I received the following error message:

"could not execute statement due to a constraint failure (19 UNIQUE constraint failed: user.user)

I'm puzzled by this error as the same code was functional in a recent cordova project which I migrated to Ionic. Any insights on what might be causing this issue?

Answer №1

It seems like you have a redundant insertion in your code ... take a look below

var insert_record = function(data) {

    var queryResult = runQuery("INSERT INTO database (record) VALUES (?)", data);
    console.log("inside insert_record", queryResult) // Error message displayed here
    return runQuery("INSERT INTO database (record) VALUES (?)", data); <-- you already executed a query above, no need to repeat it?!?
};

Answer №2

Even after closing the app, the sqlite database remains intact, causing an attempt to insert data each time the app is opened (likely successful on first launch but resulting in an error on subsequent attempts).

By utilizing CREATE TABLE IF NOT EXISTS, the app can prevent failures during table creation but may encounter issues during the initial insertion of data.

To manage this process effectively, consider using the pragma user_version to track the version of your database and determine when tables should be created or values inserted, ensuring that the database is prepared for use at all times.

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

Using JavaScript to halt the playback of HTML5 video in 'injected' HTML code

Although I know there have been similar issues resolved here before, none of the suggested solutions seem to work for me. Let me start by explaining my problem. I have a landing page located here: On the portfolio section of the landing page, I hav ...

Node.js not receiving data event in CORS ajax call

I am currently encountering an issue where the data event in my jQuery process is not being called when trying to receive JSON from an AJAX CORS call. Despite printing the JSON on the screen and verifying its presence, the data event remains uninvoked. Aft ...

Reformat a JSON file and save as a new file

I have a lengthy list of one-level JSON data similar to the example below: json-old.json [ {"stock": "abc", "volume": "45434", "price": "31", "date": "10/12/12"}, {"stock": "abc", "volume": "45435", "price": "30", "date": "10/13/12"}, {"stock": "xyz", "vo ...

Modify a variable for a specific ng-repeat item in AngularJS

I want to expand the text when a user clicks on a read more button: <md-content class="md-padding" layout-xs="column" layout="row" layout-wrap> <div flex-xs flex-gt-xs="50" layout="column" ng-repeat="paquete in paquetes"> <md-card> ...

Is there a way to implement a one-second delay before displaying a drop-down hover menu?

I've been trying to use the setTimeout function, but so far I haven't been able to figure out the correct way to do it. Any ideas on what I might be missing? JSFIDDLE $('.drop-down').click(function() { $(this).hide(); }); $(&apo ...

Ways to detect and respond to events in this particular scenario

I'm creating necessary components dynamically based on the provided CSS. This process involves iterating through a response array and generating HTML elements accordingly. for (var i = 0; i < responseinner.length; i++) { for (var k = 0; k < ...

Uncovering the jsPlumb link between a pair of identifiers

Could someone help me understand how to disconnect two HTML elements that are connected? I have the IDs of both elements, but I'm not sure how to locate their connection in the jsPlumb instance. Any tips on finding the connection between two IDs? ...

AngularJS is adjusting the form to be dirty, not pristine

I have created an HTML form and implemented validation for each input using AngularJS. However, I want the validation errors to be hidden initially when the page loads, and only show up once the user interacts with the form. This is how my validation is ...

What is the best way to customize column width in AG-Grid?

I am looking for a way to dynamically set column width in my table. I have provided a stackblitz example which demonstrates that when changing the screen size, only the table border adjusts, but not the column widths. Is there a way to also change the col ...

Exploring date comparison in AngularJS

I've encountered an issue while using ng-show in a page that I'm currently designing: <td ng-show="week.EndDate > controller.currentDate"> The week object has a property called EndDate, and the value of currentDate is being set in my c ...

Error Encountered: Attempting to access the 'play' property of an undefined object caused a TypeError

I recently tried my hand at creating avatars and animations using readyplay.me and mixamo. For those interested, you can check out the tutorial I followed here: https://dev.to/nourdinedev/how-to-use-threejs-and-react-to-render-a-3d-model-of-your-self-4kkf ...

Creating a Chrome extension that opens multiple tabs using JavaScript

Currently, I am working on a chrome extension that includes several buttons to open different tabs. However, there seems to be an issue where clicking the Seqta button opens the tab three times and clicking the maths book button opens the tab twice. Below, ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...

Encountering an error while transmitting variables through ajax

Encountering an issue when attempting to remove a user from the database. Below is the code I have written: On the server side: @RestController public class EmployeeRestController { @DeleteMapping( value = "/delete_user") public List<Em ...

Unique title: "Personalized on-click.prevent feature"

I'm having trouble coming up with a name for this concept, so I don't know what specific term to search for. I've checked out some directives, but I'm not convinced that's what I need. Essentially, I want to be able to do the follo ...

Ways to generate multiple elements using JavaScript

Is there a way to dynamically freeze columns in a table as I scroll it horizontally? I've achieved this statically using JavaScript, but is there a way to indicate the number of columns and achieve the desired style? This is what my JavaScript code c ...

What is the most effective way to transform values into different values using TypeScript?

If I have a list of country codes and I want to display the corresponding country names in my component, how can I achieve this using props? interface MyComponentProps { countryCode: 'en' | 'de' | 'fr'; } const MyComponent: ...

What is the best way to determine if a dropdown option has been selected in AngularJS?

Is there a simple way to check if any value has been selected from a dropdown menu in AngularJS without knowing which value has been selected? <button class="btn" ng-click="openDropdown($event)">{{labelX}} <span ng-click="openDropdownFromA($eve ...

The Three.js camera imported from Collada is unable to properly focus on an object within the scene

Having some trouble grasping the concept of Collada Animation in Three.js! I have an animation with a moving camera in 3Dsmax, and exported the scene into Collada. loader.load( ColladaName, function ( collada ) { model = collada.scene; model.upda ...

Issue with Bootstrap List Group Nested Links causing them to stop functioning after initial selection

I am trying to implement page navigation using the Bootstrap List-group class in HTML. However, I am facing an issue where the nested links 'Link 1' and 'Link 2' freeze after the first click. The desired functionality is as follows: ...