Search in sources :

Example 1 with DataSourceConnectionProvider

use of org.jooq.impl.DataSourceConnectionProvider in project kork by spinnaker.

the class SqlTestUtil method initDatabase.

public static TestDatabase initDatabase(String jdbcUrl, SQLDialect dialect, String dbName) {
    HikariConfig cpConfig = new HikariConfig();
    cpConfig.setJdbcUrl(jdbcUrl);
    cpConfig.setMaximumPoolSize(5);
    HikariDataSource dataSource = new HikariDataSource(cpConfig);
    DefaultConfiguration config = new DefaultConfiguration();
    config.set(new DataSourceConnectionProvider(dataSource));
    config.setSQLDialect(dialect);
    if (dialect == H2) {
        config.settings().withRenderNameStyle(AS_IS);
    }
    DSLContext context = new DefaultDSLContext(config);
    Liquibase migrate;
    try {
        DatabaseChangeLog changeLog = new DatabaseChangeLog();
        changeLog.setChangeLogParameters(new ChangeLogParameters(DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(dataSource.getConnection()))));
        changeLog.includeAll("db/changelog/", false, null, false, Comparator.comparing(String::toString), new ClassLoaderResourceAccessor(), new ContextExpression(), new LabelExpression(), false);
        migrate = new Liquibase(changeLog, new ClassLoaderResourceAccessor(), DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(dataSource.getConnection())));
    } catch (DatabaseException | SQLException | SetupException e) {
        throw new DatabaseInitializationFailed(e);
    }
    try {
        migrate.update(dbName);
    } catch (LiquibaseException e) {
        throw new DatabaseInitializationFailed(e);
    }
    return new TestDatabase(dataSource, context, migrate);
}
Also used : DefaultDSLContext(org.jooq.impl.DefaultDSLContext) HikariDataSource(com.zaxxer.hikari.HikariDataSource) DataSourceConnectionProvider(org.jooq.impl.DataSourceConnectionProvider) SQLException(java.sql.SQLException) ContextExpression(liquibase.ContextExpression) DefaultDSLContext(org.jooq.impl.DefaultDSLContext) DSLContext(org.jooq.DSLContext) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) JdbcConnection(liquibase.database.jvm.JdbcConnection) HikariConfig(com.zaxxer.hikari.HikariConfig) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) Liquibase(liquibase.Liquibase) SetupException(liquibase.exception.SetupException) ChangeLogParameters(liquibase.changelog.ChangeLogParameters) LabelExpression(liquibase.LabelExpression) LiquibaseException(liquibase.exception.LiquibaseException) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) DatabaseException(liquibase.exception.DatabaseException)

Example 2 with DataSourceConnectionProvider

use of org.jooq.impl.DataSourceConnectionProvider in project curiostack by curioswitch.

the class DatabaseModule method dbContext.

@Provides
@Singleton
static DSLContext dbContext(DataSource dataSource, DatabaseConfig config, @ForDatabase ListeningExecutorService dbExecutor) {
    Configuration configuration = new DefaultConfiguration().set(dbExecutor).set(SQLDialect.MYSQL).set(new Settings().withRenderSchema(false)).set(new DataSourceConnectionProvider(dataSource));
    if (config.getLogQueries()) {
        configuration.set(new QueryLogger());
    }
    DSLContext ctx = DSL.using(configuration);
    // Eagerly trigger JOOQ classinit for better startup performance.
    ctx.select().from("curio_server_framework_init").getSQL();
    return ctx;
}
Also used : DefaultConfiguration(org.jooq.impl.DefaultConfiguration) Configuration(org.jooq.Configuration) DataSourceConnectionProvider(org.jooq.impl.DataSourceConnectionProvider) DSLContext(org.jooq.DSLContext) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) Settings(org.jooq.conf.Settings) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 3 with DataSourceConnectionProvider

use of org.jooq.impl.DataSourceConnectionProvider in project spring-boot by spring-projects.

the class JooqAutoConfigurationTests method jooqWithDefaultConnectionProvider.

