@Test public void testSave() throws SQLException { final Configuration jooqConfig = new DefaultConfiguration().set(con).set(SQLDialect.MYSQL); final News news = insertNews(con, jooqConfig); // Test now final NewsTable newsTable = new NewsTable(); final News fetchedNews = DSL.using(jooqConfig).selectFrom(newsTable).where(newsTable.CONTENT_ID.eq(news.getId())).fetchOneInto(News.class); final ContentTable contentTable = new ContentTable(); final Content fetchedContent = DSL.using(jooqConfig).selectFrom(contentTable).where(contentTable.ID.eq(news.getId())).fetchOneInto(Content.class); assertNotNull(fetchedNews); assertNotNull(fetchedContent); }
@Test public void testGet() { final Configuration jooqConfig = new DefaultConfiguration().set(con).set(SQLDialect.MYSQL); final News news = insertNews(con, jooqConfig); final News fetchedNews = new NewsDao(con).getNews(news.getId()); assertNotNull(fetchedNews); assertEquals(news.getTitle(), fetchedNews.getTitle()); assertEquals(news.getText(), fetchedNews.getText()); assertEquals(news.getProviderId(), fetchedNews.getProviderId()); assertEquals(news.getCategoryId(), fetchedNews.getCategoryId()); assertEquals(news.getLocale(), fetchedNews.getLocale()); assertEquals(news.getLink(), fetchedNews.getLink()); assertEquals(news.getImageUrl(), fetchedNews.getImageUrl()); assertEquals(news.getImageWidth(), fetchedNews.getImageWidth()); assertEquals(news.getImageHeight(), fetchedNews.getImageHeight()); assertEquals(news.getNewsGroupId(), fetchedNews.getNewsGroupId()); }
private static void initInternal(final Vertx vertx, final String name) { vertxRef = vertx; Fn.pool(CONFIGS, name, () -> Infix.init(Plugins.Infix.JOOQ, (config) -> { // Initialized client final Configuration configuration = new DefaultConfiguration(); configuration.set(SQLDialect.MYSQL_8_0); final ConnectionProvider provider = new DefaultConnectionProvider(HikariCpPool.getConnection( config.getJsonObject("provider") )); // Initialized default configuration configuration.set(provider); return configuration; }, JooqInfix.class)); }
@Provides @Singleton static DSLContext dbContext( DataSource dataSource, @ForDatabase ListeningExecutorService dbExecutor) { Configuration configuration = new DefaultConfiguration() .set(dbExecutor) .set(SQLDialect.MYSQL) .set(new Settings().withRenderSchema(false)) .set(new DataSourceConnectionProvider(dataSource)) .set(DatabaseUtil.sfmRecordMapperProvider()); DSLContext ctx = DSL.using(configuration); // Eagerly trigger JOOQ classinit for better startup performance. ctx.select().from("curio_server_framework_init").getSQL(); return ctx; }
private String createDDL(DefaultConfiguration config) { DSLContext create = DSL.using(config); String ddl = create.alterTable(table("oidc_invitations")) .renameColumn(field("oidc_sub")) .to(field("oidc_payload", SQLDataType.CLOB)) .getSQL(); if (create.configuration().dialect() == SQLDialect.MYSQL) { Matcher m = Pattern.compile("\\s+RENAME\\s+COLUMN\\s+(\\w+)\\s+TO\\s+", Pattern.CASE_INSENSITIVE).matcher(ddl); StringBuffer sb = new StringBuffer(); if (m.find()) { m.appendReplacement(sb, " change " + m.group(1) + " "); m.appendTail(sb); sb.append(" text not null"); ddl = sb.toString(); } } return ddl; }
/** * 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() // Normally, the records are "attached" to the Configuration that created (i.e. fetch/insert) them. // This means that they hold an internal reference to the same database connection that was used. // The idea behind this is to make CRUD easier for potential subsequent store/refresh/delete // operations. We do not use or need that. .withAttachRecords(false) // To log or not to log the sql queries, that is the question .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); }
@Bean @ConditionalOnMissingBean(org.jooq.Configuration.class) public DefaultConfiguration jooqConfiguration() { DefaultConfiguration configuration = new DefaultConfiguration(); if (this.properties.getSqlDialect() != null) { configuration.set(this.properties.getSqlDialect()); } configuration.set(this.connectionProvider); if (this.transactionProvider != null) { configuration.set(this.transactionProvider); } if (this.recordMapperProvider != null) { configuration.set(this.recordMapperProvider); } if (this.settings != null) { configuration.set(this.settings); } configuration.set(this.recordListenerProviders); configuration.set(this.executeListenerProviders); configuration.set(this.visitListenerProviders); return configuration; }
@Override public void run(T dwConfiguration, Environment environment) throws Exception { final DataSourceFactory dbConfig = getDataSourceFactory(dwConfiguration); ManagedDataSource dataSource = dbConfig.build(environment.metrics(), "jooq"); this.configuration = new DefaultConfiguration(); this.configuration.set(new DataSourceConnectionProvider(dataSource)); configure(this.configuration); environment.jersey().register(JooqTransactionalApplicationListener.class); environment.jersey().register( new ConfigurationFactoryProvider.Binder(this.configuration, dataSource, multiTenantConnectionProvider)); environment.lifecycle().manage(dataSource); if (multiTenantConnectionProvider != null) { environment.lifecycle().manage(multiTenantConnectionProvider); } environment.healthChecks().register("jooq", new JooqHealthCheck( DSL.using(this.configuration.derive(new DefaultConnectionProvider(dataSource.getConnection()))), dbConfig.getValidationQuery())); }
@Provides @Singleton Configuration jooqConfigs(Config config) { HikariConfig hikaryConfig = new HikariConfig(); hikaryConfig.setJdbcUrl(config.get(ConfigConverters.ofString(), "db.jdbcUrl")); hikaryConfig.setUsername(config.get(ConfigConverters.ofString(), "db.username")); hikaryConfig.setPassword(config.get(ConfigConverters.ofString(), "db.password")); HikariDataSource dataSource = new HikariDataSource(hikaryConfig); Configuration jooqConfiguration = new DefaultConfiguration(); jooqConfiguration.set(new DataSourceConnectionProvider(dataSource)); jooqConfiguration.set(DATABASE_DIALECT); return jooqConfiguration; }
@Test public void testHsqlDb() throws SQLException { Connection conn = DbHelper.objectDb(); DSLContext dsl = DSL .using(new DefaultConfiguration().set(conn) .set(SQLDialect.HSQLDB) .set(SfmRecordMapperProviderFactory.newInstance().ignorePropertyNotFound().newProvider())); List<Issue318> list = dsl.select() .from("issue318").fetchInto(Issue318.class); assertEquals(1, list.size()); Issue318 value = list.get(0); assertTrue(Math.abs(value.getT().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() - System.currentTimeMillis()) < 10000); assertNotNull(value.getId()); }
@Test public void testIgnoreFields() throws Exception { Connection conn = DbHelper.objectDb(); DSLContext dsl = DSL .using(new DefaultConfiguration().set(conn) .set(SQLDialect.HSQLDB) .set(SfmRecordMapperProviderFactory.newInstance().addAlias("id", "noId").ignorePropertyNotFound().newProvider())); List<DbObject> list = dsl.select() .from("TEST_DB_OBJECT").fetchInto(DbObject.class); assertEquals(2, list.size()); assertEquals(0, list.get(0).getId()); list.get(0).setId(1); DbHelper.assertDbObjectMapping(list.get(0)); }
@Setup public void init() throws Exception { ConnectionParam cp = new ConnectionParam(); cp.db = db; cp.init(); dslNoSfmMapping = DSL.using(new DefaultConfiguration().set(cp.dataSource).set( db.getSqlDialect())); dslNoSfmMappingselectFromSmallBenchMark = dslNoSfmMapping.selectFrom(TestSmallBenchmarkObject.TEST_SMALL_BENCHMARK_OBJECT); dslSfmMapping = DSL. using(new DefaultConfiguration().set(cp.dataSource) .set(db.getSqlDialect()) .set(new SfmRecordMapperProvider())); dslSfmMappingselectFromSmallBenchMark = dslSfmMapping.selectFrom(TestSmallBenchmarkObject.TEST_SMALL_BENCHMARK_OBJECT); }
public CollectModelManager(SurveyManager surveyManager, RecordManager recordManager, CodeListManager codeListManager, SpeciesManager speciesManager, RecordFileManager recordFileManager, Database database) { this.surveyManager = surveyManager; this.recordManager = recordManager; this.codeListManager = codeListManager; this.speciesManager = speciesManager; this.recordFileManager = recordFileManager; codeListSizeEvaluator = new CodeListSizeEvaluator(new DatabaseCodeListSizeDao(database)); DefaultConfiguration defaultConfiguration = new DefaultConfiguration(); defaultConfiguration.setSettings(defaultConfiguration.settings().withRenderSchema(false)); defaultConfiguration .set(database.dataSource()) .set(SQLDialect.SQLITE); jooqDsl = new CollectDSLContext(defaultConfiguration); }
private void setupDatabase() { System.setProperty("org.jooq.no-logo", "true"); dataSource = dataSourceFactory.createDataSource("cattle"); DataSourceConnectionProvider dscp = new DataSourceConnectionProvider(dataSource); ThreadLocalTransactionProvider tp = new ThreadLocalTransactionProvider(dscp, false); LoggerListener logger = new LoggerListener(); logger.setMaxLength(1000); ExecuteListener[] listeners = new ExecuteListener[] { logger, new StopWatchListener() }; Settings settings = dbSetting("cattle"); jooqConfig = new DefaultConfiguration() .set(getSQLDialect("cattle")) .set(settings) .set(dscp) .set(tp) .set(DefaultExecuteListenerProvider.providers(listeners)); }
private HealthCheck.Result runHealthCheck(MockDataProvider provider) throws Exception { MockConnection mockConnection = new MockConnection(provider) { @Override public Savepoint setSavepoint() throws SQLException { return new Savepoint() { @Override public int getSavepointId() throws SQLException { return 0; } @Override public String getSavepointName() throws SQLException { return "savepoint"; } }; } }; Configuration configuration = new DefaultConfiguration().set(mockConnection); configuration.settings().setExecuteLogging(false); JooqHealthCheck healthCheck = new JooqHealthCheck(configuration, validationQuery); return healthCheck.check(); }
void run(Transactional tx) { // Initialise some jOOQ objects final DefaultConnectionProvider c = new DefaultConnectionProvider(connection); final Configuration configuration = new DefaultConfiguration().set(c).set(SQLDialect.H2); try { // Run the transaction and pass a jOOQ // DSLContext object to it tx.run(DSL.using(configuration)); // If we get here, then commit the // transaction c.commit(); } catch (RuntimeException e) { // Any exception will cause a rollback c.rollback(); System.err.println(e.getMessage()); // Eat exceptions in silent mode. if (!silent) throw e; } }
@Override public void configure(final Env env, final Config conf, final Binder binder) { Key<DataSource> dskey = Key.get(DataSource.class, Names.named(name)); HikariDataSource ds = (HikariDataSource) env.get(dskey) .orElseThrow(() -> new NoSuchElementException("DataSource missing: " + dskey)); Configuration jooqconf = new DefaultConfiguration(); ConnectionProvider dscp = new DataSourceConnectionProvider(ds); jooqconf.set(JDBCUtils.dialect(ds.getDataSourceProperties().getProperty("url"))); jooqconf.set(dscp); jooqconf.set(new DefaultTransactionProvider(dscp)); if (callback != null) { callback.accept(jooqconf, conf); } ServiceKey serviceKey = env.serviceKey(); serviceKey.generate(Configuration.class, name, k -> binder.bind(k).toInstance(jooqconf)); Provider<DSLContext> dsl = () -> DSL.using(jooqconf); serviceKey.generate(DSLContext.class, name, k -> binder.bind(k).toProvider(dsl)); }
@Test(timeout = 4000) public void test05() throws Throwable { WorkspaceSnapshot workspaceSnapshot0 = new WorkspaceSnapshot(); Product product0 = new Product(); workspaceSnapshot0.definingProduct = product0; DefaultConfiguration defaultConfiguration0 = new DefaultConfiguration(); NoConnectionProvider noConnectionProvider0 = (NoConnectionProvider) defaultConfiguration0.connectionProvider(); SQLDialect sQLDialect0 = SQLDialect.SQLITE; Settings settings0 = new Settings(); DefaultDSLContext defaultDSLContext0 = new DefaultDSLContext(noConnectionProvider0, sQLDialect0, settings0); // Undeclared exception! try { workspaceSnapshot0.loadDefiningProduct(defaultDSLContext0); fail("Expecting exception: RuntimeException"); } catch (RuntimeException e) { // // Cannot execute query. No Connection configured // assertThrownBy("org.jooq.impl.AbstractQuery", e); } }
@Test(timeout = 4000) public void test14() throws Throwable { WorkspaceSnapshot workspaceSnapshot0 = new WorkspaceSnapshot(); DefaultConfiguration defaultConfiguration0 = new DefaultConfiguration(); DefaultDSLContext defaultDSLContext0 = new DefaultDSLContext(defaultConfiguration0); // Undeclared exception! try { workspaceSnapshot0.deltaFrom(defaultDSLContext0, workspaceSnapshot0); fail("Expecting exception: NullPointerException"); } catch (NullPointerException e) { // // no message in exception (getMessage() returned null) // assertThrownBy("com.chiralbehaviors.CoRE.workspace.WorkspaceSnapshot", e); } }
/** * Creates a new instance with the given {@link Connection}. * @param connection the {@link Connection} to use. If <code>null</code> a new {@link Connection} * will automatically acquired. */ public ADao(final Connection connection) { if(connection == null) { jooqConfig = new DefaultConfiguration().set(DBConnectionProvider.getInstance()); } else { jooqConfig = new DefaultConfiguration().set(connection); } jooqConfig.set(SQLDialect.MYSQL); }
@Inject DSLContextProviderImpl(DataSource dataSource, SQLDialect sqlDialect) { // ThreadLocalTransactionProvider handles all of the ThreadLocal semantics for us this.configuration = new DefaultConfiguration() .set(sqlDialect) .set(new ThreadLocalTransactionProvider(new DataSourceConnectionProvider(dataSource))); }
@Override protected SQLClient createDbClient(JsonObject config) { JsonObject myConfig = new JsonObject(); if(config.containsKey("db_host")) myConfig.put("host", config.getString("db_host")); if(config.containsKey("db_port")) myConfig.put("port", config.getInteger("db_port")); if(config.containsKey("db_user")) myConfig.put("username", config.getString("db_user")); if(config.containsKey("db_pass")) myConfig.put("password", config.getString("db_pass")); if(config.containsKey("db_name")) myConfig.put("database", config.getString("db_name")); myConfig.put("max_pool_size", config.getInteger("db_max_pool_size", 30)); Vertx vertx = AppGlobals.get().getVertx(); AsyncSQLClient dbClient = PostgreSQLClient.createNonShared(vertx, myConfig); AsyncJooqSQLClient client = AsyncJooqSQLClient.create(vertx, dbClient); Configuration configuration = new DefaultConfiguration(); configuration.set(SQLDialect.POSTGRES); PagesDao dao = new PagesDao(configuration); dao.setClient(client); AppGlobals.get().setGlobal("dao", dao); return dbClient; }
/** * Controller no parameter constructor * It's setting needed daos with configuration */ UserController() { try { String DB_URL = "jdbc:sqlite:test.db"; connection = DriverManager.getConnection(DB_URL); } catch (SQLException e) { e.printStackTrace(); } Configuration configuration = new DefaultConfiguration().set(connection).set(SQLDialect.SQLITE); usersDao = new UsersDao(configuration); sessionDataDao = new SessionDataDao(configuration); }
/** * Controller no parameter constructor * It's setting needed daos with configuration */ FileController() { try { String DB_URL = "jdbc:sqlite:test.db"; connection = DriverManager.getConnection(DB_URL); } catch (SQLException e) { e.printStackTrace(); } Configuration configuration = new DefaultConfiguration().set(connection).set(SQLDialect.SQLITE); fileMetadataDao = new FileMetadataDao(configuration); folderMetadataDao = new FolderMetadataDao(configuration); fileContentsDao = new FileContentsDao(configuration); }
@Bean public DSLContext getDSLContext() { HikariDataSource hikariDataSource = new HikariDataSource(); hikariDataSource.setJdbcUrl(environment.getProperty("spring.datasource.url")); hikariDataSource.setUsername(environment.getProperty("spring.datasource.username")); hikariDataSource.setPassword(environment.getProperty("spring.datasource.password")); ConnectionProvider connectionProvider = new DataSourceConnectionProvider(hikariDataSource); org.jooq.Configuration configuration = new DefaultConfiguration().set(connectionProvider).set(SQLDialect.MYSQL); return DSL.using(configuration); }
@BeforeClass public static void beforeClass() throws SQLException { TestTool.setupDB(); Configuration configuration = new DefaultConfiguration(); configuration.set(SQLDialect.MYSQL); JsonObject config = new JsonObject().put("host", "127.0.0.1").put("username", "vertx").putNull("password").put("database","vertx"); dao = new SomethingDao(configuration); Vertx vertx = Vertx.vertx(); dao.setClient(AsyncJooqSQLClient.create(vertx,MySQLClient.createNonShared(vertx, config))); compositeDao = new SomethingcompositeDao(configuration); compositeDao.setClient(AsyncJooqSQLClient.create(vertx,MySQLClient.createNonShared(vertx, config))); }
@BeforeClass public static void beforeClass() throws SQLException { TestTool.setupDB(); Configuration configuration = new DefaultConfiguration(); configuration.set(SQLDialect.MYSQL); JsonObject config = new JsonObject().put("host", "127.0.0.1").put("username", "vertx").putNull("password").put("database","vertx"); dao = new SomethingDao(configuration); Vertx vertx = Vertx.vertx(); dao.setClient(AsyncJooqSQLClient.create(vertx, MySQLClient.createNonShared(vertx, config))); compositeDao = new SomethingcompositeDao(configuration); compositeDao.setClient(AsyncJooqSQLClient.create(vertx,MySQLClient.createNonShared(vertx, config))); }
@BeforeClass public static void beforeClass() throws SQLException { // TestTool.setupDB(); System.setProperty("vertx.logger-delegate-factory-class-name", SLF4JLogDelegateFactory.class.getName()); Configuration configuration = new DefaultConfiguration(); configuration.set(SQLDialect.MYSQL); JsonObject config = new JsonObject().put("host", "127.0.0.1").put("username", "vertx").putNull("password").put("database","vertx"); dao = new SomethingDao(configuration); Vertx vertx = Vertx.vertx(); dao.setClient(AsyncJooqSQLClient.create(vertx, MySQLClient.createNonShared(vertx, config))); compositeDao = new SomethingcompositeDao(configuration); compositeDao.setClient(AsyncJooqSQLClient.create(vertx, MySQLClient.createNonShared(vertx, config))); }
public static DefaultConfiguration defaultConfigFromDataSource(DataSource ds) { DataSourceConnectionProvider dcp = new DataSourceConnectionProvider(ds); DefaultConfiguration jooqConfig = new DefaultConfiguration(); jooqConfig.set(SQLDialect.MYSQL); jooqConfig.set(dcp); return jooqConfig; }
@Test public void testMysql() { DefaultConfiguration config = new DefaultConfiguration(); config.setSQLDialect(SQLDialect.MYSQL); assertThat(createDDL(config)).containsIgnoringCase("CHANGE"); }
@Override public final void migrate(Connection connection) throws Exception { didExecute = true; SQLDialect dialect = JDBCUtils.dialect(connection); if (SQLDialect.DEFAULT.equals(dialect)) throw new IllegalStateException("Dialect couldn't be deducted from connection " + connection); Configuration configuration = new DefaultConfiguration().set(connection).set(dialect); DdlExecuteListener listener = new DdlExecuteListener(); configuration.set(new DefaultExecuteListenerProvider(listener)); DSLContext create = DSL.using(configuration); migrate(connection, create); ddlInstructionExecuted = listener.ddlInstructionExecuted(); }
public DSLContext getDSLContext() { if (dslContext == null) { Configuration defaultConfiguration = new DefaultConfiguration().set(getConnection()) .set(SQLDialect.MYSQL); dslContext = DSL.using(defaultConfiguration); } return dslContext; }
DSLContext get(Connection conn) { return DSL.using(new DefaultConfiguration() .set(conn) .set(JDBCUtils.dialect(conn)) .set(settings) .set(listenerProvider)); }
@BeforeClass public static void beforeClass() throws SQLException { TestTool.setupDB(); Configuration configuration = new DefaultConfiguration(); configuration.set(SQLDialect.HSQLDB); configuration.set(DriverManager.getConnection("jdbc:hsqldb:mem:test", "test", "")); dao = new SomethingDao(configuration); dao.setVertx(Vertx.vertx()); compositeDao = new SomethingcompositeDao(configuration); compositeDao.setVertx(Vertx.vertx()); }