views:

271

answers:

2

Is there a simple way to modify a table in recent sqlite versions so that it matches a predefined schema?

Schema:

war_id INTEGER NOT NULL, 
clanname VARCHAR(64), 
clanhomepage VARCHAR(128), 
date DATETIME, 
server VARCHAR(64), 
warmode_id INTEGER, 
squad_id INTEGER, 
notes TEXT, clantag String(16), 
PRIMARY KEY (war_id), 
FOREIGN KEY(warmode_id) REFERENCES warmodes (warmode_id), 
FOREIGN KEY(squad_id) REFERENCES squads (squad_id), 
FOREIGN KEY(orgamember_id) REFERENCES users (user_id)

Now I want to insert clantag VARCHAR(16) after clanname so it is consistent with other setups.

I don't mind exporting, ditching, recreating, yet I wonder if there's an option to do so without that, given other sql databases can handle that...

A: 

SQLite is not other SQL databases and cannot do that.

Ignacio Vazquez-Abrams
+1  A: 

SQlite supports adding columns, as shown here. The only restriction you'll face is that the column will be at the end of the table, but for normal use column order shouldn't be a problem. An alternative solution is to create a new table with the new definition, insert all your data into it, drop the old table and rename the new table, like this:

BEGIN TRANSACTION;
CREATE TABLE War_TMP( 
    war_id INTEGER NOT NULL, 
    clanname VARCHAR(64), 
    clantag VARCHAR(16),
    clanhomepage VARCHAR(128), 
    date DATETIME, 
    server VARCHAR(64), 
    warmode_id INTEGER, 
    squad_id INTEGER, 
    notes TEXT, 
    PRIMARY KEY (war_id), 
    FOREIGN KEY(warmode_id) REFERENCES warmodes (warmode_id), 
    FOREIGN KEY(squad_id) REFERENCES squads (squad_id), 
    FOREIGN KEY(orgamember_id) REFERENCES users (user_id)
);

INSERT INTO War_TMP() SELECT war_id, clanname, "", clanhomepage,date,server,warmode_id,squad_id,notes FROM War;
DROP TABLE War;

ALTER TABLE War_TMP RENAME TO War;

COMMIT;
Koert
That's what I expected to some end :) Good to know, that I didn't overlook something more simple than this.
Jokey