- Notifications
You must be signed in to change notification settings - Fork122
Initial attempt at adding jOOQ#59
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
3 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
2 changes: 2 additions & 0 deletionsdocker/mysql/setup.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletionsstubbornjava-common/build.gradle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -38,5 +38,6 @@ dependencies { | ||
| compile libs.jooqCodegen | ||
| testCompile libs.junit | ||
| testCompile libs.hsqldb | ||
| } | ||
| // {{end:dependencies}} | ||
93 changes: 93 additions & 0 deletionsstubbornjava-common/src/main/java/com/stubbornjava/common/db/DSLs.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| package com.stubbornjava.common.db; | ||
| import java.util.function.Supplier; | ||
| import javax.sql.DataSource; | ||
| import org.jooq.DSLContext; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import com.stubbornjava.common.Configs; | ||
| import com.stubbornjava.common.HealthChecks; | ||
| import com.stubbornjava.common.Metrics; | ||
| import com.typesafe.config.Config; | ||
| import com.zaxxer.hikari.HikariDataSource; | ||
| public class DSLs { | ||
| private static final Logger logger = LoggerFactory.getLogger(DSLs.class); | ||
| private static final Config conf = Configs.properties(); | ||
| private DSLs() {} | ||
| // Letting HikariDataSource leak out on purpose here. It won't go very far. | ||
| private enum Transactional { | ||
| INSTANCE(ConnectionPool.getDataSourceFromConfig(conf.getConfig("pools.transactional"), Metrics.registry(), HealthChecks.getHealthCheckRegistry())); | ||
| private final HikariDataSource dataSource; | ||
| private Transactional(HikariDataSource datasource) { | ||
| this.dataSource = datasource; | ||
| } | ||
| public HikariDataSource getDataSource() { | ||
| return dataSource; | ||
| } | ||
| } | ||
| private static HikariDataSource getTransactionalDataSource() { | ||
| return Transactional.INSTANCE.getDataSource(); | ||
| } | ||
| private enum Processing { | ||
| INSTANCE(ConnectionPool.getDataSourceFromConfig(conf.getConfig("pools.processing"), Metrics.registry(), HealthChecks.getHealthCheckRegistry())); | ||
| private final HikariDataSource dataSource; | ||
| private Processing(HikariDataSource datasource) { | ||
| this.dataSource = datasource; | ||
| } | ||
| public HikariDataSource getDataSource() { | ||
| return dataSource; | ||
| } | ||
| } | ||
| private static HikariDataSource getProcessingDataSource() { | ||
| return Processing.INSTANCE.getDataSource(); | ||
| } | ||
| public static DSLContext any() { | ||
| return ThreadLocalJooqConfig.getCurrentContext(); | ||
| } | ||
| public static DSLContextWrapper transactional() { | ||
| return new DSLContextWrapper(Transactional.INSTANCE.getDataSource()); | ||
| } | ||
| public static DSLContextWrapper processing() { | ||
| return new DSLContextWrapper(Processing.INSTANCE.getDataSource()); | ||
| } | ||
| public static final class DSLContextWrapper { | ||
| private final HikariDataSource ds; | ||
| public DSLContextWrapper(HikariDataSource ds) { | ||
| this.ds = ds; | ||
| } | ||
| public final DSLContext get() { | ||
| return ThreadLocalJooqConfig.ensureNamedConfiguration(ds.getPoolName()); | ||
| } | ||
| public final void newTransaction(Runnable runnable) { | ||
| ThreadLocalJooqConfig.threadLocalTransaction(ds.getPoolName(), ds, runnable); | ||
| } | ||
| public final <T> T newTransactionResult(Supplier<T> supplier) { | ||
| return ThreadLocalJooqConfig.threadLocalTransactionResult(ds.getPoolName(), ds, supplier); | ||
| } | ||
| } | ||
| public static void main(String[] args) { | ||
| logger.debug("starting"); | ||
| DataSource processing = DSLs.getProcessingDataSource(); | ||
| logger.debug("processing started"); | ||
| DataSource transactional = DSLs.getTransactionalDataSource(); | ||
| logger.debug("transactional started"); | ||
| logger.debug("done"); | ||
| } | ||
| } |
10 changes: 7 additions & 3 deletions...ubbornjava/common/db/jooq/JooqConfig.java → ...om/stubbornjava/common/db/JooqConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
22 changes: 22 additions & 0 deletionsstubbornjava-common/src/main/java/com/stubbornjava/common/db/NamedConfiguration.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| package com.stubbornjava.common.db; | ||
| import org.jooq.Configuration; | ||
| public class NamedConfiguration { | ||
| private final String name; | ||
| private final Configuration configuration; | ||
| public NamedConfiguration(String name, Configuration configuration) { | ||
| super(); | ||
| this.name = name; | ||
| this.configuration = configuration; | ||
| } | ||
| public String getName() { | ||
| return name; | ||
| } | ||
| public Configuration getConfiguration() { | ||
| return configuration; | ||
| } | ||
| } |
157 changes: 157 additions & 0 deletionsstubbornjava-common/src/main/java/com/stubbornjava/common/db/TableCrud.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| package com.stubbornjava.common.db; | ||
| import java.util.ArrayList; | ||
| import java.util.Arrays; | ||
| import java.util.Collection; | ||
| import java.util.Collections; | ||
| import java.util.List; | ||
| import java.util.function.Function; | ||
| import java.util.function.Supplier; | ||
| import org.jooq.Condition; | ||
| import org.jooq.DSLContext; | ||
| import org.jooq.Field; | ||
| import org.jooq.Record; | ||
| import org.jooq.RecordMapper; | ||
| import org.jooq.RecordUnmapper; | ||
| import org.jooq.UniqueKey; | ||
| import org.jooq.UpdatableRecord; | ||
| import org.jooq.impl.TableImpl; | ||
| public class TableCrud<Rec extends UpdatableRecord<Rec>, T> { | ||
| private final TableImpl<Rec> table; | ||
| private final RecordMapper<Record, T> mapper; | ||
| private final RecordUnmapper<T, Rec> unmapper; | ||
| private final Supplier<DSLContext> configSupplier; | ||
| public TableCrud(TableImpl<Rec> table, | ||
| RecordMapper<Rec, T> mapper, | ||
| RecordUnmapper<T, Rec> unmapper, | ||
| Supplier<DSLContext> configSupplier) { | ||
| super(); | ||
| this.table = table; | ||
| this.mapper = (RecordMapper<Record, T>) mapper; | ||
| this.unmapper = unmapper; | ||
| this.configSupplier = configSupplier; | ||
| } | ||
| public T insertReturning(T obj) { | ||
| Rec rec = records(Collections.singletonList(obj), false).get(0); | ||
| rec.insert(); | ||
| return rec.map(mapper); | ||
| } | ||
| public void insert(T obj) { | ||
| insert(Collections.singletonList(obj)); | ||
| } | ||
| @SuppressWarnings("unchecked") | ||
| public void insert(T... objects) { | ||
| insert(Arrays.asList(objects)); | ||
| } | ||
| public void insert(Collection<T> objects) { | ||
| // Execute a batch INSERT | ||
| if (objects.size() > 1) { | ||
| configSupplier.get().batchInsert(records(objects, false)).execute(); | ||
| } | ||
| // Execute a regular INSERT | ||
| else if (objects.size() == 1) { | ||
| records(objects, false).get(0).insert(); | ||
| } | ||
| } | ||
| public void update(T obj) { | ||
| update(Collections.singletonList(obj)); | ||
| } | ||
| @SuppressWarnings("unchecked") | ||
| public void update(T... objects) { | ||
| update(Arrays.asList(objects)); | ||
| } | ||
| public void update(Collection<T> objects) { | ||
| // Execute a batch UPDATE | ||
| if (objects.size() > 1) { | ||
| configSupplier.get().batchUpdate(records(objects, false)).execute(); | ||
| } | ||
| // Execute a regular UPDATE | ||
| else if (objects.size() == 1) { | ||
| records(objects, false).get(0).update(); | ||
| } | ||
| } | ||
| public void delete(T obj) { | ||
| delete(Collections.singletonList(obj)); | ||
| } | ||
| @SuppressWarnings("unchecked") | ||
| public void delete(T... objects) { | ||
| delete(Arrays.asList(objects)); | ||
| } | ||
| public void delete(Collection<T> objects) { | ||
| // Execute a batch DELETE | ||
| if (objects.size() > 1) { | ||
| configSupplier.get().batchDelete(records(objects, false)).execute(); | ||
| } | ||
| // Execute a regular DELETE | ||
| else if (objects.size() == 1) { | ||
| records(objects, false).get(0).delete(); | ||
| } | ||
| } | ||
| public T findOne(Function<TableImpl<Rec>, Condition> func) { | ||
| return configSupplier.get().fetchOne(table, func.apply(table)).map(mapper); | ||
| } | ||
| public List<T> find(Function<TableImpl<Rec>, Condition> func) { | ||
| return configSupplier.get().fetch(table, func.apply(table)).map(mapper); | ||
| } | ||
| public int deleteWhere(Function<TableImpl<Rec>, Condition> func) { | ||
| return configSupplier.get().deleteFrom(table).where(func.apply(table)).execute(); | ||
| } | ||
| // Copy pasted from jOOQ's DAOImpl.java | ||
| private /* non-final */ Field<?>[] pk() { | ||
| UniqueKey<?> key = table.getPrimaryKey(); | ||
| return key == null ? null : key.getFieldsArray(); | ||
| } | ||
| // Copy pasted from jOOQ's DAOImpl.java | ||
| private /* non-final */ List<Rec> records(Collection<T> objects, boolean forUpdate) { | ||
| List<Rec> result = new ArrayList<>(); | ||
| Field<?>[] pk = pk(); | ||
| for (T object : objects) { | ||
| Rec record = unmapper.unmap(object); | ||
| record.attach(configSupplier.get().configuration()); | ||
| if (forUpdate && pk != null) | ||
| for (Field<?> field : pk) | ||
| record.changed(field, false); | ||
| resetChangedOnNotNull(record); | ||
| result.add(record); | ||
| } | ||
| return result; | ||
| } | ||
| // Copy pasted from jOOQ's Tools.java | ||
| /** | ||
| * [#2700] [#3582] If a POJO attribute is NULL, but the column is NOT NULL | ||
| * then we should let the database apply DEFAULT values | ||
| */ | ||
| private static final void resetChangedOnNotNull(Record record) { | ||
| int size = record.size(); | ||
| for (int i = 0; i < size; i++) | ||
| if (record.get(i) == null) | ||
| if (!record.field(i).getDataType().nullable()) | ||
| record.changed(i, false); | ||
| } | ||
| } |
65 changes: 65 additions & 0 deletionsstubbornjava-common/src/main/java/com/stubbornjava/common/db/ThreadLocalJooqConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| package com.stubbornjava.common.db; | ||
| import java.util.function.Supplier; | ||
| import javax.sql.DataSource; | ||
| import org.jooq.Configuration; | ||
| import org.jooq.DSLContext; | ||
| import org.jooq.impl.DSL; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import com.google.common.base.Preconditions; | ||
| public class ThreadLocalJooqConfig { | ||
| private static final Logger log = LoggerFactory.getLogger(ThreadLocalJooqConfig.class); | ||
| private static final ThreadLocal<NamedConfiguration> configurations = new ThreadLocal<>(); | ||
| // This is used to fetch any currently existing configuration. | ||
| public static DSLContext getCurrentContext() { | ||
| return DSL.using(safeGet().getConfiguration()); | ||
| } | ||
| // Make sure we have the expected named config. | ||
| // This is useful if we know we are running a long running query | ||
| // and want to ensure we are using a different connection pool than | ||
| // the default pool. | ||
| public static DSLContext ensureNamedConfiguration(String name) { | ||
| NamedConfiguration config = safeGet(); | ||
| if (!name.equals(config.getName())) { | ||
| log.error("Expected to find a {} configuration but found {}", name, config.getName()); | ||
| throw new IllegalStateException(String.format("Expected to find a %s configuration but found %s", name, config.getName())); | ||
| } | ||
| return DSL.using(config.getConfiguration()); | ||
| } | ||
| private static void setNamedConfiguration(String name, Configuration configuration) { | ||
| configurations.set(new NamedConfiguration(name, configuration)); | ||
| log.debug("Set ThreadLocal configuration with name {}", name); | ||
| } | ||
| public static void threadLocalTransaction(String name, DataSource ds, Runnable runnable) { | ||
| threadLocalTransactionResult(name, ds, () -> { runnable.run(); return null;} ); | ||
| } | ||
| public static <T> T threadLocalTransactionResult(String name, DataSource ds, Supplier<T> supplier) { | ||
| return DSL.using(JooqConfig.defaultConfigFromDataSource(ds)) | ||
| .transactionResult(ctx -> { | ||
| try { | ||
| ThreadLocalJooqConfig.setNamedConfiguration(name, ctx); | ||
| return supplier.get(); | ||
| } finally { | ||
| configurations.remove(); | ||
| log.debug("Removed ThreadLocal configuration with name {}", name); | ||
| } | ||
| }); | ||
| } | ||
| private static NamedConfiguration safeGet() { | ||
| NamedConfiguration config = configurations.get(); | ||
| Preconditions.checkNotNull(config, "No Configuration has been initialized on this thread."); | ||
| log.debug("Found ThreadLocal configuration with name {}", config.getName()); | ||
| return config; | ||
| } | ||
| } |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.