How to drop an ORMLite database? - android

I would like to know how to drop a database with ORMLite.
Is there already any API call?
Just dropping all the tables does not delete the whole database.
Thanks in advance.

Edit:
Looks like you figured it out. You do something like:
boolean success =
context.deleteDatabase(
"/data/data/source.package.goes.here/databases/database-name.db‌​");
Edit:
Dropping a database is strange with ORMLite but I think it can be done. Really, when you do a dao.executeRaw(...) method, you have a connection open to the database engine that can perform just about any operation. You should be able to something like:
fooDao.executeRaw("drop database foo;");
That at least works for me under MySQL and it should under Sqlite.
Yes, ORMLite has the TableUtils class which allows you to create and drop tables. Here are the javadocs for the method.

You could do something like this,
TableUtils.dropTable(connectionSource, Model_Class.class, false);
for each table in the database, provided if you had model class for each table.
Reference:
http://ormlite.com/javadoc/ormlite-core/com/j256/ormlite/table/TableUtils.html#dropTable%28com.j256.ormlite.support.ConnectionSource,%20java.lang.Class,%20boolean%29

Related

Android Room - Create custom index

I migrate my database from DBFlow to Room finally.
However, some queries I made for my old database don't really match what I know about Room. So in my Entity I have / had these calls:
"CREATE INDEX IF NOT EXISTS `idDeletedStartEndLocalIndex` ON `QUANTITY`(START_LOCAL, END_LOCAL DESC)"
I implemented that in Room as
Index("START_LOCAL", "END_LOCAL")
but how can I add the Descending at the index? Should I just write "END_LOCAL DESC"? Would that work as expected?
Same for this one
"CREATE UNIQUE INDEX IF NOT EXISTS `serverQtyId` ON QUANTITY(SERVER_QUANTITY_ID) WHERE SERVER_QUANTITY_ID > 0"
How can I add the WHERE SERVER_QUANTITY_ID > 0 clause to the Index annotation of room? Is that even possible?
Okay, looks like there are not many ways around this. So I did the queries manually.
For those who have the same problem, my code looks like this:
runBlocking(Dispatchers.IO){
with (getInstance().openHelper.writableDatabase) {
execSQL("CREATE INDEX IF NOT EXISTS `someIndexName` ON `QUANTITY`(...)")
...
}
}
So what I do is basically get the Database Instance and their openHelper. From there you can get the writable Database. It then supports executing SQL queries directly.
All this is run in the IO coroutine scope but that's just for convenience.

Android Room database. Creating and dropping tables with table name as parameter

Is there any way I can create and drop tables similar to a 'RawQuery'?
I tried with a #RawQuery annotation (which it would be the perfect solution for me) but when I am compiling I get an error saying methods annotated with RawQuery can't return void.
I read only SELECT, UPDATE and DELETE statements are allowed when using #Query.
I would like to achieve the "creation or deletion of tables" by passing a tablename as a parameter, something like the following:
#Query("DROP TABLE :name")
void deleteTable (String name);
Any ideas on how to achieve this?
Thanks!
Official doc states that,
RawQuery serves as an escape hatch where you can build your own SQL query at runtime but still use Room to convert it into
objects.
RawQuery methods must return a non-void type. If you want to execute a raw query that does not return any value, use
RoomDatabase#query methods.
or use it like,
#RawQuery
int deleteTable (SupportSQLiteQuery query); //We can return int status like it used to return with database.delete()
//Usage
dao.deleteTable(
new SimpleSQLiteQuery("DROP TABLE tablename")
)
The ting is, wit Room, you don't have to "drop" tables, the tables re created based on your entity classes (annotated with #Entity).
As far as I know, you usually need to drop tables in case the columns change or there are some updates on the "structure", with Room there's no point in doing this unless you change the structure of your entity that can't be automatically handled by the migration. In this case, Room gives you the chance to do the migration by yourself. Check the documentation here: https://developer.android.com/training/data-storage/room/migrating-db-versions
But like the documentation states, be really careful with this.

Delete all data from all tables in Sugar ORM

I use Sugar ORM 1.5 in my app and I want to clear all info when the user logoff.
I want to avoid deleting the database file or use pure SQLite scripts if possible.
The only solution I found was using deleteAll on all tables, but I want to know if there is a better way to do it.
Regards,
EDIT
I solve the problem I had deleting the database just calling SugarContext.terminate(); before deleting the database and SugarContext.init(context); after.
Looks like it's the best solution like Henry Dang pointed in the comments, and it is faster than deleting all data.
This snippet works for me. It terminates the context deletes all tables and recreates them:
SugarContext.terminate();
SchemaGenerator schemaGenerator = new SchemaGenerator(getApplicationContext());
schemaGenerator.deleteTables(new SugarDb(getApplicationContext()).getDB());
SugarContext.init(getApplicationContext());
schemaGenerator.createDatabase(new SugarDb(getApplicationContext()).getDB());
SchemaGenerator is from com.orm, my SugarORM version is 1.5.
for other users who just want to delete all records (not tables or database)
public static void deleteAllrecords(Context applicationContext) {
List<Class> domainClasses = getDomainClasses(applicationContext);
for (Class domain : domainClasses) {
SugarRecord.deleteAll(domain);
}
}
if we want to delete sequence also you can add this line inside for loop
SugarRecord.executeQuery("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + NamingHelper.toSQLName(domain) + "'");

How can I recreate a database with default values?

In my application, I want to delete my existing database and create a new one with default values. Default values can be inserted to the database from XML.
Does anyone have any idea on how to reuse a database?
Assuming that you are using a SQLite database, to delete all the rows from all of your tables inside your database you can use db.execSQL() and heed the advice from this question Drop all tables command:
You can do it with the following DANGEROUS commands:
PRAGMA writable_schema = 1;
delete from sqlite_master where type = 'table';
PRAGMA writable_schema = 0;
you then want to recover the deleted space with
VACUUM
and a good test to make sure everything is ok
PRAGMA INTEGRITY_CHECK;
If you haven't written a way to read your XML data yet, this is excellent reading: Store parsed xml data to sqlite ? Android
Well basically that's not an Android specific question.
Firstly when do you want to recreate the database with default values and how to trigget it.
In an UI event like button click etc?
Or when you start/stop or destroy your activity?
In any cases you need to drop the database and recreate the whole structure (tables,relationships etc.) again.

How To delete a table

How do i delete a whole table in android through code?
I'd say just use a DROP TABLE query?
(I'm asuming you're talking about a database, and you're using the SQLite that's in Android, right? http://www.sqlite.org/lang_droptable.html )
an example as requested:
DROP TABLE IF EXISTS mydatabase.myTable
You can delete a database easily by writing a test case inheriting from AndroidTestCase (You don't have to but its an option), that way you will get access to Context, and call deleteDatabase("mydatabase.db") on it.

Categories

Resources