Search code examples
iosobjective-csqlitefmdb

SQLite id field - autofill


I've added a new table to my DB:

CREATE TABLE myTable (
myId ID NOT NULL,
aNumber INTEGER NOT NULL,
anUniqueTextId TEXT NOT NULL,
aText TEXT,
PRIMARY KEY(myId, anUniqueTextId) ON CONFLICT IGNORE,
FOREIGN KEY(anUniqueTextId, aNumber) REFERENCES otherTable(otherTableId, otherTableValue2) ON DELETE CASCADE
);

Now I want to insert values without manually finding out which index should I put in myId field:

[myDatabase inTransaction:^(FMDatabase *db, BOOL *rollback) {
        [db executeUpdate:@"INSERT INTO myTable VALUES(?,?,?)",
//         @(myData.myId), //I don't want to insert it manually
         @(aNumber),
         myData.anUniqueTextId,
         myData.aText];

        if (db.lastErrorCode) {
            NSLog(@"Huston, we've got a problem: %@", db.lastError.localizedDescription);
        }
}];

Ofc, I get here an error telling:

table myTable has 4 columns but 3 values were supplied

Now the question is how to insert the data to make this field autoinsert myId? I'm not sure if my insert code is invalid or CREATE TABLE statement.

-- UPDATE --

I've updated create statement to correct one:

CREATE TABLE myTable (
myId INTEGER PRIMARY KEY DEFAULT 0 NOT NULL,
aNumber INTEGER NOT NULL,
anUniqueTextId TEXT NOT NULL,
aText TEXT,
FOREIGN KEY(anUniqueTextId, aNumber) REFERENCES otherTable(otherTableId, otherTableValue2) ON DELETE CASCADE
);

Solution

  • With respect to your comment you need to specify the PRIMARY KEY with a NULLvalue in the QUERY:

    [db executeUpdate:@"INSERT INTO myTable VALUES(?,?,?,?)",
         NULL,
         @(aNumber),
         myData.anUniqueTextId,
         myData.aText];
    

    That way the database will fill in the primary key and autoincrement it (SQL Lite specs for PRIMARY KEY).