@Test
void jooqWithDefaultConnectionProvider() {
    this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class).run((context) -> {
        DSLContext dsl = context.getBean(DSLContext.class);
        ConnectionProvider connectionProvider = dsl.configuration().connectionProvider();
        assertThat(connectionProvider).isInstanceOf(DataSourceConnectionProvider.class);
        DataSource connectionProviderDataSource = ((DataSourceConnectionProvider) connectionProvider).dataSource();
        assertThat(connectionProviderDataSource).isInstanceOf(TransactionAwareDataSourceProxy.class);
    });
}
Also used : DataSourceConnectionProvider(org.jooq.impl.DataSourceConnectionProvider) DSLContext(org.jooq.DSLContext) ConnectionProvider(org.jooq.ConnectionProvider) DataSourceConnectionProvider(org.jooq.impl.DataSourceConnectionProvider) DataSource(javax.sql.DataSource) Test(org.junit.jupiter.api.Test)

Example 4 with DataSourceConnectionProvider

use of org.jooq.impl.DataSourceConnectionProvider in project steve by RWTH-i5-IDSG.

the class BeanConfiguration method dslContext.

/**
 * Can we re-use DSLContext as a Spring bean (singleton)? Yes, the Spring tutorial of
 * Jooq also does it that way, but only if we do not change anything about the
 * config after the init (which we don't do anyways) and if the ConnectionProvider
 * does not store any shared state (we use DataSourceConnectionProvider of Jooq, so no problem).
 *
 * Some sources and discussion:
 * - http://www.jooq.org/doc/3.6/manual/getting-started/tutorials/jooq-with-spring/
 * - http://jooq-user.narkive.com/2fvuLodn/dslcontext-and-threads
 * - https://groups.google.com/forum/#!topic/jooq-user/VK7KQcjj3Co
 * - http://stackoverflow.com/questions/32848865/jooq-dslcontext-correct-autowiring-with-spring
 */
@Bean
public DSLContext dslContext() {
    initDataSource();
    Settings settings = new Settings().withAttachRecords(false).withExecuteLogging(CONFIG.getDb().isSqlLogging());
    // Configuration for JOOQ
    org.jooq.Configuration conf = new DefaultConfiguration().set(SQLDialect.MYSQL).set(new DataSourceConnectionProvider(dataSource)).set(settings);
    return DSL.using(conf);
}
Also used : DataSourceConnectionProvider(org.jooq.impl.DataSourceConnectionProvider) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) Settings(org.jooq.conf.Settings) LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) Bean(org.springframework.context.annotation.Bean)

Example 5 with DataSourceConnectionProvider

use of org.jooq.impl.DataSourceConnectionProvider in project jOOQ by jOOQ.

the class SparkCRUD method main.

