FMDB MODIFY query not working to set constraints in existing SQLite database - objective-c

My sqlite database has existing column named order_id in tbl_order with duplicate entries.
I am trying to remove duplicate entries and add constraint(UNIQUE) to solve this.
So I have tried following code to solve above issue.
I have checked previous and current build version to manage existing and new database.
It successfully executes first query but showing error in modify constraint.
if (previousBuildVersion < currentBuildVersion) {
FMResultSet *result = nil;
result = [self.objDB executeQuery:#"SELECT DISTINCT order_id FROM tbl_order ORDER BY order_id"];
[self.objDB executeUpdate:#"ALTER TABLE 'tbl_order' MODIFY \ 'order_id' TEXT NOT NULL UNIQUE \ ;"];
}
I am getting this error in Xcode:
[logging] near "MODIFY": syntax error
DB Error: 1 "near "MODIFY": syntax error"
Please suggest a solution to this issue as I have very less experience working with FMDB library.
Thanks in advance.

You cannot alter column in sqlite once it has been created.
Only the RENAME TABLE and ADD COLUMN variants of the ALTER TABLE command are supported. Other kinds of ALTER TABLE operations such as DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT, and so forth are omitted.
Please check this link for more details :
https://www.sqlite.org/omitted.html

Related

SQLGrammerException : could not execute statement

I am trying to alter a postgreSQL table using the following code.
String query = "ALTER TABLE \"georbis:world_boundaries\" DROP COLUMN testcolumn";
sessionFactory.openSession().createSQLQuery(query).executeUpdate();
The problem is my table name contains colon(:) due to which i'm getting the following error.
ERROR: unterminated quoted identifier at or near ""georbis? DROP COLUMN testcolumn" at character 13
STATEMENT: ALTER TABLE "georbis? DROP COLUMN testcolumn
Other answers of similar questions suggest that i should put double quotes(") around the table name which i tried but still getting the same error.
Also when i run the same query from SQL editor it works perfectly fine.
I also tried to run the same query for a table that does not contain colon(:) and it worked .
Solution : Thanks everyone. Got the answer from HERE
I changed my query like this and it worked.
String query = "ALTER TABLE \"georbis\\:world_boundaries\" DROP COLUMN testcolumn";
The problem is that ":" is a prompt for a named parameter. Executing the query directly in the ORM Session means the ORM will try to parse it and transform it.
Assuming you are using the latest Hibernate Session, you will need to execute the query at a lower level (jdbc connection), as this answer describes:
sessionFactory.openSession().doWork(
new Work() {
public void execute(Connection connection) throws SQLException
{
try(Statement stmt=connection.createStatement()){
stmt.executeUpdate("ALTER TABLE \"georbis:world_boundaries\" DROP COLUMN testcolumn");
}
}
}
);
That being said, are you absolutely sure you want to execute DDL from the ORM? There are other solutions out there. If your project is Maven, you can use SQL Maven plugin to put up then tear down SQL setups for testing.

How to delete a mysql-enum-like column in sql server?

in orther to get a column similar to the mysql ENUM type, I wrote a sql query as follows
ALTER TABLE [DbName].[dbo].[MediaContent]
ADD MediaType nvarchar(50)
check(MediaType in ('audio','video','song','other'))
this worked as wished(for test): But now I want to delete this column without success. It seems like there no way to directly delete a column which has a constraint up on it.
How can I solve this issue? I want to delete this column and create another one.
here is the error message I get while the deletion
The object 'CK__MediaCont__Media__14270015' is dependent on column 'MediaType'.
ALTER TABLE DROP COLUMN MediaType failed
because one or more objects access this
column. (Microsoft SQL Server, Error: 5074)
The object referenced in the error message is the name of the constraint. You should be able to use the follow:
ALTER TABLE [DbName].[dbo].[MediaContent]
DROP CONSTRAINT CK__MediaCont__Media__14270015
You need to first drop the check constraint mentioned in the error message since that's stopping you from dropping the column. Following that you may drop the column.
Drop the constrain first then drop the column ,it will work

How to deal with a Firebird table that's apparently both there and not there

I've just had something very strange happen to me with a Firebird database.
I was trying to create a table, and the CREATE TABLE failed for some reason. But now it's stuck in a very strange state:
If I try to CREATE TABLE again with the same table name, it gives an error: the table already exists. But if I try to DROP TABLE that table, it gives an error: the table does not exist. Trying to SELECT * FROM that table gives the "table does not exist" error, and the name does not show up in the metadata query:
SELECT RDB$RELATION_NAME
FROM RDB$RELATIONS
WHERE RDB$SYSTEM_FLAG=0
So for some reason, the table really seems to not be there, but I can't create it because something somewhere indicates that it does exist.
Does anyone have any idea how to fix this? I've already tried closing all connections to that database, which has helped with inconsistency issues in the past, but this time it doesn't help.
You didn't give details about what was the error when you tried to create the table, so I cannot comment it. But RDB$RELATIONS is not the only system table affected when you create a table. Maybe you are now in an inconsistent situation where some information about that table exists in some system tables and doesn't exists in others.
Another option is corrupted indexes in the system tables, so the record is not there but the index think it still exists.
Try to do a backup/restore and see if it helps. It it doesnt work, try to search for records related to that "non created" table in the other system tables (RDB$RELATION_FIELDS, etc) and if you find any, try to delete them.
As a last option, you may create a new clean database with correct metadata and pump your data to it using IBDataPump.

Delete from sql server 2000?

I want to delete all rows from table in sql server 2000 but whenever I want to delete manually or with query it shows error. In help tab it shows ODBC error: <0s>.
My table contains some '0' values but its datatype is String. Is that's the reason for this
error.
code is:
stat2=conn.createStatement();
stat2.executeUpdate("Delete * from pat.dbo.PHPL");
"Key column information is insufficient or incorrect. Too many rows were affected by update" that's warning and when click help it shows: ODBC error: <0s>. An ODBC error has been generated. You might have deleted a record that has a foreign key value related to it, or you might have violated a check constraint. For details, refer to your ODBC documentation.
Use
Truncate Table PHPL
I think you have duplicate identities, check you are not allowing duplicates on this column.

Avoid duplicate rows in phonegap database

I have a database with a single column and create it like this
function populateDB(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS RESULT(result, UNIQUE(result))');
}
however, when I want to write objects into the table, I get the error:
could not execute statement (19 constraint failed)
The error only appears when I add the NOT NULL and PRIMARY KEY to the set-Up. Without it, it keeps writing duplicates in my database (I fill the database with data from a webservice on startup of a phonegap iOS application, so I want to catch duplicate rows on database level)
At first I had only "PRIMARY KEY" in it, and because the error says something about constraints, I was assuming the primary key has to be "NOT NULL", adding it to the code, I still got the same error.
how can I solve this. thanks in advance
edit: Maybe it´s important for you to know that I write stringyfied JSON Objects into the results column.
edit: I insert the object in this function. Basically I do it one by one:
this.save = function(){
db.transaction (function(transaction){
object = $.toJSON(self);
object = encodeURI(object);
transaction.executeSql('INSERT INTO RESULT (result) VALUES ("'+object+'")');
},
errorCB,
successCB
);
}
edit: I updated my set up table code. The error doesnt occur on every row, but the objects are actually unique.
"IF NOT EXISTS" is the catch here. You get constraint failed when you use conditions like "IF NOT EXISTS" or "REPLACE", "IGNORE" etc in SQLite queries.
Suppose, you're trying to create a table that already exists, then the constraint (here not creating the table again if it already exist) fails and hence the query fails (which you actually want - you dont want to duplicate the tables right?) and gives you the error constraint failed.
You may get a similar error on INSERT or REPLACE, INSERT or IGNORE, etc...