Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jooq dynamically change db's schema in generated query

Tags:

java

sql

jooq

I have 2 similar schemas in simple database - "develop" and "stage". I have generated Java classes with Jooq for one of that schemas ("develop" for example). When jooq generates query to db, it implicitly add schema's name to all query's aliases

select "develop"."image"."id", "develop"."image"."image_data" 
from "develop"."image" 
where "develop"."image"."id" = ?

So my question is, whether there are the way to change jooq schema name (for "stage" as an example) in generated query without regenerating jooq's classes for "stage" schema?

like image 755
Vladyslav Nikolaiev Avatar asked Jun 09 '17 10:06

Vladyslav Nikolaiev


1 Answers

You have several options, which can even be combined:

Use the code generator's schema mapping feature

If you want to avoid hard-wiring the "develop" schema name into your generated classes, you can rewrite that to some other schema name like this:

<configuration>
  <generator>
    <database>
      <schemata>
        <schema>
          <inputSchema>develop</inputSchema>
          <outputSchema>stage</outputSchema>
        </schema>
      ...

Of course, this just postpones the problem, because the schema name is still in the generated code. You can remove the name entirely from generated code by using the following option:

<configuration>
  <generator>
    <database>
      <schemata>
        <schema>
          <inputSchema>develop</inputSchema>
          <outputSchemaToDefault>true</outputSchemaToDefault>
        </schema>
      ...

This will now remove any schema references from generated code, so the generated classes can run on all your schemas (be sure to use the correct connection and search_path, of course!)

I think this is the best option for you

More details here: https://www.jooq.org/doc/latest/manual/code-generation/codegen-advanced/codegen-config-catalog-and-schema-mapping/

Use the runtime schema mapping feature

You can leave generated code as it is and rewrite all object references at runtime using Settings (which you supply to your jOOQ runtime Configuration). Again, you have the same two options:

Mapping the schema name:

new Settings().withRenderMapping(new RenderMapping()
  .withSchemata(new MappedSchema()
    .withInput("develop")
    .withOutput("stage")
  )
);

Removing all schema names:

new Settings().withRenderSchema(false);

More details here: https://www.jooq.org/doc/latest/manual/sql-building/dsl-context/custom-settings/settings-render-mapping/

like image 120
Lukas Eder Avatar answered Nov 15 '22 23:11

Lukas Eder