How can I dynamically exclude objects from code generation in jOOQ

Viewed 33

jOOQ's code generator supports <includes> and <excludes> elements to include and exclude objects from code generation by using a static regular expression. For example:

<configuration>
  <generator>
    <database>
      <includes>.*</includes>
      <excludes>
           UNUSED_TABLE                # This table (unqualified name) should not be generated
         | PREFIX_.*                   # Objects with a given prefix should not be generated
         | SECRET_SCHEMA\.SECRET_TABLE # This table (qualified name) should not be generated
         | SECRET_ROUTINE              # This routine (unqualified name) ...
      </excludes>
    </database>
  </generator>
</configuration>

As documented in the manual. These regular expressions are static. Is there any way to dynamically include or exclude objects, e.g. based on some property of a table? For example, I would like to exclude all views from being generated in a PostgreSQL database.

This has been a frequent question in other forums, which now has an answer, which is why I'm documenting it here.

1 Answers

Starting with jOOQ 3.17 and #6489, it is now possible to construct includes/excludes expressions dynamically using a SQL query!

This query produces all tables that aren't views as regular expressions:

select table_schema || '\.' || table_name
from information_schema.tables
where table_type != 'VIEW';

The result includes:

information_schema\.sql_features
information_schema\.sql_implementation_info
information_schema\.sql_parts
information_schema\.sql_sizing
...

This query can now be added to the configuration, either exclusively, or in addition to other regular expressions:

<configuration>
  <generator>
    <database>
      <includes>.*</includes>
      <excludes>static_exclusions</excludes>
      <excludeSql>
        select table_schema || '\.' || table_name
        from information_schema.tables
        where table_type != 'VIEW'
      </excludeSql>
    </database>
  </generator>
</configuration>

The query is obviously vendor specific. If a different RDBMS is being used (e.g. Oracle), then the query needs to be adapted, e.g. to query SYS.ALL_TABLES

Related