assertj-db icon indicating copy to clipboard operation
assertj-db copied to clipboard

Add assertions for database structure

Open aartiPl opened this issue 10 years ago • 4 comments

I need assertions for checking database structure. E.g. I want to check if specific table exists in database.

Proposed assertions: assertThat(table).exists(); or assertThat(source).tableExists("name");

Additionally it would be nice to have convinience method isEmpty() for assertThat(table).hasNumberOfRows(0);

JDBC code to check if table exists ()

public static boolean hasTable(DataSource ds, String name) {
        boolean exists = false;

        try(Connection c = ds.getConnection();
            //table names usually stored in database uppercased
            ResultSet rs = c.getMetaData().getTables(null, null, name.toUpperCase(), null)) {

            if (rs.next()) {
                exists = true; // table exists
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return exists;
    }

Or just do some operation and catch jdbc exception: table not exists. Below assertion partially does the trick, but is not elegant. assertThat(table).hasNumberOfRows(0);

aartiPl avatar Jul 09 '15 08:07 aartiPl

It is a good idea. But i prefer to plan for a next release. For the moment, the goal is to make the first release (it will be done in a couple of day). Thanks

regis1512 avatar Jul 09 '15 08:07 regis1512

@regis1512 is anyone working on this? I'd like to take a crack on this as I have started some work on this out of necessity.

Avinash-Bhat avatar Aug 04 '16 18:08 Avinash-Bhat

This is my proposal for the APIs (not exhaustive list).

  1. TableAssert.exist()
  2. AbstractColumnAssert.exist()
  3. AbstractColumnAssert.hasType(String)
  4. AbstractColumnAssert.isPrimaryKey()
  5. AbstractColumnAssert.hasDefaultValue(Object)

For completion, the inverse of the isPrimaryKey and, exist should also be provided.

there should be additional methods for additional checks , like foreign key, uniqueness, non-nullability, auto-increment,...

Avinash-Bhat avatar Aug 04 '16 19:08 Avinash-Bhat

@Avinash-Bhat Checking existence of table is implemented in release 1.3.0

VanRoy avatar Dec 26 '19 17:12 VanRoy