public static void main(String[] args) throws Exception {
    final BasicDataSource ds = new BasicDataSource();
    final Properties properties = new Properties();
    properties.load(SparkCRUD.class.getResourceAsStream("/config.properties"));
    ds.setDriverClassName(properties.getProperty("db.driver"));
    ds.setUrl(properties.getProperty("db.url"));
    ds.setUsername(properties.getProperty("db.username"));
    ds.setPassword(properties.getProperty("db.password"));
    final ConnectionProvider cp = new DataSourceConnectionProvider(ds);
    final Configuration configuration = new DefaultConfiguration().set(cp).set(SQLDialect.H2).set(new ThreadLocalTransactionProvider(cp, true));
    final DSLContext ctx = DSL.using(configuration);
    final JSONFormat format = new JSONFormat().format(true).header(false).recordFormat(RecordFormat.OBJECT);
    // Creates a new book resource, will return the ID to the created resource
    // author and title are sent as query parameters e.g. /books?author=Foo&title=Bar
    post("/books", (request, response) -> {
        return ctx.transactionResult(() -> {
            AuthorRecord author = upsertAuthor(ctx, request);
            BookRecord book = ctx.newRecord(BOOK);
            book.setAuthorId(author.getId());
            book.setTitle(request.queryParams("title"));
            book.store();
            // 201 Created
            response.status(201);
            return book.formatJSON(format);
        });
    });
    // Gets the book resource for the provided id
    get("/books/:id", (request, response) -> {
        Record2<String, String> book = ctx.select(BOOK.TITLE, AUTHOR.NAME).from(BOOK).join(AUTHOR).on(BOOK.AUTHOR_ID.eq(AUTHOR.ID)).where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).fetchOne();
        if (book != null) {
            return book.formatJSON(format);
        } else {
            // 404 Not found
            response.status(404);
            return "{\"error\":\"Book not found\"}";
        }
    });
    // Updates the book resource for the provided id with new information
    // author and title are sent as query parameters e.g. /books/<id>?author=Foo&title=Bar
    put("/books/:id", (request, response) -> {
        return ctx.transactionResult(() -> {
            BookRecord book = ctx.selectFrom(BOOK).where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).fetchOne();
            if (book != null) {
                AuthorRecord author = upsertAuthor(ctx, request);
                String newAuthor = request.queryParams("author");
                String newTitle = request.queryParams("title");
                if (newAuthor != null)
                    book.setAuthorId(author.getId());
                if (newTitle != null)
                    book.setTitle(newTitle);
                book.update();
                return book.formatJSON(format);
            } else {
                // 404 Not found
                response.status(404);
                return "{\"error\":\"Book not found\"}";
            }
        });
    });
    // Deletes the book resource for the provided id
    delete("/books/:id", (request, response) -> {
        return ctx.transactionResult(() -> {
            BookRecord book = ctx.deleteFrom(BOOK).where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).returning().fetchOne();
            if (book != null) {
                return book.formatJSON(format);
            } else {
                // 404 Not found
                response.status(404);
                return "{\"error\":\"Book not found\"}";
            }
        });
    });
    // Gets all available book resources
    get("/books", (request, response) -> {
        return ctx.select(BOOK.ID, BOOK.TITLE).from(BOOK).fetch().formatJSON(format);
    });
}
Also used : DefaultConfiguration(org.jooq.impl.DefaultConfiguration) Configuration(org.jooq.Configuration) DataSourceConnectionProvider(org.jooq.impl.DataSourceConnectionProvider) ThreadLocalTransactionProvider(org.jooq.impl.ThreadLocalTransactionProvider) DSLContext(org.jooq.DSLContext) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) Properties(java.util.Properties) JSONFormat(org.jooq.JSONFormat) ConnectionProvider(org.jooq.ConnectionProvider) DataSourceConnectionProvider(org.jooq.impl.DataSourceConnectionProvider) AuthorRecord(org.jooq.example.db.h2.tables.records.AuthorRecord) BookRecord(org.jooq.example.db.h2.tables.records.BookRecord) BasicDataSource(org.apache.commons.dbcp.BasicDataSource)

Aggregations

DataSourceConnectionProvider (org.jooq.impl.DataSourceConnectionProvider)7 DSLContext (org.jooq.DSLContext)5 DefaultConfiguration (org.jooq.impl.DefaultConfiguration)5 Configuration (org.jooq.Configuration)3 Settings (org.jooq.conf.Settings)3 Provides (dagger.Provides)2 Singleton (javax.inject.Singleton)2 ConnectionProvider (org.jooq.ConnectionProvider)2 HikariConfig (com.zaxxer.hikari.HikariConfig)1 HikariDataSource (com.zaxxer.hikari.HikariDataSource)1 SQLException (java.sql.SQLException)1 Properties (java.util.Properties)1 DataSource (javax.sql.DataSource)1 ContextExpression (liquibase.ContextExpression)1 LabelExpression (liquibase.LabelExpression)1 Liquibase (liquibase.Liquibase)1 ChangeLogParameters (liquibase.changelog.ChangeLogParameters)1 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)1 JdbcConnection (liquibase.database.jvm.JdbcConnection)1 DatabaseException (liquibase.exception.DatabaseException)1