Lubos
Lubos

Reputation: 1209

H2 database corruption

is there a way how to check database corruption before the application starts for H2 Database ? I'd like to run automatic restore from backup zip file on application startup if I find the data are corrupted.

I cannot check it just by connecting to database, because if the DB file is there even if it is empty, I still can connect and default tables are generated.

I was also thinking to make one select statement to each table in database to make sure its working. I didn't find any built in sql function in H2 database to check the data corruption.

Upvotes: 4

Views: 2640

Answers (1)

Thomas Mueller
Thomas Mueller

Reputation: 50107

To check if the database file exists, you could use

if (new java.io.File(databaseFileName).exists()) { ... }

If the file exists, but the database is corrupt, then usually you will not be able to connect to it (trying to connect will throw an exception). This is the fastest way I know to verify it.

There is a small risk that the database file exists, but not fully initialized. If that is the case, then some of the tables don't exist. The standard way to verify all tables exists is to use DatabaseMetaData.getTables.

But unless you use some dangerous features (such disabling the transaction log, or disable database file locking) the database should not get corrupt, if you use a recent version of H2. If the database does get corrupt, then this might be a problem on how you use H2, or possibly a bug in H2 itself. It might make sense to send an mail with the details to the H2 Google Group.

Upvotes: 2

Related Questions