repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestQueryCleanup.java
jdbi/src/test/java/org/skife/jdbi/v2/TestQueryCleanup.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import static java.lang.String.format; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.UUID; import org.h2.jdbcx.JdbcDataSource; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.killbill.commons.utils.collect.Iterators; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.util.IntegerMapper; @Category(JDBITests.class) public class TestQueryCleanup { private static final int COUNT = 100; private DBI dbi; @Before public void setUp() throws Exception { final JdbcDataSource ds = new JdbcDataSource(); ds.setURL(format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1", UUID.randomUUID())); dbi = new DBI(ds); dbi.withHandle(new HandleCallback<Void>() { @Override public Void withHandle(final Handle handle) { handle.execute("create table something (id int primary key, name varchar(100))"); for (int i = 0; i < COUNT; i++) { handle.createStatement("insert into something (id, name) values (:id, :name)") .bind("id", i) .bind("name", UUID.randomUUID().toString()) .execute(); } return null; } }); } @Test public void testBasicCleanupHandle() throws Exception { final Handle handle = dbi.open(); final Query<Integer> q = handle.createQuery("SELECT COUNT(1) FROM something").map(IntegerMapper.FIRST); final ResultIterator<Integer> it = q.iterator(); assertEquals(COUNT, Iterators.getOnlyElement(it).intValue()); assertFalse(it.hasNext()); assertFalse(handle.getConnection().isClosed()); handle.close(); assertTrue(handle.getConnection().isClosed()); } @Test public void testBasicCleanupIterator() throws Exception { final Handle handle = dbi.open(); final Query<Integer> q = handle.createQuery("SELECT COUNT(1) FROM something") .cleanupHandle() .map(IntegerMapper.FIRST); final ResultIterator<Integer> it = q.iterator(); assertEquals(COUNT, Iterators.getOnlyElement(it).intValue()); assertFalse(it.hasNext()); assertTrue(handle.getConnection().isClosed()); } @Test public void testBasicCleanupHalfwayHandle1() throws Exception { final Handle handle = dbi.open(); final Query<Integer> q = handle.createQuery("SELECT id FROM something").map(IntegerMapper.FIRST); final ResultIterator<Integer> it = q.iterator(); for (int i = 0; i < COUNT / 2; i++) { assertTrue(it.hasNext()); it.next(); } assertTrue(it.hasNext()); assertFalse(handle.getConnection().isClosed()); handle.close(); assertTrue(handle.getConnection().isClosed()); } @Test public void testBasicCleanupHalfwayHandle2() throws Exception { final Handle handle = dbi.open(); final Query<Integer> q = handle.createQuery("SELECT id FROM something") .cleanupHandle() .map(IntegerMapper.FIRST); final ResultIterator<Integer> it = q.iterator(); for (int i = 0; i < COUNT / 2; i++) { assertTrue(it.hasNext()); it.next(); } assertTrue(it.hasNext()); assertFalse(handle.getConnection().isClosed()); handle.close(); assertTrue(handle.getConnection().isClosed()); } @Test public void testBasicCleanupHalfwayIterator() throws Exception { final Handle handle = dbi.open(); final Query<Integer> q = handle.createQuery("SELECT id FROM something") .cleanupHandle() .map(IntegerMapper.FIRST); final ResultIterator<Integer> it = q.iterator(); for (int i = 0; i < COUNT / 2; i++) { assertTrue(it.hasNext()); it.next(); } assertTrue(it.hasNext()); assertFalse(handle.getConnection().isClosed()); it.close(); assertTrue(handle.getConnection().isClosed()); } @Test public void testDoubleCleanup() throws Exception { final Handle handle = dbi.open(); final Query<Integer> q = handle .createQuery("SELECT id FROM something") .cleanupHandle() .cleanupHandle() .map(IntegerMapper.FIRST); final ResultIterator<Integer> it = q.iterator(); while (it.hasNext()) { it.next(); } assertFalse(it.hasNext()); assertTrue(handle.getConnection().isClosed()); } @Test public void testDoubleCleanupHalfwayHandle() throws Exception { final Handle handle = dbi.open(); final Query<Integer> q = handle .createQuery("SELECT id FROM something") .cleanupHandle() .cleanupHandle() .map(IntegerMapper.FIRST); final ResultIterator<Integer> it = q.iterator(); for (int i = 0; i < COUNT / 2; i++) { assertTrue(it.hasNext()); it.next(); } assertTrue(it.hasNext()); assertFalse(handle.getConnection().isClosed()); handle.close(); assertTrue(handle.getConnection().isClosed()); } @Test public void testDoubleCleanupHalfwayIterator() throws Exception { final Handle handle = dbi.open(); final Query<Integer> q = handle .createQuery("SELECT id FROM something") .cleanupHandle() .cleanupHandle() .map(IntegerMapper.FIRST); final ResultIterator<Integer> it = q.iterator(); for (int i = 0; i < COUNT / 2; i++) { assertTrue(it.hasNext()); it.next(); } assertTrue(it.hasNext()); assertFalse(handle.getConnection().isClosed()); it.close(); assertTrue(handle.getConnection().isClosed()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestTooManyCursors.java
jdbi/src/test/java/org/skife/jdbi/v2/TestTooManyCursors.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.CallbackFailedException; import org.skife.jdbi.v2.tweak.HandleCallback; import java.io.PrintWriter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import javax.sql.DataSource; import static org.junit.Assert.fail; /** * Oracle was getting angry about too many open cursors because of the large number * of prepared statements being created and cached indefinitely. */ @Category(JDBITests.class) public class TestTooManyCursors extends DBITestCase { @Test public void testFoo() throws Exception { DataSource ds = DERBY_HELPER.getDataSource(); DataSource dataSource = new ErrorProducingDataSource(ds, 99); IDBI dbi = new DBI(dataSource); try { dbi.withHandle(new HandleCallback<Object>() { @Override public Void withHandle(Handle handle) throws Exception { handle.setStatementBuilder(new DefaultStatementBuilder()); for (int idx = 0; idx < 100; idx++) { handle.createQuery("SELECT " + idx + " FROM something").first(); } return null; } }); } catch (CallbackFailedException e) { fail("We have too many open connections"); } } private static class ErrorProducingDataSource implements DataSource { private final DataSource target; private final int connCount; ErrorProducingDataSource(DataSource target, int i) { this.target = target; connCount = i; } @Override public Connection getConnection() throws SQLException { return ConnectionInvocationHandler.newInstance(target.getConnection(), connCount); } @Override public Connection getConnection(String string, String string1) throws SQLException { return ConnectionInvocationHandler.newInstance(target.getConnection(string, string1), connCount); } @Override public PrintWriter getLogWriter() throws SQLException { return target.getLogWriter(); } @Override public void setLogWriter(PrintWriter printWriter) throws SQLException { target.setLogWriter(printWriter); } @Override public void setLoginTimeout(int i) throws SQLException { target.setLoginTimeout(i); } @Override public int getLoginTimeout() throws SQLException { return target.getLoginTimeout(); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new UnsupportedOperationException(); } } private static class ConnectionInvocationHandler implements InvocationHandler { private Connection connection; private int numSuccessfulStatements; private int numStatements = 0; public static Connection newInstance(Connection connection, int numSuccessfulStatements) { return (Connection) Proxy.newProxyInstance(connection.getClass().getClassLoader(), new Class[]{Connection.class}, new ConnectionInvocationHandler(connection, numSuccessfulStatements)); } public ConnectionInvocationHandler(Connection connection, int numSuccessfulStatements) { this.connection = connection; this.numSuccessfulStatements = numSuccessfulStatements; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if ("createStatement".equals(method.getName()) || "prepareCall".equals(method.getName()) || "prepareStatement".equals(method.getName())) { if (++numStatements > numSuccessfulStatements) { throw new SQLException("Fake 'maximum open cursors exceeded' error"); } return StatementInvocationHandler.newInstance((Statement) method.invoke(connection, args), this); } else { return method.invoke(connection, args); } } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } public void registerCloseStatement() { numStatements--; } } private static class StatementInvocationHandler implements InvocationHandler { private Statement stmt; private ConnectionInvocationHandler connectionHandler; public static Statement newInstance(Statement stmt, ConnectionInvocationHandler connectionHandler) { Class<?> o = stmt.getClass(); List<Class<?>> interfaces = new ArrayList<Class<?>>(); while (!o.equals(Object.class)) { interfaces.addAll(Arrays.asList((Class<?> [])o.getInterfaces())); o = o.getSuperclass(); } return (Statement) Proxy.newProxyInstance(stmt.getClass().getClassLoader(), interfaces.toArray(new Class[interfaces.size()]), new StatementInvocationHandler(stmt, connectionHandler)); } public StatementInvocationHandler(Statement stmt, ConnectionInvocationHandler connectionHandler) { this.stmt = stmt; this.connectionHandler = connectionHandler; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("close".equals(method.getName())) { connectionHandler.registerCloseStatement(); } try { return method.invoke(stmt, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestCallable.java
jdbi/src/test/java/org/skife/jdbi/v2/TestCallable.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import java.sql.Types; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestCallable extends DBITestCase { private BasicHandle h; @Override public void doSetUp() throws Exception { h = openHandle(); try { h.execute("drop function to_degrees"); h.execute("drop procedure test_procedure"); } catch (Exception e) { // okay if not present } h.execute("CREATE FUNCTION TO_DEGREES(RADIANS DOUBLE) RETURNS DOUBLE\n" + "PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA\n" + "EXTERNAL NAME 'java.lang.Math.toDegrees'"); h.execute("CREATE PROCEDURE TEST_PROCEDURE(in in_param varchar(20), out out_param varchar(20))\n" + "PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA\n" + "EXTERNAL NAME 'org.skife.jdbi.v2.TestCallable.testProcedure'"); } @Override public void doTearDown() throws Exception { try { h.execute("drop function to_degrees"); h.execute("drop procedure test_procedure"); } catch (Exception e) { // okay if not present } if (h != null) h.close(); } @Test public void testStatement() throws Exception { OutParameters ret = h.createCall("? = CALL TO_DEGREES(?)") .registerOutParameter(0, Types.DOUBLE) .bind(1, 100.0d) .invoke(); // JDBI oddity : register or bind is 0-indexed, which JDBC is 1-indexed. Double expected = Math.toDegrees(100.0d); assertEquals(expected, ret.getDouble(1)); assertEquals(expected.longValue(), ret.getLong(1).longValue()); assertEquals(expected.shortValue(), ret.getShort(1).shortValue()); assertEquals(expected.intValue(), ret.getInt(1).intValue()); assertEquals(expected.floatValue(), ret.getFloat(1), 0.001); try { ret.getDate(1); fail("didn't throw exception !"); } catch (Exception e) { //e.printStackTrace(); } try { ret.getDate(2); fail("didn't throw exception !"); } catch (Exception e) { //e.printStackTrace(); } } @Test public void testStatementWithNamedParam() throws Exception { OutParameters ret = h.createCall(":x = CALL TO_DEGREES(:y)") .registerOutParameter("x", Types.DOUBLE) .bind("y", 100.0d) .invoke(); Double expected = Math.toDegrees(100.0d); assertEquals(expected, ret.getDouble("x")); assertEquals(expected.longValue(), ret.getLong("x").longValue()); assertEquals(expected.shortValue(), ret.getShort("x").shortValue()); assertEquals(expected.intValue(), ret.getInt("x").intValue()); assertEquals(expected.floatValue(), ret.getFloat("x"), 0.001); try { ret.getDate("x"); fail("didn't throw exception !"); } catch (Exception e) { //e.printStackTrace(); } try { ret.getDate("y"); fail("didn't throw exception !"); } catch (Exception e) { assertTrue(true); } } @Test public void testWithNullReturn() throws Exception { OutParameters ret = h.createCall("CALL TEST_PROCEDURE(?, ?)") .bind(0, (String)null) .registerOutParameter(1, Types.VARCHAR) .invoke(); // JDBI oddity : register or bind is 0-indexed, which JDBC is 1-indexed. String out = ret.getString(2); assertEquals(out, null); } @Test public void testWithNullReturnWithNamedParam() throws Exception { OutParameters ret = h.createCall("CALL TEST_PROCEDURE(:x, :y)") .bind("x", (String)null) .registerOutParameter("y", Types.VARCHAR) .invoke(); String out = ret.getString("y"); assertEquals(out, null); } public static void testProcedure(String in, String[] out) { out = new String[1]; out[0] = in; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/TestStatementExceptionContext.java
jdbi/src/test/java/org/skife/jdbi/v2/TestStatementExceptionContext.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.exceptions.StatementException; import static org.junit.Assert.assertEquals; /** * */ @Category(JDBITests.class) public class TestStatementExceptionContext extends DBITestCase { @Test public void testFoo() throws Exception { Handle h = openHandle(); try { h.insert("WOOF", 7, "Tom"); } catch (StatementException e) { assertEquals(e.getStatementContext().getRawSql(), "WOOF"); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestClasspathStatementLocator.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestClasspathStatementLocator.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestClasspathStatementLocator { private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); DBI dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testBam() throws Exception { handle.execute("insert into something (id, name) values (6, 'Martin')"); Something s = handle.attach(Cromulence.class).findById(6L); assertThat(s.getName(), equalTo("Martin")); } static interface Cromulence { @SqlQuery public Something findById(@Bind("id") Long id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/MapWith.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/MapWith.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface MapWith { Class<? extends ResultSetMapper> value(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestClassBasedSqlObject.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestClassBasedSqlObject.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.subpackage.SomethingDao; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestClassBasedSqlObject { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testPassThroughMethod() throws Exception { Dao dao = handle.attach(Dao.class); dao.insert(3, "Cora"); Something c = dao.findByIdHeeHee(3); assertThat(c, equalTo(new Something(3, "Cora"))); } @Test(expected = AbstractMethodError.class) public void testUnimplementedMethod() throws Exception { Dao dao = handle.attach(Dao.class); dao.totallyBroken(); } @Test public void testPassThroughMethodWithDaoInAnotherPackage() throws Exception { SomethingDao dao = handle.attach(SomethingDao.class); dao.insert(3, "Cora"); Something c = dao.findByIdHeeHee(3); assertThat(c, equalTo(new Something(3, "Cora"))); } @Test(expected = AbstractMethodError.class) public void testUnimplementedMethodWithDaoInAnotherPackage() throws Exception { SomethingDao dao = handle.attach(SomethingDao.class); dao.totallyBroken(); } public static abstract class Dao { @SqlUpdate("insert into something (id, name) values (:id, :name)") public abstract void insert(@Bind("id") int id, @Bind("name") String name); @SqlQuery("select id, name from something where id = :id") public abstract Something findById(@Bind("id") int id); public Something findByIdHeeHee(int id) { return findById(id); } public abstract void totallyBroken(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestTransactionAnnotation.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestTransactionAnnotation.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.exceptions.TransactionFailedException; import java.io.IOException; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestTransactionAnnotation { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testTx() throws Exception { Dao dao = handle.attach(Dao.class); Something s = dao.insertAndFetch(1, "Ian"); assertThat(s, equalTo(new Something(1, "Ian"))); } @Test public void testTxFail() throws Exception { Dao dao = handle.attach(Dao.class); try { dao.failed(1, "Ian"); fail("should have raised exception"); } catch (TransactionFailedException e) { assertThat(e.getCause().getMessage(), equalTo("woof")); } assertThat(dao.findById(1), nullValue()); } @Test public void testNestedTransactions() throws Exception { Dao dao = handle.attach(Dao.class); Something s = dao.insertAndFetchWithNestedTransaction(1, "Ian"); assertThat(s, equalTo(new Something(1, "Ian"))); } @Test public void testTxActuallyCommits() throws Exception { Handle h2 = dbi.open(); Dao one = handle.attach(Dao.class); Dao two = h2.attach(Dao.class); // insert in @Transaction method Something inserted = one.insertAndFetch(1, "Brian"); // fetch from another connection Something fetched = two.findById(1); assertThat(fetched, equalTo(inserted)); } @Test public void testConcurrent() throws Exception { ExecutorService es = Executors.newFixedThreadPool(3); final CountDownLatch inserted = new CountDownLatch(1); final CountDownLatch committed = new CountDownLatch(1); final Other o = dbi.onDemand(Other.class); Future<Void> rf = es.submit(new Callable<Void>() { @Override public Void call() throws Exception { try { o.insert(inserted, 1, "diwaker"); committed.countDown(); return null; } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); return null; } } }); Future<Void> tf = es.submit(new Callable<Void>() { @Override public Void call() throws Exception { try { inserted.await(); committed.await(); Something s2 = o.find(1); assertThat(s2, equalTo(new Something(1, "diwaker"))); return null; } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); return null; } } }); rf.get(); tf.get(); es.shutdown(); } public static abstract class Other { @Transaction public void insert(CountDownLatch inserted, int id, String name) throws InterruptedException { reallyInsert(id, name); inserted.countDown(); } @SqlUpdate("insert into something (id, name) values (:id, :name)") public abstract void reallyInsert(@Bind("id") int id, @Bind("name") String name); @SqlQuery("select id, name from something where id = :id") public abstract Something find(@Bind("id") int id); } public static abstract class Dao { @SqlUpdate("insert into something (id, name) values (:id, :name)") public abstract void insert(@Bind("id") int id, @Bind("name") String name); @SqlQuery("select id, name from something where id = :id") public abstract Something findById(@Bind("id") int id); @Transaction(TransactionIsolationLevel.READ_COMMITTED) public Something insertAndFetch(int id, String name) { insert(id, name); return findById(id); } @Transaction public Something insertAndFetchWithNestedTransaction(int id, String name) { return insertAndFetch(id, name); } @Transaction public Something failed(int id, String name) throws IOException { insert(id, name); throw new IOException("woof"); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/SomethingMapper.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/SomethingMapper.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; public class SomethingMapper implements ResultSetMapper<Something> { @Override public Something map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new Something(r.getInt("id"), r.getString("name")); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestGetGeneratedKeys.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestGetGeneratedKeys.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcConnectionPool; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import org.skife.jdbi.v2.tweak.HandleCallback; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestGetGeneratedKeys { private JdbcConnectionPool ds; private DBI dbi; @Before public void setUp() throws Exception { ds = JdbcConnectionPool.create("jdbc:h2:mem:" + UUID.randomUUID(), "username", "password"); dbi = new DBI(ds); dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(Handle handle) throws Exception { handle.execute("create table something (id identity primary key, name varchar(32))"); return null; } }); } @After public void tearDown() throws Exception { ds.dispose(); } public static interface DAO extends CloseMe { @SqlUpdate("insert into something (name) values (:it)") @GetGeneratedKeys public long insert(@Bind String name); @SqlQuery("select name from something where id = :it") public String findNameById(@Bind long id); } @Test public void testFoo() throws Exception { DAO dao = dbi.open(DAO.class); long brian_id = dao.insert("Brian"); long keith_id = dao.insert("Keith"); assertThat(dao.findNameById(brian_id), equalTo("Brian")); assertThat(dao.findNameById(keith_id), equalTo("Keith")); dao.close(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestMapBinder.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestMapBinder.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.h2.jdbcx.JdbcDataSource; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.tweak.ResultSetMapper; import junit.framework.TestCase; @Category(JDBITests.class) public class TestMapBinder extends TestCase { private DBI dbi; private Handle handle; @Override public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:test"); dbi = new DBI(ds); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100), a varchar(100), b int, c varchar(100))"); } @Override public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } public void testInsert() throws Exception { Spiffy s = handle.attach(Spiffy.class); s.insert(allMap(5, "woo", 3, "too")); Result elem = s.load(5); assertEquals("too", elem.c); assertEquals(3, elem.b); } public void testUpdate() throws Exception { Spiffy s = handle.attach(Spiffy.class); s.insert(allMap(4, "woo", 1, "too")); Map<String, Object> update = new HashMap<String, Object>(); update.put("a", "goo"); update.put("b", 2); update.put("c", null); assertEquals(1, s.update(4, update)); Result elem = s.load(4); assertEquals("goo", elem.a); assertEquals(2, elem.b); assertEquals("too", elem.c); } public void testUpdatePrefix() throws Exception { Spiffy s = handle.attach(Spiffy.class); s.insert(allMap(4, "woo", 1, "too")); Map<Object, Object> update = new HashMap<Object, Object>(); update.put("b", 2); update.put(new A(), "goo"); assertEquals(1, s.updatePrefix(4, update)); Result elem = s.load(4); assertEquals("goo", elem.a); assertEquals(1, elem.b); // filtered out by annotation value assertEquals("too", elem.c); } private Map<String, Object> allMap(int id, Object a, int b, Object c) { Map<String, Object> map = new HashMap<String, Object>(); map.put("id", id); map.put("a", a); map.put("b", b); map.put("c", c); return map; } interface Spiffy { @SqlUpdate("insert into something (id, a, b, c) values (:id, :a, :b, :c)") int insert(@BindMap Map<String, Object> bindings); @SqlUpdate("update something set a=coalesce(:a, a), b=coalesce(:b, b), c=coalesce(:c, c) where id=:id") int update(@Bind("id") int id, @BindMap Map<String, Object> updates); @SqlUpdate("update something set a=coalesce(:asdf.a, a), c=coalesce(:asdf.c, c) where id=:id") int updatePrefix(@Bind("id") int id, @BindMap(prefix="asdf", value={"a","c"}, implicitKeyStringConversion=true) Map<Object, Object> updates); @SqlQuery("select * from something where id = :id") @Mapper(ResultMapper.class) Result load(@Bind("id") int id); } static class ResultMapper implements ResultSetMapper<Result> { @Override public Result map(int index, ResultSet r, StatementContext ctx) throws SQLException { Result ret = new Result(); ret.id = r.getInt("id"); ret.a = r.getString("a"); ret.b = r.getInt("b"); ret.c = r.getString("c"); return ret; } } static class Result { String a, c; int id, b; } static class A { @Override public String toString() { return "a"; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestStatements.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestStatements.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import org.skife.jdbi.v2.util.StringMapper; import java.util.UUID; import static org.junit.Assert.assertEquals; @Category(JDBITests.class) public class TestStatements { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testInsert() throws Exception { Inserter i = SqlObjectBuilder.open(dbi, Inserter.class); // this is what is under test here int rows_affected = i.insert(2, "Diego"); String name = handle.createQuery("select name from something where id = 2").map(StringMapper.FIRST).first(); assertEquals(1, rows_affected); assertEquals("Diego", name); i.close(); } @Test public void testInsertWithVoidReturn() throws Exception { Inserter i = SqlObjectBuilder.open(dbi, Inserter.class); // this is what is under test here i.insertWithVoidReturn(2, "Diego"); String name = handle.createQuery("select name from something where id = 2").map(StringMapper.FIRST).first(); assertEquals("Diego", name); i.close(); } public static interface Inserter extends CloseMe { @SqlUpdate("insert into something (id, name) values (:id, :name)") public int insert(@Bind("id") long id, @Bind("name") String name); @SqlUpdate("insert into something (id, name) values (:id, :name)") public void insertWithVoidReturn(@Bind("id") long id, @Bind("name") String name); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestOverrideStatementRewriter.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestOverrideStatementRewriter.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.ColonPrefixNamedParamStatementRewriter; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.HashPrefixStatementRewriter; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.customizers.OverrideStatementRewriterWith; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestOverrideStatementRewriter { private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); DBI dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); // this is the default, but be explicit for sake of clarity in test dbi.setStatementRewriter(new ColonPrefixNamedParamStatementRewriter()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testFoo() throws Exception { // test will raise exceptions if SQL is bogus -- if it uses the colon prefix form Hashed h = handle.attach(Hashed.class); h.insert(new Something(1, "Joy")); Something s = h.findById(1); assertThat(s.getName(), equalTo("Joy")); } @OverrideStatementRewriterWith(HashPrefixStatementRewriter.class) static interface Hashed { @SqlUpdate("insert into something (id, name) values (#id, #name)") public void insert(@BindBean Something s); @SqlQuery("select id, name from something where id = #id") public Something findById(@Bind("id") int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestModifiers.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestModifiers.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.sqlobject.customizers.FetchSize; import org.skife.jdbi.v2.sqlobject.customizers.MaxRows; import org.skife.jdbi.v2.sqlobject.customizers.QueryTimeOut; import org.skife.jdbi.v2.sqlobject.customizers.TransactionIsolation; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import org.skife.jdbi.v2.sqlobject.mixins.Transactional; import java.util.List; import java.util.UUID; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.skife.jdbi.v2.TransactionIsolationLevel.READ_UNCOMMITTED; public class TestModifiers { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test @Category(JDBITests.class) public void testFetchSizeAsArgOnlyUsefulWhenSteppingThroughDebuggerSadly() throws Exception { Spiffy s = SqlObjectBuilder.attach(handle, Spiffy.class); s.insert(14, "Tom"); s.insert(15, "JFA"); s.insert(16, "Sunny"); List<Something> things = s.findAll(1); assertEquals(3, things.size()); } @Test @Category(JDBITests.class) public void testFetchSizeOnMethodOnlyUsefulWhenSteppingThroughDebuggerSadly() throws Exception { Spiffy s = SqlObjectBuilder.attach(handle, Spiffy.class); s.insert(14, "Tom"); s.insert(15, "JFA"); s.insert(16, "Sunny"); List<Something> things = s.findAll(); assertEquals(3, things.size()); } @Test @Category(JDBITests.class) public void testMaxSizeOnMethod() throws Exception { Spiffy s = SqlObjectBuilder.attach(handle, Spiffy.class); s.insert(14, "Tom"); s.insert(15, "JFA"); s.insert(16, "Sunny"); List<Something> things = s.findAllWithMaxRows(); assertEquals(1, things.size()); } @Test @Category(JDBITests.class) public void testMaxSizeOnParam() throws Exception { Spiffy s = SqlObjectBuilder.attach(handle, Spiffy.class); s.insert(14, "Tom"); s.insert(15, "JFA"); s.insert(16, "Sunny"); List<Something> things = s.findAllWithMaxRows(2); assertEquals(2, things.size()); } @Test @Category(JDBITests.class) public void testQueryTimeOutOnMethodOnlyUsefulWhenSteppingThroughDebuggerSadly() throws Exception { Spiffy s = SqlObjectBuilder.attach(handle, Spiffy.class); s.insert(14, "Tom"); s.insert(15, "JFA"); s.insert(16, "Sunny"); List<Something> things = s.findAllWithQueryTimeOut(); assertEquals(3, things.size()); } @Test @Category(JDBITests.class) public void testQueryTimeOutOnParamOnlyUsefulWhenSteppingThroughDebuggerSadly() throws Exception { Spiffy s = SqlObjectBuilder.attach(handle, Spiffy.class); s.insert(14, "Tom"); s.insert(15, "JFA"); s.insert(16, "Sunny"); List<Something> things = s.findAllWithQueryTimeOut(2); assertEquals(3, things.size()); } // Note-1615: This was "@Category(JDBIQuarantineTests.class)". Changed to JDBITests because test passed by default @Test @Category(JDBITests.class) // Behavior changed with H2 1.4 public void testIsolationLevelOnMethod() throws Exception { Spiffy spiffy = dbi.open(Spiffy.class); IsoLevels iso = dbi.open(IsoLevels.class); spiffy.begin(); spiffy.insert(1, "Tom"); Something tom = iso.findById(1); assertThat(tom, notNullValue()); spiffy.rollback(); Something not_tom = iso.findById(1); assertThat(not_tom, nullValue()); spiffy.close(); iso.close(); } // Note-1615: This was "@Category(JDBIQuarantineTests.class)". Changed to JDBITests because test passed by default @Test @Category(JDBITests.class) // Behavior changed with H2 1.4 public void testIsolationLevelOnParam() throws Exception { Spiffy spiffy = dbi.open(Spiffy.class); IsoLevels iso = dbi.open(IsoLevels.class); spiffy.begin(); spiffy.insert(1, "Tom"); Something tom = iso.findById(1, READ_UNCOMMITTED); assertThat(tom, notNullValue()); spiffy.rollback(); Something not_tom = iso.findById(1); assertThat(not_tom, nullValue()); spiffy.close(); iso.close(); } public static interface Spiffy extends CloseMe, Transactional<Spiffy> { @SqlQuery("select id, name from something where id = :id") public Something byId(@Bind("id") long id); @SqlQuery("select id, name from something") public List<Something> findAll(@FetchSize(1) int fetchSize); @SqlQuery("select id, name from something") @FetchSize(2) public List<Something> findAll(); @SqlQuery("select id, name from something") public List<Something> findAllWithMaxRows(@MaxRows(1) int fetchSize); @SqlQuery("select id, name from something") @MaxRows(1) public List<Something> findAllWithMaxRows(); @SqlQuery("select id, name from something") public List<Something> findAllWithQueryTimeOut(@QueryTimeOut(1) int timeOutInSeconds); @SqlQuery("select id, name from something") @QueryTimeOut(1) public List<Something> findAllWithQueryTimeOut(); @SqlUpdate("insert into something (id, name) values (:id, :name)") public void insert(@Bind("id") long id, @Bind("name") String name); } public static interface IsoLevels extends CloseMe { @TransactionIsolation(READ_UNCOMMITTED) @SqlQuery("select id, name from something where id = :id") public Something findById(@Bind("id") int id); @SqlQuery("select id, name from something where id = :id") public Something findById(@Bind("id") int id, @TransactionIsolation TransactionIsolationLevel iso); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestNewApiOnDbiAndHandle.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestNewApiOnDbiAndHandle.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.mixins.GetHandle; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @Category(JDBITests.class) public class TestNewApiOnDbiAndHandle { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @Test public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testOpenNewSpiffy() throws Exception { Spiffy spiffy = dbi.open(Spiffy.class); try { spiffy.insert(new Something(1, "Tim")); spiffy.insert(new Something(2, "Diego")); assertEquals("Diego", spiffy.findNameById(2)); } finally { dbi.close(spiffy); } assertTrue(spiffy.getHandle().getConnection().isClosed()); } @Test public void testOnDemandSpiffy() throws Exception { Spiffy spiffy = dbi.onDemand(Spiffy.class); spiffy.insert(new Something(1, "Tim")); spiffy.insert(new Something(2, "Diego")); assertEquals("Diego", spiffy.findNameById(2)); } @Test public void testAttach() throws Exception { Spiffy spiffy = handle.attach(Spiffy.class); spiffy.insert(new Something(1, "Tim")); spiffy.insert(new Something(2, "Diego")); assertEquals("Diego", spiffy.findNameById(2)); } static interface Spiffy extends GetHandle { @SqlUpdate("insert into something (id, name) values (:it.id, :it.name)") void insert(@Bind(value = "it", binder = SomethingBinderAgainstBind.class) Something s); @SqlQuery("select name from something where id = :id") String findNameById(@Bind("id") int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestBindBeanFactory.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestBindBeanFactory.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.derby.DerbyHelper; import org.skife.jdbi.v2.Binding; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.Update; import java.lang.annotation.Annotation; import static org.junit.Assert.assertEquals; @Category(JDBITests.class) public class TestBindBeanFactory { private static final DerbyHelper DERBY_HELPER = new DerbyHelper(); @BeforeClass public static void setUpClass() throws Exception { DERBY_HELPER.start(); } @AfterClass public static void tearDownClass() throws Exception { DERBY_HELPER.stop(); } @Test public void testBindBeanFactory() throws Exception { BindBeanFactory factory = new BindBeanFactory(); @SuppressWarnings("unchecked") Binder<BindBean, Object> beanBinder = factory.build(new BindBeanImpl()); final DBI dbi = new DBI(DERBY_HELPER.getDataSource()); final Handle handle = dbi.open(); final Update testStatement = handle.createStatement("does not matter"); TestBean testBean = new TestBean(); beanBinder.bind(testStatement, new BindBeanImpl(), testBean); StatementContext context = testStatement.getContext(); Binding binding = context.getBinding(); assertEquals("LongArgument", binding.forName("ALong").getClass().getSimpleName()); assertEquals("BooleanArgument", binding.forName("ARealBoolean").getClass().getSimpleName()); assertEquals("BooleanArgument", binding.forName("ANullBoolean").getClass().getSimpleName()); assertEquals("StringArgument", binding.forName("AString").getClass().getSimpleName()); assertEquals("ObjectArgument", binding.forName("AFoo").getClass().getSimpleName()); assertEquals("ShortArgument", binding.forName("AShort").getClass().getSimpleName()); handle.close(); } public static class TestBean { public long getALong() { return 4815162342L; } public Boolean getARealBoolean() { return Boolean.TRUE; } public Boolean getANullBoolean() { return null; } public String getAString() { return "a string, what did you expect?"; } public Foo getAFoo() { return new Foo(); } public Short getAShort() { return Short.valueOf((short) 12345); } } public static class Foo { } static class BindBeanImpl implements BindBean { @Override public Class<? extends Annotation> annotationType() { return BindBean.class; } @Override public String value() { return "___jdbi_bare___"; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestReturningQuery.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestReturningQuery.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import java.util.UUID; import static org.junit.Assert.assertEquals; @Category(JDBITests.class) public class TestReturningQuery { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testWithRegisteredMapper() throws Exception { handle.execute("insert into something (id, name) values (7, 'Tim')"); dbi.registerMapper(new SomethingMapper()); Spiffy spiffy = SqlObjectBuilder.open(dbi, Spiffy.class); Something s = spiffy.findById(7) .first(); assertEquals("Tim", s.getName()); } @Test public void testWithExplicitMapper() throws Exception { handle.execute("insert into something (id, name) values (7, 'Tim')"); Spiffy2 spiffy = SqlObjectBuilder.open(dbi, Spiffy2.class); Something s = spiffy.findByIdWithExplicitMapper(7) .first(); assertEquals("Tim", s.getName()); } public static interface Spiffy extends CloseMe { @SqlQuery("select id, name from something where id = :id") public Query<Something> findById(@Bind("id") int id); } public static interface Spiffy2 extends CloseMe { @SqlQuery("select id, name from something where id = :id") @Mapper(SomethingMapper.class) public Query<Something> findByIdWithExplicitMapper(@Bind("id") int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestCustomBinder.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestCustomBinder.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import java.util.UUID; import static org.junit.Assert.assertEquals; @Category(JDBITests.class) public class TestCustomBinder { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testFoo() throws Exception { handle.execute("insert into something (id, name) values (2, 'Martin')"); Spiffy spiffy = SqlObjectBuilder.open(dbi, Spiffy.class); Something s = spiffy.findSame(new Something(2, "Unknown")); assertEquals("Martin", s.getName()); spiffy.close(); } @Test public void testCustomBindingAnnotation() throws Exception { Spiffy s = handle.attach(Spiffy.class); s.insert(new Something(2, "Keith")); assertEquals("Keith", s.findNameById(2)); } public static interface Spiffy extends CloseMe { @SqlQuery("select id, name from something where id = :it.id") @Mapper(SomethingMapper.class) public Something findSame(@Bind(value = "it", binder = SomethingBinderAgainstBind.class) Something something); @SqlUpdate("insert into something (id, name) values (:s.id, :s.name)") public int insert(@BindSomething("s") Something something); @SqlQuery("select name from something where id = :id") String findNameById(@Bind("id") int i); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestReturningQueryResults.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestReturningQueryResults.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @Category(JDBITests.class) public class TestReturningQueryResults { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testSingleValue() throws Exception { handle.execute("insert into something (id, name) values (7, 'Tim')"); Spiffy spiffy = SqlObjectBuilder.open(dbi, Spiffy.class); Something s = spiffy.findById(7); assertEquals("Tim", s.getName()); } @Test public void testIterator() throws Exception { handle.execute("insert into something (id, name) values (7, 'Tim')"); handle.execute("insert into something (id, name) values (3, 'Diego')"); Spiffy spiffy = SqlObjectBuilder.open(dbi, Spiffy.class); Iterator<Something> itty = spiffy.findByIdRange(2, 10); Set<Something> all = new HashSet<Something>(); while (itty.hasNext()) { all.add(itty.next()); } assertEquals(2, all.size()); assertTrue(all.contains(new Something(7, "Tim"))); assertTrue(all.contains(new Something(3, "Diego"))); } @Test public void testList() throws Exception { handle.execute("insert into something (id, name) values (7, 'Tim')"); handle.execute("insert into something (id, name) values (3, 'Diego')"); Spiffy spiffy = SqlObjectBuilder.open(dbi, Spiffy.class); List<Something> all = spiffy.findTwoByIds(3, 7); assertEquals(2, all.size()); assertTrue(all.contains(new Something(7, "Tim"))); assertTrue(all.contains(new Something(3, "Diego"))); } public static interface Spiffy extends CloseMe { @SqlQuery("select id, name from something where id = :id") @Mapper(SomethingMapper.class) public Something findById(@Bind("id") int id); @SqlQuery("select id, name from something where id >= :from and id <= :to") @Mapper(SomethingMapper.class) public Iterator<Something> findByIdRange(@Bind("from") int from, @Bind("to") int to); @SqlQuery("select id, name from something where id = :first or id = :second") @Mapper(SomethingMapper.class) public List<Something> findTwoByIds(@Bind("first") int from, @Bind("second") int to); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestOnDemandSqlObject.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestOnDemandSqlObject.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.easymock.EasyMock; import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.ResultIterator; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.exceptions.TransactionException; import org.skife.jdbi.v2.exceptions.UnableToCloseResourceException; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.exceptions.DBIException; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.sqlobject.mixins.GetHandle; import org.skife.jdbi.v2.sqlobject.mixins.Transactional; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.util.StringMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestOnDemandSqlObject { private DBI dbi; private Handle handle; private JdbcDataSource ds; @Before public void setUp() throws Exception { ds = new JdbcDataSource(); ds.setURL(String.format("jdbc:h2:mem:%s", UUID.randomUUID())); dbi = new DBI(ds); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testAPIWorks() throws Exception { Spiffy s = SqlObjectBuilder.onDemand(dbi, Spiffy.class); s.insert(7, "Bill"); String bill = handle.createQuery("select name from something where id = 7").map(StringMapper.FIRST).first(); assertEquals("Bill", bill); } @Test public void testTransactionBindsTheHandle() throws Exception { TransactionStuff txl = SqlObjectBuilder.onDemand(dbi, TransactionStuff.class); TransactionStuff tx2 = SqlObjectBuilder.onDemand(dbi, TransactionStuff.class); txl.insert(8, "Mike"); txl.begin(); assertSame(txl.getHandle(), txl.getHandle()); txl.updateName(8, "Miker"); assertEquals("Miker", txl.byId(8).getName()); assertEquals("Mike", tx2.byId(8).getName()); txl.commit(); assertNotSame(txl.getHandle(), txl.getHandle()); assertEquals("Miker", tx2.byId(8).getName()); } @Test public void testIteratorBindsTheHandle() throws Exception { Spiffy s = SqlObjectBuilder.onDemand(dbi, Spiffy.class); s.insert(1, "Tom"); s.insert(2, "Sam"); assertNotSame(s.getHandle(), s.getHandle()); Iterator<Something> all = s.findAll(); assertSame(s.getHandle(), s.getHandle()); all.next(); assertSame(s.getHandle(), s.getHandle()); all.next(); assertFalse(all.hasNext()); assertNotSame(s.getHandle(), s.getHandle()); } @Test(expected=TransactionException.class) public void testExceptionOnClose() throws Exception { DBI dbi = new DBI(ds) { @Override public Handle open() { Handle h = EasyMock.createMock(Handle.class); h.createStatement(EasyMock.anyString()); EasyMock.expectLastCall() .andThrow(new TransactionException("connection reset")); h.close(); EasyMock.expectLastCall() .andThrow(new UnableToCloseResourceException("already closed", null)); EasyMock.replay(h); return h; } }; Spiffy s = SqlObjectBuilder.onDemand(dbi, Spiffy.class); s.insert(1, "Tom"); } @Test public void testIteratorCloseHandleOnError() throws Exception { HandleTrackerDBI dbi = new HandleTrackerDBI(ds); Spiffy s = SqlObjectBuilder.onDemand(dbi, Spiffy.class); try { s.crashNow(); fail(); } catch (DBIException e) { } assertFalse( dbi.hasOpenedHandle() ); } @Test public void testIteratorClosedOnReadError() throws Exception { HandleTrackerDBI dbi = new HandleTrackerDBI(ds); Spiffy spiffy = SqlObjectBuilder.onDemand(dbi, Spiffy.class); spiffy.insert(1, "Tom"); Iterator<Something> i = spiffy.crashOnFirstRead(); try { i.next(); fail(); } catch (DBIException ex) { } assertFalse(dbi.hasOpenedHandle()); } @Test public void testIteratorClosedIfEmpty() throws Exception { HandleTrackerDBI dbi = new HandleTrackerDBI(ds); Spiffy spiffy = SqlObjectBuilder.onDemand(dbi, Spiffy.class); ResultIterator<Something> nothing = spiffy.findAll(); assertFalse(dbi.hasOpenedHandle()); } @Test public void testIteratorPrepatureClose() throws Exception { HandleTrackerDBI dbi = new HandleTrackerDBI(ds); Spiffy spiffy = SqlObjectBuilder.onDemand(dbi, Spiffy.class); spiffy.insert(1, "Tom"); ResultIterator<Something> all = spiffy.findAll(); all.close(); assertFalse( dbi.hasOpenedHandle() ); } @Test public void testSqlFromExternalFileWorks() throws Exception { Spiffy spiffy = SqlObjectBuilder.onDemand(dbi, Spiffy.class); ExternalSql external = SqlObjectBuilder.onDemand(dbi, ExternalSql.class); spiffy.insert(1, "Tom"); spiffy.insert(2, "Sam"); Iterator<Something> all = external.findAll(); all.next(); all.next(); assertFalse(all.hasNext()); } public static interface Spiffy extends GetHandle { @SqlUpdate("insert into something (id, name) values (:id, :name)") public void insert(@Bind("id") long id, @Bind("name") String name); @SqlQuery("select name, id from something") @Mapper(SomethingMapper.class) ResultIterator<Something> findAll(); @SqlQuery("select * from crash now") @Mapper(SomethingMapper.class) Iterator<Something> crashNow(); @SqlQuery("select name, id from something") @Mapper(CrashingMapper.class) Iterator<Something> crashOnFirstRead(); } public static interface TransactionStuff extends GetHandle, Transactional<TransactionStuff> { @SqlQuery("select id, name from something where id = :id") @Mapper(SomethingMapper.class) public Something byId(@Bind("id") long id); @SqlUpdate("update something set name = :name where id = :id") public void updateName(@Bind("id") long id, @Bind("name") String name); @SqlUpdate("insert into something (id, name) values (:id, :name)") public void insert(@Bind("id") long id, @Bind("name") String name); } public static interface ExternalSql extends GetHandle { @SqlQuery("all-something") @Mapper(SomethingMapper.class) Iterator<Something> findAll(); } static class CrashingMapper implements ResultSetMapper<Something> { @Override public Something map(int index, ResultSet r, StatementContext ctx) throws SQLException { throw new SQLException("protocol error"); } } public static class HandleTrackerDBI extends DBI { final List<Handle> openedHandle = new ArrayList<Handle>(); HandleTrackerDBI(DataSource dataSource) { super(dataSource); } @Override public Handle open() { Handle h = super.open(); openedHandle.add(h); return h; } boolean hasOpenedHandle() throws SQLException { for (Handle h : openedHandle) { if (!h.getConnection().isClosed()) return true; } return false; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestSqlCall.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestSqlCall.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.logging.PrintStreamLog; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestSqlCall { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); dbi.registerMapper(new SomethingMapper()); dbi.setSQLLog(new PrintStreamLog(System.out)); handle = dbi.open(); handle.execute("create table something( id integer primary key, name varchar(100) )"); handle.execute("CREATE ALIAS stored_insert FOR \"org.skife.jdbi.v2.sqlobject.TestSqlCall.insertSomething\";"); } @After public void tearDown() throws Exception { handle.close(); } @Test public void testFoo() throws Exception { Dao dao = handle.attach(Dao.class); // OutParameters out = handle.createCall(":num = call stored_insert(:id, :name)") // .bind("id", 1) // .bind("name", "Jeff") // .registerOutParameter("num", Types.INTEGER) // .invoke(); dao.insert(1, "Jeff"); assertThat(handle.attach(Dao.class).findById(1), equalTo(new Something(1, "Jeff"))); } public static interface Dao { @SqlCall("call stored_insert(:id, :name)") public void insert(@Bind("id") int id, @Bind("name") String name); @SqlQuery("select id, name from something where id = :id") Something findById(@Bind("id") int id); } public static int insertSomething(Connection conn, int id, String name) throws SQLException { PreparedStatement stmt = conn.prepareStatement("insert into something (id, name) values (?, ?)"); stmt.setInt(1, id); stmt.setString(2, name); return stmt.executeUpdate(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestDoublyTransactional.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestDoublyTransactional.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.h2.jdbcx.JdbcDataSourceBackwardsCompat; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.sqlobject.customizers.TransactionIsolation; import org.skife.jdbi.v2.sqlobject.mixins.Transactional; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.SQLException; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import javax.naming.Referenceable; import javax.sql.ConnectionPoolDataSource; import javax.sql.DataSource; import javax.sql.XADataSource; @Category(JDBITests.class) public class TestDoublyTransactional { private DBI dbi; private Handle handle; private final AtomicBoolean inTransaction = new AtomicBoolean(); interface TheBasics extends Transactional<TheBasics> { @SqlUpdate("insert into something (id, name) values (:id, :name)") @TransactionIsolation(TransactionIsolationLevel.SERIALIZABLE) int insert(@BindBean Something something); } @Test public void testDoublyTransactional() throws Exception { final TheBasics dao = dbi.onDemand(TheBasics.class); dao.inTransaction(TransactionIsolationLevel.SERIALIZABLE, new Transaction<Void, TheBasics>() { @Override public Void inTransaction(TheBasics transactional, TransactionStatus status) throws Exception { transactional.insert(new Something(1, "2")); inTransaction.set(true); transactional.insert(new Something(2, "3")); inTransaction.set(false); return null; } }); } @Before public void setUp() throws Exception { final JdbcDataSource realDs = new JdbcDataSource(); realDs.setURL(String.format("jdbc:h2:mem:%s", UUID.randomUUID())); final DataSource ds = (DataSource) Proxy.newProxyInstance(realDs.getClass().getClassLoader(), new Class<?>[]{XADataSource.class, DataSource.class, ConnectionPoolDataSource.class, Serializable.class, Referenceable.class, JdbcDataSourceBackwardsCompat.class}, new InvocationHandler() { @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { if ("getConnection".equals(method.getName())) { final Connection real = realDs.getConnection(); return Proxy.newProxyInstance(real.getClass().getClassLoader(), new Class<?>[]{Connection.class}, new TxnIsolationCheckingInvocationHandler(real)); } else { return method.invoke(realDs, args); } } }); dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } private static final Set<Method> CHECKED_METHODS; static { try { CHECKED_METHODS = Set.of(Connection.class.getMethod("setTransactionIsolation", int.class)); } catch (final Exception e) { throw new ExceptionInInitializerError(e); } } private class TxnIsolationCheckingInvocationHandler implements InvocationHandler { private final Connection real; public TxnIsolationCheckingInvocationHandler(Connection real) { this.real = real; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (CHECKED_METHODS.contains(method) && inTransaction.get()) { throw new SQLException(String.format("PostgreSQL would not let you set the transaction isolation here")); } return method.invoke(real, args); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestGetGeneratedKeysPostgres.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestGetGeneratedKeysPostgres.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcConnectionPool; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import org.skife.jdbi.v2.tweak.HandleCallback; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestGetGeneratedKeysPostgres { private JdbcConnectionPool ds; private DBI dbi; @Before public void setUp() throws Exception { dbi = new DBI("jdbc:postgresql:test", "postgres", "postgres"); dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(Handle handle) throws Exception { handle.execute("create sequence id_sequence INCREMENT 1 START WITH 100"); handle.execute("create table if not exists something (name text, id int DEFAULT nextval('id_sequence'), CONSTRAINT something_id PRIMARY KEY ( id ));"); return null; } }); } @After public void tearDown() throws Exception { dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(Handle handle) throws Exception { handle.execute("drop table something"); handle.execute("drop sequence id_sequence"); return null; } }); } public static interface DAO extends CloseMe { @SqlUpdate("insert into something (name, id) values (:name, nextval('id_sequence'))") @GetGeneratedKeys(columnName = "id") public long insert(@Bind("name") String name); @SqlQuery("select name from something where id = :it") public String findNameById(@Bind long id); } @Ignore @Test public void testFoo() throws Exception { DAO dao = dbi.open(DAO.class); Long brian_id = dao.insert("Brian"); long keith_id = dao.insert("Keith"); assertThat(dao.findNameById(brian_id), equalTo("Brian")); assertThat(dao.findNameById(keith_id), equalTo("Keith")); dao.close(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/BindSomething.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/BindSomething.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.Something; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) @BindingAnnotation(BindSomething.Factory.class) public @interface BindSomething { String value(); static class Factory implements BinderFactory { @Override public Binder build(Annotation annotation) { return new Binder() { @Override public void bind(SQLStatement q, Annotation bind, Object arg) { BindSomething bs = (BindSomething) bind; Something it = (Something) arg; q.bind(bs.value() + ".id", it.getId()); q.bind(bs.value() + ".name", it.getName()); } }; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestOverrideStatementLocatorWith.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestOverrideStatementLocatorWith.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.customizers.Define; import org.skife.jdbi.v2.sqlobject.customizers.OverrideStatementLocatorWith; import org.skife.jdbi.v2.sqlobject.stringtemplate.StringTemplate3StatementLocator; import org.skife.jdbi.v2.util.StringMapper; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestOverrideStatementLocatorWith { private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); DBI dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testBaz() throws Exception { Kangaroo wombat = handle.attach(Kangaroo.class); wombat.insert(new Something(7, "Henning")); String name = handle.createQuery("select name from something where id = 7") .map(StringMapper.FIRST) .first(); assertThat(name, equalTo("Henning")); } @Test public void testBam() throws Exception { handle.execute("insert into something (id, name) values (6, 'Martin')"); Something s = handle.attach(Kangaroo.class).findById(6L); assertThat(s.getName(), equalTo("Martin")); } @Test public void testBap() throws Exception { handle.execute("insert into something (id, name) values (2, 'Bean')"); Kangaroo w = handle.attach(Kangaroo.class); assertThat(w.findNameFor(2), equalTo("Bean")); } @Test public void testDefines() throws Exception { handle.attach(Kangaroo.class).weirdInsert("something", "id", "name", 5, "Bouncer"); String name = handle.createQuery("select name from something where id = 5") .map(StringMapper.FIRST) .first(); assertThat(name, equalTo("Bouncer")); } @OverrideStatementLocatorWith(StringTemplate3StatementLocator.class) static interface Kangaroo { @SqlUpdate public void insert(@BindBean Something s); @SqlQuery public Something findById(@Bind("id") Long id); @SqlQuery("select name from something where id = :it") String findNameFor(@Bind int id); @SqlUpdate void weirdInsert(@Define("table") String table, @Define("id_column") String idColumn, @Define("value_column") String valueColumn, @Bind("id") int id, @Bind("value") String name); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestRegisteredMappersWork.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestRegisteredMappersWork.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.helpers.MapResultAsBean; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class TestRegisteredMappersWork { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); dbi.registerMapper(new MySomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } public static interface BooleanDao { @SqlQuery("select 1+1 = 2") public boolean fetchABoolean(); } @Test @Category(JDBITests.class) public void testFoo() throws Exception { boolean world_is_right = handle.attach(BooleanDao.class).fetchABoolean(); assertThat(world_is_right, equalTo(true)); } public static class Bean { private String name; private String color; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } } public static interface BeanMappingDao { @SqlUpdate("create table beans ( name varchar primary key, color varchar )") public void createBeanTable(); @SqlUpdate("insert into beans (name, color) values (:name, :color)") public void insertBean(@BindBean Bean bean); @SqlQuery("select name, color from beans where name = :name") @MapResultAsBean public Bean findByName(@Bind("name") String name); } @Test @Category(JDBITests.class) public void testBuiltIn() throws Exception { Spiffy s = SqlObjectBuilder.attach(handle, Spiffy.class); s.insert(1, "Tatu"); assertEquals("Tatu", s.findNameBy(1)); } @Test @Category(JDBITests.class) public void testRegisterMapperAnnotationWorks() throws Exception { Kabob bob = dbi.onDemand(Kabob.class); bob.insert(1, "Henning"); Something henning = bob.find(1); assertThat(henning, equalTo(new Something(1, "Henning"))); } @Test @Category(JDBITests.class) public void testNoErrorOnNoData() throws Exception { Kabob bob = dbi.onDemand(Kabob.class); Something henning = bob.find(1); assertThat(henning, nullValue()); List<Something> rs = bob.listAll(); assertThat(rs.isEmpty(), equalTo(true)); Iterator<Something> itty = bob.iterateAll(); assertThat(itty.hasNext(), equalTo(false)); } public static interface Spiffy extends CloseMe { @SqlQuery("select id, name from something where id = :id") public Something byId(@Bind("id") long id); @SqlQuery("select name from something where id = :id") public String findNameBy(@Bind("id") long id); @SqlUpdate("insert into something (id, name) values (:id, :name)") public void insert(@Bind("id") long id, @Bind("name") String name); } public static interface Kabob { @SqlUpdate("insert into something (id, name) values (:id, :name)") public void insert(@Bind("id") int id, @Bind("name") String name); @SqlQuery("select id, name from something where id = :id") public Something find(@Bind("id") int id); @SqlQuery("select id, name from something order by id") public List<Something> listAll(); @SqlQuery("select id, name from something order by id") public Iterator<Something> iterateAll(); } public static class MySomethingMapper implements ResultSetMapper<Something> { @Override public Something map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new Something(r.getInt("id"), r.getString("name")); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/SomethingBinderAgainstBind.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/SomethingBinderAgainstBind.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.Something; public class SomethingBinderAgainstBind implements Binder<Bind, Something> { @Override public void bind(SQLStatement q, Bind bind, Something it) { q.bind(bind.value() + ".id", it.getId()); q.bind(bind.value() + ".name", it.getName()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestCreateSqlObjectAnnotation.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestCreateSqlObjectAnnotation.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestCreateSqlObjectAnnotation { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testSimpleCreate() throws Exception { Foo foo = handle.attach(Foo.class); foo.insert(1, "Stephane"); Something s = foo.createBar().findById(1); assertThat(s, equalTo(new Something(1, "Stephane"))); } @Test public void testInsertAndFind() throws Exception { Foo foo = handle.attach(Foo.class); Something s = foo.insertAndFind(1, "Stephane"); assertThat(s, equalTo(new Something(1, "Stephane"))); } @Test public void testTransactionPropagates() throws Exception { Foo foo = dbi.onDemand(Foo.class); try { foo.insertAndFail(1, "Jeff"); fail("should have raised an exception"); } catch (Exception e){} Something n = foo.createBar().findById(1); assertThat(n, nullValue()); } public static abstract class Foo { @CreateSqlObject public abstract Bar createBar(); @SqlUpdate("insert into something (id, name) values (:id, :name)") public abstract int insert(@Bind("id") int id, @Bind("name") String name); @Transaction public Something insertAndFind(int id, String name) { insert(id, name); return createBar().findById(id); } @Transaction public Something insertAndFail(int id, String name) { insert(id, name); return createBar().explode(); } } public static abstract class Bar { @SqlQuery("select id, name from something where id = :it") public abstract Something findById(@Bind int id); public Something explode() { throw new RuntimeException(); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestBeanBinder.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestBeanBinder.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.util.StringMapper; import java.util.UUID; import static org.junit.Assert.assertEquals; @Category(JDBITests.class) public class TestBeanBinder { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testInsert() throws Exception { Spiffy s = handle.attach(Spiffy.class); s.insert(new Something(2, "Bean")); String name = handle.createQuery("select name from something where id = 2").map(StringMapper.FIRST).first(); assertEquals("Bean", name); } @Test public void testRead() throws Exception { Spiffy s = handle.attach(Spiffy.class); handle.insert("insert into something (id, name) values (17, 'Phil')"); Something phil = s.findByEqualsOnBothFields(new Something(17, "Phil")); assertEquals("Phil", phil.getName()); } interface Spiffy { @SqlUpdate("insert into something (id, name) values (:id, :name)") int insert(@BindBean Something s); @SqlQuery("select id, name from something where id = :s.id and name = :s.name") Something findByEqualsOnBothFields(@BindBean("s") Something s); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestObjectMethods.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestObjectMethods.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestObjectMethods { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testToString() throws Exception { DAO dao = handle.attach(DAO.class); assertThat(dao.toString(), containsString(DAO.class.getName())); } @Test public void testEquals() throws Exception { DAO dao = handle.attach(DAO.class); assertThat(dao, equalTo(dao)); } @Test public void testNotEquals() throws Exception { DAO dao = handle.attach(DAO.class); DAO oad = handle.attach(DAO.class); assertThat(dao, not(equalTo(oad))); } @Test public void testHashCodeDiff() throws Exception { DAO dao = handle.attach(DAO.class); DAO oad = handle.attach(DAO.class); assertThat(dao.hashCode(), not(equalTo(oad.hashCode()))); } @Test public void testHashCodeMatch() throws Exception { DAO dao = handle.attach(DAO.class); assertThat(dao.hashCode(), equalTo(dao.hashCode())); } public static interface DAO { @SqlUpdate("insert into something (id, name) values (:id, :name)") public void insert(@Bind("id")long id, @Bind("name") String name); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestVariousOddities.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestVariousOddities.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import java.util.UUID; import java.util.concurrent.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestVariousOddities { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testAttach() throws Exception { Spiffy s = SqlObjectBuilder.attach(handle, Spiffy.class); s.insert(new Something(14, "Tom")); Something tom = s.byId(14); assertEquals("Tom", tom.getName()); } @Test public void testRegisteredMappersWork() throws Exception { } @Test public void testEquals() { Spiffy s1 = SqlObjectBuilder.attach(handle, Spiffy.class); Spiffy s2 = SqlObjectBuilder.attach(handle, Spiffy.class); assertEquals(s1, s1); assertNotSame(s1, s2); assertFalse(s1.equals(s2)); } @Test public void testToString() { Spiffy s1 = SqlObjectBuilder.attach(handle, Spiffy.class); Spiffy s2 = SqlObjectBuilder.attach(handle, Spiffy.class); assertNotNull(s1.toString()); assertNotNull(s2.toString()); assertTrue(s1.toString() != s2.toString()); } @Test public void testHashCode() { Spiffy s1 = SqlObjectBuilder.attach(handle, Spiffy.class); Spiffy s2 = SqlObjectBuilder.attach(handle, Spiffy.class); assertFalse(0 == s1.hashCode()); assertFalse(0 == s2.hashCode()); assertTrue(s1.hashCode() != s2.hashCode()); } @Test public void testConcurrentHashCode() throws ExecutionException, InterruptedException { Callable<SpiffyConcurrent> callable = new Callable<SpiffyConcurrent>() { @Override public SpiffyConcurrent call() throws Exception { return SqlObjectBuilder.attach(handle, SpiffyConcurrent.class); } }; ExecutorService pool = Executors.newFixedThreadPool(2); Future<SpiffyConcurrent> f1 = pool.submit(callable); Future<SpiffyConcurrent> f2 = pool.submit(callable); SpiffyConcurrent s1 = f1.get(); SpiffyConcurrent s2 = f2.get(); assertFalse(0 == s1.hashCode()); assertFalse(0 == s2.hashCode()); assertTrue(s1.hashCode() != s2.hashCode()); } @Test public void testNullQueryReturn() { try { SqlObjectBuilder.attach(handle, SpiffyBoom.class); } catch (IllegalStateException e) { assertEquals("Method org.skife.jdbi.v2.sqlobject.TestVariousOddities$SpiffyBoom#returnNothing " + "is annotated as if it should return a value, but the method is void.", e.getMessage()); return; } fail(); } public static interface Spiffy extends CloseMe { @SqlQuery("select id, name from something where id = :id") @Mapper(SomethingMapper.class) public Something byId(@Bind("id") long id); @SqlUpdate("insert into something (id, name) values (:it.id, :it.name)") public void insert(@Bind(value = "it", binder = SomethingBinderAgainstBind.class) Something it); } public static interface SpiffyBoom extends CloseMe { @SqlQuery("SELECT 1") void returnNothing(); } /** * This interface should not be loaded by any test other than {@link TestVariousOddities#testConcurrentHashCode()}. */ public static interface SpiffyConcurrent { } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestPostgresBugs.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestPostgresBugs.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import java.io.IOException; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.sqlobject.mixins.Transactional; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.util.IntegerMapper; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assume.assumeThat; @Category(JDBITests.class) public class TestPostgresBugs { private static DBI createDbi() { String user = System.getenv("POSTGRES_USER"); String pass = System.getenv("POSTGRES_PASS"); String url = System.getenv("POSTGRES_URL"); assumeThat(user, notNullValue()); // assumeThat(pass, notNullValue()); assumeThat(url, notNullValue()); final DBI dbi = new DBI(url, user, pass); dbi.registerMapper(new SomethingMapper()); return dbi; } @BeforeClass public static void setUp() throws Exception { createDbi().withHandle(new HandleCallback<Object>() { @Override public Object withHandle(Handle handle) throws Exception { handle.execute("create table if not exists something (id int primary key, name varchar(100))"); handle.execute("delete from something"); return null; } }); } @Test public void testConnected() throws Exception { DBI dbi = createDbi(); int four = dbi.withHandle(new HandleCallback<Integer>() { @Override public Integer withHandle(Handle handle) throws Exception { return handle.createQuery("select 2 + 2").map(IntegerMapper.FIRST).first(); } }); assertThat(four, equalTo(4)); } @Test public void testTransactions() throws Exception { DBI dbi = createDbi(); Dao dao = dbi.onDemand(Dao.class); dao.begin(); Something s = dao.insertAndFetch(1, "Brian"); dao.commit(); assertThat(s, equalTo(new Something(1, "Brian"))); } @Test public void testExplicitBeginAndInTransaction() throws Exception { DBI dbi = createDbi(); Dao dao = dbi.onDemand(Dao.class); dao.begin(); Something s = dao.inTransaction(new org.skife.jdbi.v2.Transaction<Something, Dao>() { @Override public Something inTransaction(Dao transactional, TransactionStatus status) throws Exception { return transactional.insertAndFetch(1, "Brian"); } }); dao.commit(); assertThat(s, equalTo(new Something(1, "Brian"))); } public static abstract class Dao implements Transactional<Dao> { @SqlUpdate("insert into something (id, name) values (:id, :name)") public abstract void insert(@Bind("id") int id, @Bind("name") String name); @SqlQuery("select id, name from something where id = :id") public abstract Something findById(@Bind("id") int id); @Transaction(TransactionIsolationLevel.READ_COMMITTED) public Something insertAndFetch(int id, String name) { insert(id, name); return findById(id); } @Transaction public Something insertAndFetchWithNestedTransaction(int id, String name) { return insertAndFetch(id, name); } @Transaction public Something failed(int id, String name) throws IOException { insert(id, name); throw new IOException("woof"); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestPositionalBinder.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestPositionalBinder.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.logging.PrintStreamLog; import java.util.List; import java.util.Map; import java.util.UUID; import static org.junit.Assert.assertEquals; @Category(JDBITests.class) public class TestPositionalBinder { private Handle handle; private SomethingDao somethingDao; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); DBI dbi = new DBI(ds); dbi.setSQLLog(new PrintStreamLog()); handle = dbi.open(); somethingDao = handle.attach(SomethingDao.class); handle.execute("create table something (something_id int primary key, name varchar(100), code int)"); handle.execute("insert into something(something_id, name, code) values (1, 'Brian', 12)"); handle.execute("insert into something(something_id, name, code) values (2, 'Keith', 27)"); handle.execute("insert into something(something_id, name, code) values (3, 'Coda', 14)"); } @After public void tearDown() throws Exception { handle.close(); } @Test public void testOnePositionalParameter() { String name = somethingDao.findNameById(2); assertEquals("Keith", name); } @Test public void testManyPositionalParameters() { Integer id = somethingDao.getIdByNameAndCode("Coda", 14); assertEquals(3, id.intValue()); } @Test public void testInsertWithPositionalParameters() { somethingDao.insertSomething(4, "Dave", 90); List<Map<String, Object>> rows = handle.select("select * from something where something_id=?", 4); assertEquals(rows.size(), 1); Map<String, Object> row = rows.get(0); assertEquals(row.get("something_id"), 4); assertEquals(row.get("name"), "Dave"); assertEquals(row.get("code"), 90); } @Test public void testInsertWithDefaultParams(){ somethingDao.insertWithDefaultParams("Greg",21); List<Map<String, Object>> rows = handle.select("select * from something where something_id=?", 19); assertEquals(rows.size(), 1); Map<String, Object> row = rows.get(0); assertEquals(row.get("something_id"), 19); assertEquals(row.get("name"), "Greg"); assertEquals(row.get("code"), 21); } static interface SomethingDao { @SqlQuery("select name from something where something_id=:0") String findNameById(int i); @SqlQuery("select something_id from something where name=:0 and code=:1") Integer getIdByNameAndCode(String name, int code); @SqlUpdate("insert into something(something_id, name, code) values (:0, :1, :2)") void insertSomething(int id, String name, int code); @SqlUpdate("insert into something(something_id,name, code) values (19, :0, :code)") void insertWithDefaultParams(String name, @Bind("code") int code); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestStringTemplate3Locator.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestStringTemplate3Locator.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.customizers.Define; import org.skife.jdbi.v2.sqlobject.stringtemplate.ExternalizedSqlViaStringTemplate3; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.util.StringMapper; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestStringTemplate3Locator { private Handle handle; @Before public void setUp() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testBaz() throws Exception { Wombat wombat = handle.attach(Wombat.class); wombat.insert(new Something(7, "Henning")); String name = handle.createQuery("select name from something where id = 7") .map(StringMapper.FIRST) .first(); assertThat(name, equalTo("Henning")); } @Test public void testBam() throws Exception { handle.execute("insert into something (id, name) values (6, 'Martin')"); Something s = handle.attach(Wombat.class).findById(6L); assertThat(s.getName(), equalTo("Martin")); } @Test public void testBap() throws Exception { handle.execute("insert into something (id, name) values (2, 'Bean')"); Wombat w = handle.attach(Wombat.class); assertThat(w.findNameFor(2), equalTo("Bean")); } @Test public void testDefines() throws Exception { handle.attach(Wombat.class).weirdInsert("something", "id", "name", 5, "Bouncer"); handle.attach(Wombat.class).weirdInsert("something", "id", "name", 6, "Bean"); String name = handle.createQuery("select name from something where id = 5") .map(StringMapper.FIRST) .first(); assertThat(name, equalTo("Bouncer")); } @Test public void testBatching() throws Exception { Wombat roo = handle.attach(Wombat.class); roo.insertBunches(new Something(1, "Jeff"), new Something(2, "Brian")); assertThat(roo.findById(1L), equalTo(new Something(1, "Jeff"))); assertThat(roo.findById(2L), equalTo(new Something(2, "Brian"))); } @Test public void testNoTemplateDefined() throws Exception { HoneyBadger badass = handle.attach(HoneyBadger.class); badass.insert("something", new Something(1, "Ted")); badass.insert("something", new Something(2, "Fred")); } @UseStringTemplate3StatementLocator static interface HoneyBadger { @SqlUpdate("insert into <table> (id, name) values (:id, :name)") public void insert(@Define("table") String table, @BindBean Something s); @SqlQuery("select id, name from <table> where id = :id") public Something findById(@Define("table") String table, @Bind("id") Long id); } @ExternalizedSqlViaStringTemplate3 static interface Wombat { @SqlUpdate public void insert(@BindBean Something s); @SqlQuery public Something findById(@Bind("id") Long id); @SqlQuery("select name from something where id = :it") String findNameFor(@Bind int id); @SqlUpdate void weirdInsert(@Define("table") String table, @Define("id_column") String idColumn, @Define("value_column") String valueColumn, @Bind("id") int id, @Bind("value") String name); @SqlBatch void insertBunches(@BindBean Something... somethings); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestReentrancy.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestReentrancy.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.sqlobject.mixins.GetHandle; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.util.StringMapper; import java.util.List; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; @Category(JDBITests.class) public class TestReentrancy { private DBI dbi; private Handle handle; interface TheBasics extends GetHandle { @SqlUpdate("insert into something (id, name) values (:id, :name)") int insert(@BindBean Something something); } @Test public void testGetHandleProvidesSeperateHandle() throws Exception { final TheBasics dao = dbi.onDemand(TheBasics.class); Handle h = dao.getHandle(); try { h.execute("insert into something (id, name) values (1, 'Stephen')"); fail("should have raised exception, connection will be closed at this point"); } catch (UnableToCreateStatementException e) { // happy path } } @Test public void testHandleReentrant() throws Exception { final TheBasics dao = dbi.onDemand(TheBasics.class); dao.withHandle(new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { dao.insert(new Something(7, "Martin")); handle.createQuery("SELECT 1").list(); return null; } }); } @Test public void testTxnReentrant() throws Exception { final TheBasics dao = dbi.onDemand(TheBasics.class); dao.withHandle(new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { handle.inTransaction(new TransactionCallback<Void>() { @Override public Void inTransaction(Handle conn, TransactionStatus status) throws Exception { dao.insert(new Something(1, "x")); List<String> rs = conn.createQuery("select name from something where id = 1") .map(StringMapper.FIRST) .list(); assertThat(rs.size(), equalTo(1)); conn.createQuery("SELECT 1").list(); return null; } }); return null; } }); } @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL(String.format("jdbc:h2:mem:%s", UUID.randomUUID())); dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestMixinInterfaces.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/TestMixinInterfaces.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.sqlobject.mixins.CloseMe; import org.skife.jdbi.v2.sqlobject.mixins.GetHandle; import org.skife.jdbi.v2.sqlobject.mixins.Transactional; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.util.StringMapper; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @Category(JDBITests.class) public class TestMixinInterfaces { private DBI dbi; private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL(String.format("jdbc:h2:mem:%s", UUID.randomUUID())); dbi = new DBI(ds); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testGetHandle() throws Exception { WithGetHandle g = SqlObjectBuilder.attach(handle, WithGetHandle.class); Handle h = g.getHandle(); assertSame(handle, h); } @Test public void testWithHandle() throws Exception { WithGetHandle g = SqlObjectBuilder.attach(handle, WithGetHandle.class); String name = g.withHandle(new HandleCallback<String>() { @Override public String withHandle(Handle handle) throws Exception { handle.execute("insert into something (id, name) values (8, 'Mike')"); return handle.createQuery("select name from something where id = 8").map(StringMapper.FIRST).first(); } }); assertEquals("Mike", name); } @Test public void testBeginAndCommitTransaction() throws Exception { TransactionStuff txl = SqlObjectBuilder.attach(handle, TransactionStuff.class); txl.insert(8, "Mike"); txl.begin(); txl.updateName(8, "Miker"); assertEquals("Miker", txl.byId(8).getName()); txl.rollback(); assertEquals("Mike", txl.byId(8).getName()); } @Test public void testInTransaction() throws Exception { TransactionStuff txl = SqlObjectBuilder.attach(handle, TransactionStuff.class); txl.insert(7, "Keith"); Something s = txl.inTransaction(new Transaction<Something, TransactionStuff>() { @Override public Something inTransaction(TransactionStuff conn, TransactionStatus status) throws Exception { return conn.byId(7); } }); assertEquals("Keith", s.getName()); } @Test public void testInTransactionWithLevel() throws Exception { TransactionStuff txl = SqlObjectBuilder.attach(handle, TransactionStuff.class); txl.insert(7, "Keith"); Something s = txl.inTransaction(TransactionIsolationLevel.SERIALIZABLE, new Transaction<Something, TransactionStuff>() { @Override public Something inTransaction(TransactionStuff conn, TransactionStatus status) throws Exception { Assert.assertEquals(TransactionIsolationLevel.SERIALIZABLE, conn.getHandle().getTransactionIsolationLevel()); return conn.byId(7); } }); assertEquals("Keith", s.getName()); } @Test public void testTransactionIsolationActuallyHappens() throws Exception { TransactionStuff txl = SqlObjectBuilder.attach(handle, TransactionStuff.class); TransactionStuff tx2 = SqlObjectBuilder.open(dbi, TransactionStuff.class); txl.insert(8, "Mike"); txl.begin(); txl.updateName(8, "Miker"); assertEquals("Miker", txl.byId(8).getName()); assertEquals("Mike", tx2.byId(8).getName()); txl.commit(); assertEquals("Miker", tx2.byId(8).getName()); tx2.close(); } @Test public void testJustJdbiTransactions() throws Exception { Handle h1 = dbi.open(); Handle h2 = dbi.open(); h1.execute("insert into something (id, name) values (8, 'Mike')"); h1.begin(); h1.execute("update something set name = 'Miker' where id = 8"); assertEquals("Mike", h2.createQuery("select name from something where id = 8").map(StringMapper.FIRST).first()); h1.commit(); h1.close(); h2.close(); } @Test public void testTransmogrifiable() throws Exception { Hobbsian h = handle.attach(Hobbsian.class); h.insert(2, "Cora"); Something s = h.become(TransactionStuff.class).byId(2); assertThat(s, equalTo(new Something(2, "Cora"))); } public static interface WithGetHandle extends CloseMe, GetHandle { } public static interface Hobbsian extends org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier { @SqlUpdate("insert into something (id, name) values (:id, :name)") public void insert(@Bind("id") int id, @Bind("name") String name); } public static interface TransactionStuff extends CloseMe, Transactional<TransactionStuff>, GetHandle { @SqlQuery("select id, name from something where id = :id") @Mapper(SomethingMapper.class) public Something byId(@Bind("id") long id); @SqlUpdate("update something set name = :name where id = :id") public void updateName(@Bind("id") long id, @Bind("name") String name); @SqlUpdate("insert into something (id, name) values (:id, :name)") public void insert(@Bind("id") long id, @Bind("name") String name); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/subpackage/SomethingDao.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/subpackage/SomethingDao.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject.subpackage; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; public abstract class SomethingDao { @SqlUpdate("insert into something (id, name) values (:id, :name)") public abstract void insert(@Bind("id") int id, @Bind("name") String name); @SqlQuery("select id, name from something where id = :id") public abstract Something findById(@Bind("id") int id); public Something findByIdHeeHee(int id) { return findById(id); } public abstract void totallyBroken(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/TestStringTemplate3StatementLocatorWithCustomErrorHandler.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/TestStringTemplate3StatementLocatorWithCustomErrorHandler.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject.stringtemplate; import java.util.List; import java.util.UUID; import org.antlr.stringtemplate.StringTemplateErrorListener; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.unstable.BindIn; @Category(JDBITests.class) public class TestStringTemplate3StatementLocatorWithCustomErrorHandler { private DBI dbi; private Handle handle; private MyDAO dao; @Before public void setUp() { dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); handle = dbi.open(); handle.createStatement("create table foo (id int, bar varchar(100) default null);").execute(); dao = dbi.onDemand(MyDAO.class); } @After public void tearDown() throws Exception { handle.execute("drop table foo"); handle.close(); } @Test(expected=UnableToCreateStatementException.class) public void testBrokenSyntax() { dao.broken(); } @Test public void testWorks() { dao.works(List.of(1L, 2L)); } @Test public void testIds() { dao.ids(List.of(1, 2)); } @UseStringTemplate3StatementLocator(errorListener=MyTestCustomErrorHandler.class) public interface MyDAO { @SqlQuery("select * from foo where bar < 12 and id in (<ids>)") Object broken(); @SqlQuery("select * from foo where bar \\< 12 and id in (<ids>)") Object works(@BindIn("ids") List<Long> ids); @SqlQuery("select * from foo where id in (<ids>)") Object ids(@BindIn("ids") List<Integer> ids); } public static class MyTestCustomErrorHandler implements StringTemplateErrorListener { @Override public void error(String msg, Throwable e) { if(e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } @Override public void warning(String msg) { throw new RuntimeException("warning:" + msg); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/Kombucha.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/Kombucha.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject.stringtemplate; import org.skife.jdbi.v2.sqlobject.SqlQuery; @UseStringTemplate3StatementLocator("/org/skife/jdbi/v2/sqlobject/stringtemplate/Kombucha.sql.stg") public interface Kombucha { @SqlQuery String getIngredients(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/TestingStatementContext.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/TestingStatementContext.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject.stringtemplate; import org.skife.jdbi.v2.Binding; import org.skife.jdbi.v2.Cleanable; import org.skife.jdbi.v2.StatementContext; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class TestingStatementContext implements StatementContext { private final Map<String, Object> attributes; public TestingStatementContext(final Map<String, Object> globalAttributes) { attributes = new HashMap<String, Object>(globalAttributes); } @Override public Object setAttribute(final String key, final Object value) { return attributes.put(key, value); } @Override public Object getAttribute(final String key) { return attributes.get(key); } @Override public Map<String, Object> getAttributes() { return attributes; } @Override public String getRawSql() { throw new UnsupportedOperationException(); } @Override public String getRewrittenSql() { throw new UnsupportedOperationException(); } @Override public String getLocatedSql() { throw new UnsupportedOperationException(); } @Override public PreparedStatement getStatement() { throw new UnsupportedOperationException(); } @Override public Connection getConnection() { throw new UnsupportedOperationException(); } @Override public Binding getBinding() { throw new UnsupportedOperationException(); } @Override public Class<?> getSqlObjectType() { throw new UnsupportedOperationException(); } @Override public Method getSqlObjectMethod() { throw new UnsupportedOperationException(); } @Override public boolean isReturningGeneratedKeys() { throw new UnsupportedOperationException(); } @Override public void addCleanable(final Cleanable cleanable) { throw new UnsupportedOperationException(); } @Override public Collection<Cleanable> getCleanables() { throw new UnsupportedOperationException(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/SuperDrink.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/SuperDrink.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject.stringtemplate; @UseStringTemplate3StatementLocator("/org/skife/jdbi/v2/sqlobject/stringtemplate/SuperDrink.sql.stg") public interface SuperDrink { }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/TestST4StatementLocator.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/TestST4StatementLocator.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject.stringtemplate; import java.util.Collections; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.JDBITests; import org.stringtemplate.v4.STGroupFile; @Category(JDBITests.class) public class TestST4StatementLocator { @Test public void testIds() throws Exception { final ST4StatementLocator statementLocator = new ST4StatementLocator(new STGroupFile("org/skife/jdbi/v2/sqlobject/stringtemplate/Jun.sql.stg")); Assert.assertEquals(0, statementLocator.locatedSqlCache.size()); Assert.assertEquals("select * from foo where id in ()", statementLocator.locate("get", new TestingStatementContext(Collections.emptyMap()))); Assert.assertEquals(1, statementLocator.locatedSqlCache.size()); Assert.assertEquals("select * from foo where id in ()", statementLocator.locatedSqlCache.get("get")); // See @BindIn Assert.assertEquals("select * from foo where id in (:__ids_0)", statementLocator.locate("get", new TestingStatementContext(Map.of("ids", ":__ids_0")))); Assert.assertEquals(2, statementLocator.locatedSqlCache.size()); Assert.assertEquals("select * from foo where id in (:__ids_0)", statementLocator.locatedSqlCache.get("get___#___ids___#___:__ids_0")); Assert.assertEquals("select * from foo where id in (:__ids_0,:__ids_1)", statementLocator.locate("get", new TestingStatementContext(Map.of("ids", ":__ids_0,:__ids_1")))); Assert.assertEquals(3, statementLocator.locatedSqlCache.size()); Assert.assertEquals("select * from foo where id in (:__ids_0,:__ids_1)", statementLocator.locatedSqlCache.get("get___#___ids___#___:__ids_0,:__ids_1")); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/TestStringTemplate3StatementLocatorWithSuperGroupAndCache.java
jdbi/src/test/java/org/skife/jdbi/v2/sqlobject/stringtemplate/TestStringTemplate3StatementLocatorWithSuperGroupAndCache.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject.stringtemplate; import org.antlr.stringtemplate.StringTemplateGroup; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.StatementContext; import java.util.HashMap; @Category(JDBITests.class) public class TestStringTemplate3StatementLocatorWithSuperGroupAndCache { @Test public void testSuperTemplate() throws Exception { final StringTemplate3StatementLocator locator = StringTemplate3StatementLocator.builder(Kombucha.class) .withSuperGroup(SuperDrink.class) .withErrorListener(StringTemplateGroup.DEFAULT_ERROR_LISTENER) .allowImplicitTemplateGroup() .treatLiteralsAsTemplates() .shouldCache() .build(); // Test statement locator from child template group and verify templates table_name got correctly evaluated final StatementContext ctx = new TestingStatementContext(new HashMap<String, Object>()); final String getIngredients = locator.locate("getIngredients", ctx); Assert.assertEquals("select tea\n" + ", mushroom\n" + ", sugar from kombucha;", getIngredients); // Test statement locator from base template group final String awesomeness = locator.locate("awesomeness", ctx); Assert.assertEquals("awesomeness;", awesomeness); } @Test public void testLocatorWithAttributes() throws Exception { final StringTemplate3StatementLocator locator = StringTemplate3StatementLocator.builder(Kombucha.class) .withSuperGroup(SuperDrink.class) .withErrorListener(StringTemplateGroup.DEFAULT_ERROR_LISTENER) .allowImplicitTemplateGroup() .treatLiteralsAsTemplates() .shouldCache() .build(); final StatementContext ctx = new TestingStatementContext(new HashMap<String, Object>()); ctx.setAttribute("historyTableName", "superDrink"); // Test the attributes get correctly evaluated final String getFromHistoryTableName = locator.locate("getFromHistoryTableName", ctx); Assert.assertEquals("select tea\n" + ", mushroom\n" + ", sugar from superDrink;", getFromHistoryTableName); // Verify we cached the template evaluation Assert.assertTrue(StringTemplate3StatementLocator.templateCached(Kombucha.class, SuperDrink.class)); // Try another time with same key-- to verify the attributes of the StringTemplate got reset correctly and we don't end up with twice the name of the table // (By default StringTemplate attributes value are appended when if we set them multiple times) final String getFromHistoryTableNameAgain = locator.locate("getFromHistoryTableName", ctx); Assert.assertEquals("select tea\n" + ", mushroom\n" + ", sugar from superDrink;", getFromHistoryTableNameAgain); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/OuterDao.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/OuterDao.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Define; import org.skife.jdbi.v2.sqlobject.helpers.MapResultAsBean; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseST4StatementLocator; @UseST4StatementLocator public interface OuterDao { @SqlUpdate void createSomething2(); @SqlUpdate void insert2(@Define("table") String table, @Bind("id") int id, @Bind("name") String name); @SqlQuery @MapResultAsBean Something findById2(@Bind("id") int id); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/ExplicitPathLoadTest.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/ExplicitPathLoadTest.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.stringtemplate.ST4StatementLocator; import static org.assertj.core.api.Assertions.assertThat; public class ExplicitPathLoadTest { @Rule public final H2Rule h2 = new H2Rule(); @Test @Category(JDBITests.class) public void testFoo() throws Exception { DBI dbi = new DBI(h2); dbi.setStatementLocator(ST4StatementLocator.fromClasspath("/explicit/sql.stg")); Dao dao = dbi.onDemand(Dao.class); dao.create(); dao.insert(1, "Brian"); String brian = dao.findNameById(1); assertThat(brian).isEqualTo("Brian"); } public interface Dao { @SqlUpdate void create(); @SqlUpdate void insert(int id, String name); @SqlQuery String findNameById(int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/DaoTest.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/DaoTest.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Define; import org.skife.jdbi.v2.sqlobject.helpers.MapResultAsBean; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseST4StatementLocator; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.util.StringMapper; import static org.assertj.core.api.Assertions.assertThat; public class DaoTest { @Rule public final H2Rule h2 = new H2Rule(); @Test @Category(JDBITests.class) public void testSimpleStatement() throws Exception { final DBI dbi = new DBI(h2); final OuterDao dao = dbi.onDemand(OuterDao.class); dao.createSomething2(); dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(final Handle h) throws Exception { h.execute("insert into something (id, name) values (1, 'Kyle')"); return null; } }); } @Test @Category(JDBITests.class) public void testDefineSomething() throws Exception { final DBI dbi = new DBI(h2); final OuterDao dao = dbi.onDemand(OuterDao.class); dao.createSomething2(); dao.insert2("something", 1, "Carlos"); final String name = dbi.withHandle(new HandleCallback<String>() { @Override public String withHandle(final Handle h) throws Exception { return h.createQuery("select name from something where id = 1") .map(new StringMapper()) .first(); } }); assertThat(name).isEqualTo("Carlos"); } @Test @Category(JDBITests.class) public void testSimpleStatementInnerClass() throws Exception { final DBI dbi = new DBI(h2); final InnerDao dao = dbi.onDemand(InnerDao.class); dao.createSomething(); dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(final Handle h) throws Exception { h.execute("insert into something (id, name) values (1, 'Kyle')"); return null; } }); } @Test @Category(JDBITests.class) public void testDefineSomethingInnerClass() throws Exception { final DBI dbi = new DBI(h2); final InnerDao dao = dbi.onDemand(InnerDao.class); dao.createSomething(); dao.insert("something", 1, "Carlos"); final String name = dbi.withHandle(new HandleCallback<String>() { @Override public String withHandle(final Handle h) throws Exception { return h.createQuery("select name from something where id = 1") .map(new StringMapper()) .first(); } }); assertThat(name).isEqualTo("Carlos"); } @Test @Category(JDBITests.class) public void testSqlLiteral() throws Exception { final DBI dbi = new DBI(h2); final InnerDao dao = dbi.onDemand(InnerDao.class); dao.createSomething(); dao.insert("something", 1, "Kyle"); final String name = dao.findNameById(1); assertThat(name).isEqualTo("Kyle"); } @Test @Category(JDBITests.class) public void testLocatorOnMethod() throws Exception { final DBI dbi = new DBI(h2); final InnerDao dao = dbi.onDemand(InnerDao.class); final OnMethod om = dbi.onDemand(OnMethod.class); dao.createSomething(); om.insertVivek(); final String name = dao.findNameById(3); assertThat(name).isEqualTo("Vivek"); } public interface OnMethod { @SqlUpdate @UseST4StatementLocator public void insertVivek(); } @UseST4StatementLocator public interface InnerDao { @SqlUpdate void createSomething(); @SqlUpdate void insert(@Define("table") String table, @Bind("id") int id, @Bind("name") String name); @SqlQuery @MapResultAsBean Something findById(@Bind("id") int id); @SqlQuery("select name from something where id = :id") String findNameById(@Bind("id") int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/SharedSTGroupCacheTest.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/SharedSTGroupCacheTest.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import java.io.File; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.stringtemplate.ST4StatementLocator; import static org.assertj.core.api.Assertions.assertThat; public class SharedSTGroupCacheTest { private static final Charset UTF_8 = StandardCharsets.UTF_8; @Test @Category(JDBITests.class) public void testUseAndDontUseSTGroupCache() throws Exception { String sql; final File tmp = File.createTempFile("test", ".stg"); final StatementContext ctx = Mockito.mock(StatementContext.class); // first write, and loaded into the cache Files.write(tmp.toPath(), "test() ::= <<chirp>>".getBytes(UTF_8)); sql = ST4StatementLocator.forURL(ST4StatementLocator.UseSTGroupCache.YES, tmp.toURI().toURL()) .locate("test", ctx); assertThat(sql).isEqualTo("chirp"); // change the template, but use cache which should not see changes Files.write(tmp.toPath(), "test() ::= <<ribbit>>".getBytes(UTF_8)); sql = ST4StatementLocator.forURL(ST4StatementLocator.UseSTGroupCache.YES, tmp.toURI().toURL()) .locate("test", ctx); assertThat(sql).isEqualTo("chirp"); // change the template and don't use cache, which should load changes Files.write(tmp.toPath(), "test() ::= <<meow>>".getBytes(UTF_8)); sql = ST4StatementLocator.forURL(ST4StatementLocator.UseSTGroupCache.NO, tmp.toURI().toURL()) .locate("test", ctx); assertThat(sql).isEqualTo("meow"); // change template again, don't use cache again, we should see the change Files.write(tmp.toPath(), "test() ::= <<woof>>".getBytes(UTF_8)); sql = ST4StatementLocator.forURL(ST4StatementLocator.UseSTGroupCache.NO, tmp.toURI().toURL()) .locate("test", ctx); assertThat(sql).isEqualTo("woof"); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/ST4Test.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/ST4Test.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.JDBITests; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STGroupFile; import java.net.URL; import static org.assertj.core.api.Assertions.assertThat; public class ST4Test { @Test @Category(JDBITests.class) public void testFoo() throws Exception { final URL stg = ST4Test.class.getResource("st4behavior.stg"); final STGroup group = new STGroupFile(stg, "UTF-8", '<', '>'); final ST st = group.getInstanceOf("foo"); st.add("name", "Brian"); final String out = st.render(); assertThat(out).isEqualTo("hello (: Brian :)"); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/H2Rule.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/H2Rule.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import org.h2.jdbcx.JdbcDataSource; import org.junit.rules.ExternalResource; import org.skife.jdbi.v2.tweak.ConnectionFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.UUID; public class H2Rule extends ExternalResource implements ConnectionFactory { private Connection conn; private JdbcDataSource pool; public synchronized DataSource getDataSource() { return this.pool; } @Override protected synchronized void after() { try { this.conn.close(); } catch (final SQLException e) { throw new IllegalStateException("unable to close last connection to h2", e); } } @Override protected synchronized void before() throws Throwable { final UUID uuid = UUID.randomUUID(); this.pool = new JdbcDataSource(); this.pool.setUrl("jdbc:h2:mem:" + uuid.toString() + ";MODE=LEGACY"); this.pool.setUser("h2"); this.pool.setPassword("h2"); this.conn = this.pool.getConnection(); } @Override public Connection openConnection() throws SQLException { return pool.getConnection(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/Something.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/Something.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import java.util.Objects; public class Something { private int id; private String name; public Something(final int id, final String name) { this.id = id; this.name = name; } public Something() { // for bean mappery } public void setId(final int id) { this.id = id; } public void setName(final String name) { this.name = name; } public int getId() { return this.id; } public String getName() { return this.name; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Something something = (Something) o; return id == something.id && Objects.equals(name, something.name); } @Override public int hashCode() { return Objects.hash(id, name); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/ExampleTest.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/ExampleTest.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Define; import org.skife.jdbi.v2.sqlobject.helpers.MapResultAsBean; import org.skife.jdbi.v2.sqlobject.stringtemplate.ST4StatementLocator; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseST4StatementLocator; import org.skife.jdbi.v2.tweak.HandleCallback; import static org.assertj.core.api.Assertions.assertThat; public class ExampleTest { @Rule public H2Rule h2 = new H2Rule(); @Test @Category(JDBITests.class) public void testFluent() throws Exception { DBI dbi = new DBI(h2); dbi.setStatementLocator(ST4StatementLocator.fromClasspath("/org/skife/jdbi/v2/st4/ExampleTest.Dao.sql.stg")); dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(final Handle h) throws Exception { h.execute("createSomethingTable"); int numCreated = h.createStatement("insertSomething") .bind("0", 0) .bind("1", "Jan") .execute(); assertThat(numCreated).as("number of rows inserted").isEqualTo(1); String name = h.createQuery("findById") .bind("0", 0) .define("columns", "name") .mapTo(String.class) .first(); assertThat(name).as("Jan's Name").isEqualTo("Jan"); return null; } }); } @UseST4StatementLocator public interface Dao { @SqlUpdate void createSomethingTable(); @SqlUpdate int insertSomething(int id, String name); @SqlQuery @MapResultAsBean Something findById(int id, @Define("columns") String... columns); @SqlQuery("select concat('Hello, ', name, '!') from something where id = :0") String findGreetingFor(int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/PerTypeLocatorTest.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/PerTypeLocatorTest.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.helpers.MapResultAsBean; import org.skife.jdbi.v2.sqlobject.stringtemplate.ST4StatementLocator; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.tweak.StatementLocator; import static org.assertj.core.api.Assertions.assertThat; public class PerTypeLocatorTest { @Rule public final H2Rule h2 = new H2Rule(); @Test @Category(JDBITests.class) public void testFallbackTemplate() throws Exception { StatementLocator sl = ST4StatementLocator.perType(ST4StatementLocator.UseSTGroupCache.YES, "/explicit/sql.stg"); DBI dbi = new DBI(h2); dbi.setStatementLocator(sl); dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(final Handle h) throws Exception { h.execute("create"); h.execute("insert", 1, "Brian"); String brian = h.createQuery("findNameById").bind("0", 1).mapTo(String.class).first(); assertThat(brian).isEqualTo("Brian"); return null; } }); } public interface Dao { @SqlUpdate void insertFixtures(); @SqlQuery @MapResultAsBean Something findById(int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/st4/FluentTest.java
jdbi/src/test/java/org/skife/jdbi/v2/st4/FluentTest.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.st4; import java.sql.ResultSet; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.stringtemplate.ST4StatementLocator; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.stringtemplate.v4.STGroupFile; import static org.assertj.core.api.Assertions.assertThat; public class FluentTest { @Rule public H2Rule h2 = new H2Rule(); @Test @Category(JDBITests.class) public void testFoo() throws Exception { final DBI dbi = new DBI(this.h2.getDataSource()); dbi.setStatementLocator(new ST4StatementLocator(new STGroupFile("org/skife/jdbi/v2/st4/DaoTest.InnerDao.sql.stg"))); dbi.withHandle(new HandleCallback<Object>() { @Override public Object withHandle(final Handle h) throws Exception { h.execute("createSomething"); h.createStatement("insert") .define("table", "something") .bind("id", 1) .bind("name", "Ven") .execute(); final Something s = h.createQuery("findById") .bind("id", 1) .map(new ResultSetMapper<Something>() { @Override public Something map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException { return new Something(r.getInt("id"), r.getString("name")); } }) .first(); assertThat(s).isEqualTo(new Something(1, "Ven")); return null; } }); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/docs/TestFoldToObjectGraph.java
jdbi/src/test/java/org/skife/jdbi/v2/docs/TestFoldToObjectGraph.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.docs; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.FoldController; import org.skife.jdbi.v2.Folder3; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.tweak.BeanMapperFactory; import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestFoldToObjectGraph { private DBI dbi; private Handle handle; private Map<String, Team> expected; @Before public void setUp() throws Exception { dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); dbi.registerMapper(new BeanMapperFactory()); handle = dbi.open(); handle.execute("create table team ( name varchar(100), " + " mascot varchar(100)," + " primary key (name) )"); handle.execute("create table person( name varchar(100), " + " role varchar(100), " + " team varchar(100)," + " primary key (name)," + " foreign key (team) references team(name) )"); handle.prepareBatch("insert into team (name, mascot) values (?, ?)") .add("A-Team", "The Van") .add("Hogan's Heroes", "The Tunnel") .execute(); handle.prepareBatch("insert into person (name, role, team) values (?, ?, ?)") .add("Kinchloe", "comms", "Hogan's Heroes") .add("Carter", "bombs", "Hogan's Heroes") .add("Murdoch", "driver", "A-Team") .add("Peck", "face", "A-Team") .execute(); Team ateam = new Team("A-Team", "The Van"); ateam.getPeople().add(new Person("Murdoch", "driver")); ateam.getPeople().add(new Person("Peck", "face")); Team hogans = new Team("Hogan's Heroes", "The Tunnel"); hogans.getPeople().add(new Person("Kinchloe", "comms")); hogans.getPeople().add(new Person("Carter", "bombs")); this.expected = Map.of("Hogan's Heroes", hogans, "A-Team", ateam); } @After public void tearDown() throws Exception { handle.close(); } @Test public void testFluentApi() throws Exception { Map<String, Team> teams = handle.createQuery("select t.name as teamName, " + " t.mascot as mascot, " + " p.name as personName, " + " p.role as role " + "from team t inner join person p on (t.name = p.team)") .map(TeamPersonJoinRow.class) .fold(new HashMap<>(), new TeamFolder()); assertThat(teams, equalTo(expected)); } public static class TeamFolder implements Folder3<Map<String, Team>, TeamPersonJoinRow> { @Override public Map<String, Team> fold(Map<String, Team> acc, TeamPersonJoinRow row, FoldController control, StatementContext ctx) throws SQLException { if (!acc.containsKey(row.getTeamName())) { acc.put(row.getTeamName(), new Team(row.getTeamName(), row.getMascot())); } acc.get(row.getTeamName()).getPeople().add(new Person(row.getPersonName(), row.getRole())); return acc; } } @Test public void testSqlObjectApi() throws Exception { Dao dao = handle.attach(Dao.class); assertThat(dao.findAllTeams(), equalTo(expected)); } public static abstract class Dao { @SqlQuery("select t.name as teamName, " + " t.mascot as mascot, " + " p.name as personName, " + " p.role as role " + "from team t inner join person p on (t.name = p.team)") public abstract Iterator<TeamPersonJoinRow> findAllTeamsAndPeople(); public Map<String, Team> findAllTeams() { Iterator<TeamPersonJoinRow> i = findAllTeamsAndPeople(); Map<String, Team> acc = new HashMap<>(); while (i.hasNext()) { TeamPersonJoinRow row = i.next(); if (!acc.containsKey(row.getTeamName())) { acc.put(row.getTeamName(), new Team(row.getTeamName(), row.getMascot())); } acc.get(row.getTeamName()).getPeople().add(new Person(row.getPersonName(), row.getRole())); } return acc; } } public static class Team { private final String name; private final String mascot; private final Set<Person> people = new LinkedHashSet<Person>(); public Team(String name, String mascot) { this.name = name; this.mascot = mascot; } public String getName() { return name; } public String getMascot() { return mascot; } public Set<Person> getPeople() { return this.people; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Team team = (Team) o; if (mascot != null ? !mascot.equals(team.mascot) : team.mascot != null) return false; return !(name != null ? !name.equals(team.name) : team.name != null) && !(people != null ? !people.equals(team.people) : team.people != null); } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (mascot != null ? mascot.hashCode() : 0); result = 31 * result + (people != null ? people.hashCode() : 0); return result; } } public static class Person { private final String name; private final String role; public Person(String name, String role) { this.name = name; this.role = role; } public String getName() { return name; } public String getRole() { return role; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return name.equals(person.name) && role.equals(person.role); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + role.hashCode(); return result; } } public static class TeamPersonJoinRow { private String teamName; private String mascot; private String personName; private String role; public String getTeamName() { return teamName; } public String getMascot() { return mascot; } public String getPersonName() { return personName; } public String getRole() { return role; } public void setTeamName(String teamName) { this.teamName = teamName; } public void setMascot(String mascot) { this.mascot = mascot; } public void setPersonName(String personName) { this.personName = personName; } public void setRole(String role) { this.role = role; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/docs/TestDocumentation.java
jdbi/src/test/java/org/skife/jdbi/v2/docs/TestDocumentation.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.docs; import static java.util.Arrays.asList; import org.h2.jdbcx.JdbcConnectionPool; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Folder2; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Query; import org.skife.jdbi.v2.Something; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.BindBean; import org.skife.jdbi.v2.sqlobject.SomethingMapper; import org.skife.jdbi.v2.sqlobject.SqlBatch; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.util.StringMapper; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.skife.jdbi.v2.ExtraMatchers.equalsOneOf; @Category(JDBITests.class) public class TestDocumentation { @Before public void setUp() throws Exception { } @Test public void testFiveMinuteFluentApi() throws Exception { // using in-memory H2 database via a pooled DataSource JdbcConnectionPool ds = JdbcConnectionPool.create("jdbc:h2:mem:" + UUID.randomUUID(), "username", "password"); DBI dbi = new DBI(ds); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(100))"); h.execute("insert into something (id, name) values (?, ?)", 1, "Brian"); String name = h.createQuery("select name from something where id = :id") .bind("id", 1) .map(StringMapper.FIRST) .first(); assertThat(name, equalTo("Brian")); h.close(); ds.dispose(); } public interface MyDAO { @SqlUpdate("create table something (id int primary key, name varchar(100))") void createSomethingTable(); @SqlUpdate("insert into something (id, name) values (:id, :name)") void insert(@Bind("id") int id, @Bind("name") String name); @SqlQuery("select name from something where id = :id") String findNameById(@Bind("id") int id); /** * close with no args is used to close the connection */ void close(); } @Test public void testFiveMinuteSqlObjectExample() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); MyDAO dao = dbi.open(MyDAO.class); dao.createSomethingTable(); dao.insert(2, "Aaron"); String name = dao.findNameById(2); assertThat(name, equalTo("Aaron")); dao.close(); } @Test public void testObtainHandleViaOpen() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle handle = dbi.open(); // make sure to close it! handle.close(); } @Test public void testObtainHandleInCallback() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); dbi.withHandle(new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { handle.execute("create table silly (id int)"); return null; } }); } @Test public void testExecuteSomeStatements() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(100))"); h.execute("insert into something (id, name) values (?, ?)", 3, "Patrick"); List<Map<String, Object>> rs = h.select("select id, name from something"); assertThat(rs.size(), equalTo(1)); Map<String, Object> row = rs.get(0); assertThat((Integer) row.get("id"), equalTo(3)); assertThat((String) row.get("name"), equalTo("Patrick")); h.close(); } @Test public void testFluentUpdate() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(100))"); h.createStatement("insert into something(id, name) values (:id, :name)") .bind("id", 4) .bind("name", "Martin") .execute(); h.close(); } @Test public void testFold() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(100))"); h.execute("insert into something (id, name) values (7, 'Mark')"); h.execute("insert into something (id, name) values (8, 'Tatu')"); StringBuilder rs = h.createQuery("select name from something order by id") .map(StringMapper.FIRST) .fold(new StringBuilder(), new Folder2<StringBuilder>() { @Override public StringBuilder fold(StringBuilder acc, ResultSet rs, StatementContext ctx) throws SQLException { acc.append(rs.getString(1)).append(", "); return acc; } }); rs.delete(rs.length() - 2, rs.length()); // trim the extra ", " assertThat(rs.toString(), equalTo("Mark, Tatu")); h.close(); } @Test public void testMappingExampleChainedIterator2() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(100))"); h.execute("insert into something (id, name) values (1, 'Brian')"); h.execute("insert into something (id, name) values (2, 'Keith')"); Iterator<String> rs = h.createQuery("select name from something order by id") .map(StringMapper.FIRST) .iterator(); assertThat(rs.next(), equalTo("Brian")); assertThat(rs.next(), equalTo("Keith")); assertThat(rs.hasNext(), equalTo(false)); h.close(); } @Test public void testMappingExampleChainedIterator3() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(100))"); h.execute("insert into something (id, name) values (1, 'Brian')"); h.execute("insert into something (id, name) values (2, 'Keith')"); for (String name : h.createQuery("select name from something order by id").map(StringMapper.FIRST)) { assertThat(name, equalsOneOf("Brian", "Keith")); } h.close(); } @Test public void testAttachToObject() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); MyDAO dao = h.attach(MyDAO.class); // do stuff with the dao h.close(); } @Test public void testOnDemandDao() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); MyDAO dao = dbi.onDemand(MyDAO.class); } public static interface SomeQueries { @SqlQuery("select name from something where id = :id") String findName(@Bind("id") int id); @SqlQuery("select name from something where id > :from and id < :to order by id") List<String> findNamesBetween(@Bind("from") int from, @Bind("to") int to); @SqlQuery("select name from something order by id") Iterator<String> findAllNames(); } @Test public void testSomeQueriesWorkCorrectly() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(32))"); h.prepareBatch("insert into something (id, name) values (:id, :name)") .add().bind("id", 1).bind("name", "Brian") .next().bind("id", 2).bind("name", "Robert") .next().bind("id", 3).bind("name", "Patrick") .next().bind("id", 4).bind("name", "Maniax") .submit().execute(); SomeQueries sq = h.attach(SomeQueries.class); assertThat(sq.findName(2), equalTo("Robert")); assertThat(sq.findNamesBetween(1, 4), equalTo(Arrays.asList("Robert", "Patrick"))); Iterator<String> names = sq.findAllNames(); assertThat(names.next(), equalTo("Brian")); assertThat(names.next(), equalTo("Robert")); assertThat(names.next(), equalTo("Patrick")); assertThat(names.next(), equalTo("Maniax")); assertThat(names.hasNext(), equalTo(false)); h.close(); } public static interface AnotherQuery { @SqlQuery("select id, name from something where id = :id") Something findById(@Bind("id") int id); } public static interface YetAnotherQuery { @SqlQuery("select id, name from something where id = :id") @Mapper(SomethingMapper.class) Something findById(@Bind("id") int id); } public static interface BatchInserter { @SqlBatch("insert into something (id, name) values (:id, :name)") void insert(@BindBean Something... somethings); } @Test public void testAnotherCoupleInterfaces() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); dbi.registerMapper(new SomethingMapper()); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(32))"); h.attach(BatchInserter.class).insert(new Something(1, "Brian"), new Something(3, "Patrick"), new Something(2, "Robert")); AnotherQuery aq = h.attach(AnotherQuery.class); YetAnotherQuery yaq = h.attach(YetAnotherQuery.class); assertThat(yaq.findById(3), equalTo(new Something(3, "Patrick"))); assertThat(aq.findById(2), equalTo(new Something(2, "Robert"))); h.close(); } public static interface QueryReturningQuery { @SqlQuery("select name from something where id = :id") Query<String> findById(@Bind("id") int id); } @Test public void testFoo() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(32))"); h.attach(BatchInserter.class).insert(new Something(1, "Brian"), new Something(3, "Patrick"), new Something(2, "Robert")); QueryReturningQuery qrq = h.attach(QueryReturningQuery.class); Query<String> q = qrq.findById(1); q.setMaxFieldSize(100); assertThat(q.first(), equalTo("Brian")); h.close(); } public static interface Update { @SqlUpdate("create table something (id integer primary key, name varchar(32))") void createSomethingTable(); @SqlUpdate("insert into something (id, name) values (:id, :name)") int insert(@Bind("id") int id, @Bind("name") String name); @SqlUpdate("update something set name = :name where id = :id") int update(@BindBean Something s); } @Test public void testUpdateAPI() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); Update u = h.attach(Update.class); u.createSomethingTable(); u.insert(17, "David"); u.update(new Something(17, "David P.")); String name = h.createQuery("select name from something where id = 17") .map(StringMapper.FIRST) .first(); assertThat(name, equalTo("David P.")); h.close(); } public static interface BatchExample { @SqlBatch("insert into something (id, name) values (:id, :first || ' ' || :last)") void insertFamily(@Bind("id") List<Integer> ids, @Bind("first") Iterator<String> firstNames, @Bind("last") String lastName); @SqlUpdate("create table something(id int primary key, name varchar(32))") void createSomethingTable(); @SqlQuery("select name from something where id = :it") String findNameById(@Bind int id); } @Test public void testBatchExample() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); BatchExample b = h.attach(BatchExample.class); b.createSomethingTable(); List<Integer> ids = asList(1, 2, 3, 4, 5); Iterator<String> first_names = asList("Tip", "Jane", "Brian", "Keith", "Eric").iterator(); b.insertFamily(ids, first_names, "McCallister"); assertThat(b.findNameById(1), equalTo("Tip McCallister")); assertThat(b.findNameById(2), equalTo("Jane McCallister")); assertThat(b.findNameById(3), equalTo("Brian McCallister")); assertThat(b.findNameById(4), equalTo("Keith McCallister")); assertThat(b.findNameById(5), equalTo("Eric McCallister")); h.close(); } public static interface ChunkedBatchExample { @SqlBatch("insert into something (id, name) values (:id, :first || ' ' || :last)") @BatchChunkSize(2) void insertFamily(@Bind("id") List<Integer> ids, @Bind("first") Iterator<String> firstNames, @Bind("last") String lastName); @SqlUpdate("create table something(id int primary key, name varchar(32))") void createSomethingTable(); @SqlQuery("select name from something where id = :it") String findNameById(@Bind int id); } public static interface BindExamples { @SqlUpdate("insert into something (id, name) values (:id, :name)") void insert(@Bind("id") int id, @Bind("name") String name); @SqlUpdate("delete from something where name = :it") void deleteByName(@Bind String name); } public static interface BindBeanExample { @SqlUpdate("insert into something (id, name) values (:id, :name)") void insert(@BindBean Something s); @SqlUpdate("update something set name = :s.name where id = :s.id") void update(@BindBean("s") Something something); } // @BindingAnnotation(SomethingBinderFactory.class) // @Retention(RetentionPolicy.RUNTIME) // @Target({ElementType.PARAMETER}) // public static @interface BindSomething { } // // public static class SomethingBinderFactory implements BinderFactory // { // public Binder build(Annotation annotation) // { // return new Binder<BindSomething, Something>() // { // public void bind(SQLStatement q, BindSomething bind, Something arg) // { // q.bind("ident", arg.getId()); // q.bind("nom", arg.getName()); // } // }; // } // } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/unstable/grammar/TestPrintfGrammar.java
jdbi/src/test/java/org/skife/jdbi/v2/unstable/grammar/TestPrintfGrammar.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.unstable.grammar; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.Lexer; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.rewriter.printf.FormatterStatementLexer; import org.skife.jdbi.v2.JDBITests; import static org.skife.jdbi.rewriter.printf.FormatterStatementLexer.EOF; import static org.skife.jdbi.rewriter.printf.FormatterStatementLexer.INTEGER; import static org.skife.jdbi.rewriter.printf.FormatterStatementLexer.LITERAL; import static org.skife.jdbi.rewriter.printf.FormatterStatementLexer.QUOTED_TEXT; import static org.skife.jdbi.rewriter.printf.FormatterStatementLexer.STRING; /** * */ @Category(JDBITests.class) public class TestPrintfGrammar extends GrammarTestCase { @Test public void testFoo() throws Exception { expect("select id from something where name like '%d' and id = %d and name like %s", LITERAL, QUOTED_TEXT, LITERAL, INTEGER, LITERAL, STRING, EOF); } @Override protected String nameOf(int type) { switch (type) { case QUOTED_TEXT: return "QUOTED_TEXT"; case INTEGER: return "INTEGER"; case STRING: return "STRING"; case LITERAL: return "LITERAL"; case EOF: return "EOF"; } return "unknown"; } @Override protected Lexer createLexer(String s) { return new FormatterStatementLexer(new ANTLRStringStream(s)); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/unstable/grammar/TestColonGrammar.java
jdbi/src/test/java/org/skife/jdbi/v2/unstable/grammar/TestColonGrammar.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.unstable.grammar; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.Lexer; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.rewriter.colon.ColonStatementLexer; import org.skife.jdbi.v2.JDBITests; import static org.skife.jdbi.rewriter.colon.ColonStatementLexer.EOF; import static org.skife.jdbi.rewriter.colon.ColonStatementLexer.ESCAPED_TEXT; import static org.skife.jdbi.rewriter.colon.ColonStatementLexer.LITERAL; import static org.skife.jdbi.rewriter.colon.ColonStatementLexer.NAMED_PARAM; import static org.skife.jdbi.rewriter.colon.ColonStatementLexer.POSITIONAL_PARAM; import static org.skife.jdbi.rewriter.colon.ColonStatementLexer.QUOTED_TEXT; /** * */ @Category(JDBITests.class) public class TestColonGrammar extends GrammarTestCase { @Test public void testNamedOnly() throws Exception { expect("select id from something where name like ':foo' and id = :id and name like :name", LITERAL, QUOTED_TEXT, LITERAL, NAMED_PARAM, LITERAL, NAMED_PARAM, EOF); } @Test public void testEmptyQuote() throws Exception { expect("select ''", LITERAL, QUOTED_TEXT, EOF); } @Test public void testEscapedEmptyQuote() throws Exception { expect("select '\\''", LITERAL, QUOTED_TEXT, EOF); } @Test public void testEscapedColon() throws Exception { expect("insert into foo (val) VALUE (:bar\\:\\:type)", LITERAL, NAMED_PARAM, ESCAPED_TEXT, ESCAPED_TEXT, LITERAL, EOF); } @Test public void testMixed() throws Exception { expect("select id from something where name like ':foo' and id = ? and name like :name", LITERAL, QUOTED_TEXT, LITERAL, POSITIONAL_PARAM, LITERAL, NAMED_PARAM, EOF); } @Test public void testThisBrokeATest() throws Exception { expect("insert into something (id, name) values (:id, :name)", LITERAL, NAMED_PARAM, LITERAL, NAMED_PARAM, LITERAL, EOF); } @Test public void testExclamationWorks() throws Exception { expect("select1 != 2 from dual", LITERAL, EOF); } @Test public void testHashInColumnNameWorks() throws Exception { expect("select col# from something where id = :id", LITERAL, NAMED_PARAM, EOF); } @Override protected String nameOf(int type) { switch (type) { case LITERAL: return "LITERAL"; case QUOTED_TEXT: return "QUOTED_TEXT"; case NAMED_PARAM: return "NAMED_PARAM"; case EOF: return "EOF"; } return String.valueOf(type); } @Override protected Lexer createLexer(String s) { return new ColonStatementLexer(new ANTLRStringStream(s)); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/unstable/grammar/GrammarTestCase.java
jdbi/src/test/java/org/skife/jdbi/v2/unstable/grammar/GrammarTestCase.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.unstable.grammar; import org.antlr.runtime.Lexer; import org.antlr.runtime.Token; import static org.junit.Assert.assertEquals; /** * */ public abstract class GrammarTestCase { public void expect(String s, int... tokens) throws Exception { Lexer lexer = createLexer(s); for (int token : tokens) { Token t = lexer.nextToken(); assertEquals(String.format("Expected %s, got %s, with '%s'", nameOf(token), nameOf(t.getType()), t.getText()), token, t.getType()); } } protected abstract Lexer createLexer(String s); protected abstract String nameOf(int type); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/skife/jdbi/v2/tweak/transactions/TestSerializableTransactionRunner.java
jdbi/src/test/java/org/skife/jdbi/v2/tweak/transactions/TestSerializableTransactionRunner.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.tweak.transactions; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBITestCase; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionIsolationLevel; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.exceptions.TransactionFailedException; import org.skife.jdbi.v2.tweak.TransactionHandler; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicInteger; @Category(JDBITests.class) public class TestSerializableTransactionRunner extends DBITestCase { @Override protected TransactionHandler getTransactionHandler() { return new SerializableTransactionRunner(); } @Test public void testEventuallyFails() throws Exception { final AtomicInteger tries = new AtomicInteger(5); Handle handle = openHandle(); try { handle.inTransaction(TransactionIsolationLevel.SERIALIZABLE, new TransactionCallback<Void>() { @Override public Void inTransaction(Handle conn, TransactionStatus status) throws Exception { tries.decrementAndGet(); throw new SQLException("serialization", "40001"); } }); } catch (TransactionFailedException e) { Assert.assertEquals("40001", ((SQLException) e.getCause()).getSQLState()); } Assert.assertEquals(0, tries.get()); } @Test public void testEventuallySucceeds() throws Exception { final AtomicInteger tries = new AtomicInteger(3); Handle handle = openHandle(); handle.inTransaction(TransactionIsolationLevel.SERIALIZABLE, new TransactionCallback<Void>() { @Override public Void inTransaction(Handle conn, TransactionStatus status) throws Exception { if (tries.decrementAndGet() == 0) { return null; } throw new SQLException("serialization", "40001"); } }); Assert.assertEquals(0, tries.get()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/JDBITestBase.java
jdbi/src/test/java/org/killbill/commons/jdbi/JDBITestBase.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi; import org.killbill.commons.embeddeddb.h2.H2EmbeddedDB; import org.skife.jdbi.v2.DBI; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; public abstract class JDBITestBase { protected H2EmbeddedDB embeddedDB; protected DBI dbi; @BeforeClass(groups = "slow") public void setUp() throws Exception { embeddedDB = new H2EmbeddedDB(); embeddedDB.initialize(); embeddedDB.start(); } @BeforeMethod(groups = "slow") public void setUpMethod() throws Exception { dbi = new DBI(embeddedDB.getDataSource()); } public void cleanupDb(final String ddl) throws Exception { embeddedDB.executeScript(ddl); } @AfterClass(groups = "slow") public void tearDown() throws Exception { embeddedDB.stop(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/TestReusableStringTemplate3StatementLocator.java
jdbi/src/test/java/org/killbill/commons/jdbi/TestReusableStringTemplate3StatementLocator.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi; import java.io.IOException; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Define; import org.skife.jdbi.v2.sqlobject.mixins.Transactional; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestReusableStringTemplate3StatementLocator extends JDBITestBase { private static final String TABLE_NAME = "something"; @BeforeMethod(groups = "slow") public void cleanupDb() throws Exception { cleanupDb("drop table if exists " + TABLE_NAME + ";\n" + "create table " + TABLE_NAME + " (id int primary key)"); // This will break - as it generates the following query on the second invocation: // delete from somethingsomething //dbi.setStatementLocator(new StringTemplate3StatementLocator(SomethingLiteralSqlDao.class, true, true)); } @Test(groups = "slow") public void testMultipleInvocationsWithoutLiterals() throws IOException { dbi.setStatementLocator(new ReusableStringTemplate3StatementLocator("/org/killbill/commons/jdbi/SomethingNonLiteralSqlDao.sql.stg", true, true)); final SomethingNonLiteralSqlDao somethingNonLiteralSqlDao = dbi.onDemand(SomethingNonLiteralSqlDao.class); somethingNonLiteralSqlDao.delete(TABLE_NAME); somethingNonLiteralSqlDao.delete(TABLE_NAME); } @Test(groups = "slow") public void testMultipleInvocationsWithLiterals() throws IOException { dbi.setStatementLocator(new ReusableStringTemplate3StatementLocator(SomethingLiteralSqlDao.class, true, true)); final SomethingLiteralSqlDao somethingLiteralSqlDao = dbi.onDemand(SomethingLiteralSqlDao.class); somethingLiteralSqlDao.delete(TABLE_NAME); somethingLiteralSqlDao.delete(TABLE_NAME); } private static interface SomethingNonLiteralSqlDao extends Transactional<SomethingLiteralSqlDao> { @SqlUpdate public void delete(@Define("tableName") String table); } private static interface SomethingLiteralSqlDao extends Transactional<SomethingLiteralSqlDao> { @SqlUpdate("delete from <tableName>") public void delete(@Define("tableName") String table); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/guice/TestDataSourceProvider.java
jdbi/src/test/java/org/killbill/commons/jdbi/guice/TestDataSourceProvider.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi.guice; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import java.util.logging.Logger; import javax.sql.DataSource; import org.h2.jdbcx.JdbcConnectionPool; import org.killbill.commons.embeddeddb.GenericStandaloneDB; import org.killbill.commons.embeddeddb.h2.H2EmbeddedDB; import org.killbill.commons.embeddeddb.mysql.KillBillMariaDbDataSource; import org.killbill.commons.jdbi.guice.DataSourceProvider.DatabaseType; import org.mariadb.jdbc.Configuration; import org.skife.config.AugmentedConfigurationObjectFactory; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.pool.HikariPool; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; public class TestDataSourceProvider { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TestDataSourceProvider.class); private static final String TEST_POOL_PREFIX = "test-pool"; @Test(groups = "fast") public void testDataSourceProviderNoPooling() throws Exception { DataSourceProvider.DatabaseType databaseType; DaoConfig daoConfig; String poolName; DataSourceProvider dataSourceProvider; // H2 databaseType = DataSourceProvider.DatabaseType.H2; daoConfig = buildDaoConfig(DataSourceConnectionPoolingType.NONE, databaseType); poolName = TEST_POOL_PREFIX + "-nopool-" + databaseType; final H2EmbeddedDB h2EmbeddedDB = new H2EmbeddedDB(); dataSourceProvider = new DataSourceProvider(daoConfig, h2EmbeddedDB, poolName); try { assertTrue(dataSourceProvider.get() instanceof JdbcConnectionPool); } finally { h2EmbeddedDB.stop(); } // Generic databaseType = DataSourceProvider.DatabaseType.GENERIC; daoConfig = buildDaoConfig(DataSourceConnectionPoolingType.NONE, databaseType); poolName = TEST_POOL_PREFIX + "-nopool-" + databaseType; final GenericStandaloneDB genericStandaloneDB = new GenericStandaloneDB(null, null, null, null); dataSourceProvider = new DataSourceProvider(daoConfig, genericStandaloneDB, poolName); assertNull(dataSourceProvider.get()); } @Test(groups = "fast") public void testDataSourceProviderHikariCP() throws Exception { DataSourceProvider.DatabaseType databaseType; DaoConfig daoConfig; String poolName; DataSourceProvider dataSourceProvider; // H2 databaseType = DataSourceProvider.DatabaseType.H2; daoConfig = buildDaoConfig(DataSourceConnectionPoolingType.HIKARICP, databaseType); poolName = TEST_POOL_PREFIX + "-0-" + databaseType; dataSourceProvider = new DataSourceProvider(daoConfig, poolName); assertTrue(dataSourceProvider.get() instanceof HikariDataSource); // Generic databaseType = DataSourceProvider.DatabaseType.GENERIC; daoConfig = buildDaoConfig(DataSourceConnectionPoolingType.HIKARICP, databaseType); poolName = TEST_POOL_PREFIX + "-0-" + databaseType; dataSourceProvider = new DataSourceProvider(daoConfig, poolName); assertTrue(dataSourceProvider.get() instanceof HikariDataSource); } @Test(groups = "fast") public void testDataSourceProviderHikariCPPoolSizing() { final DataSourceConnectionPoolingType poolingType = DataSourceConnectionPoolingType.HIKARICP; final DataSourceProvider.DatabaseType databaseType = DataSourceProvider.DatabaseType.H2; final Properties properties = defaultDaoConfigProperties(poolingType, databaseType); properties.put("org.killbill.dao.minIdle", "20"); properties.put("org.killbill.dao.maxActive", "50"); final DaoConfig daoConfig = buildDaoConfig(properties); final String poolName = TEST_POOL_PREFIX + "-1"; final DataSource dataSource = new DataSourceProvider(daoConfig, poolName).get(); assertTrue(dataSource instanceof HikariDataSource); final HikariDataSource hikariDataSource = (HikariDataSource) dataSource; assertEquals(50, hikariDataSource.getMaximumPoolSize()); assertEquals(20, hikariDataSource.getMinimumIdle()); } @Test(groups = "fast") public void testDataSourceProviderHikariCPSetsInitSQL() { final DataSourceConnectionPoolingType poolingType = DataSourceConnectionPoolingType.HIKARICP; final DataSourceProvider.DatabaseType databaseType = DataSourceProvider.DatabaseType.H2; final boolean shouldUseMariaDB = true; final Properties properties = defaultDaoConfigProperties(poolingType, databaseType); properties.put("org.killbill.dao.connectionInitSql", "SELECT 42"); final DaoConfig daoConfig = buildDaoConfig(properties); final String poolName = TEST_POOL_PREFIX + "-2"; final DataSource dataSource = new DataSourceProvider(daoConfig, poolName, shouldUseMariaDB).get(); assertTrue(dataSource instanceof HikariDataSource); final HikariDataSource hikariDataSource = (HikariDataSource) dataSource; assertEquals("SELECT 42", hikariDataSource.getConnectionInitSql()); } @Test(groups = "fast") public void testDataSourceProviderHikariCPSetsMariDBDefaults() throws SQLException { final DataSourceConnectionPoolingType poolingType = DataSourceConnectionPoolingType.HIKARICP; final DataSourceProvider.DatabaseType databaseType = DatabaseType.MYSQL; final boolean shouldUseMariaDB = true; final Properties properties = defaultDaoConfigProperties(poolingType, databaseType); final DaoConfig daoConfig = buildDaoConfig(properties); final String poolName = TEST_POOL_PREFIX + "-2"; final DataSource dataSource = new DataSourceProvider(daoConfig, poolName, shouldUseMariaDB).get(); assertTrue(dataSource instanceof HikariDataSource); final HikariDataSource hikariDataSource = (HikariDataSource) dataSource; final HikariPool hikariPool = new HikariPool(hikariDataSource); final DataSource wrappedDataSource = hikariPool.getUnwrappedDataSource(); assertTrue(wrappedDataSource instanceof KillBillMariaDbDataSource); final KillBillMariaDbDataSource mariaDbDataSource = (KillBillMariaDbDataSource) wrappedDataSource; final Configuration configuration = Configuration.parse(mariaDbDataSource.getUrl()); assertTrue(configuration.cachePrepStmts()); assertTrue(configuration.useServerPrepStmts()); } DaoConfig buildDaoConfig(final DataSourceConnectionPoolingType poolingType, final DataSourceProvider.DatabaseType databaseType) { return buildDaoConfig(defaultDaoConfigProperties(poolingType, databaseType)); } DaoConfig buildDaoConfig(final Properties properties) { return new AugmentedConfigurationObjectFactory(properties).build(DaoConfig.class); } private Properties defaultDaoConfigProperties(final DataSourceConnectionPoolingType poolingType, final DataSourceProvider.DatabaseType databaseType) { final Properties properties = new Properties(); properties.put("org.killbill.dao.poolingType", poolingType.toString()); if (DataSourceProvider.DatabaseType.MYSQL.equals(databaseType)) { properties.put("org.killbill.dao.url", "jdbc:mysql://127.0.0.1:3306/killbill"); } else if (DataSourceProvider.DatabaseType.H2.equals(databaseType)) { properties.put("org.killbill.dao.url", "jdbc:h2:file:/var/tmp/killbill;MODE=LEGACY;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); } else { properties.put("org.killbill.dao.url", "jdbc:test:@myhost:1521:orcl"); logger.info("GenericDriver.class.getName() = " + GenericDriver.class.getName()); properties.put("org.killbill.dao.driverClassName", GenericDriver.class.getName()); } return properties; } public static final class GenericDriver implements Driver { static { try { DriverManager.registerDriver(new GenericDriver()); } catch (final SQLException e) { throw new RuntimeException("Could not register driver", e); } } public Connection connect(final String url, final Properties info) throws SQLException { logger.info(this + " connect " + url + " " + info); return new ConnectionStub(); } public boolean acceptsURL(final String url) throws SQLException { return url.contains(":test:"); } public DriverPropertyInfo[] getPropertyInfo(final String url, final Properties info) throws SQLException { return new DriverPropertyInfo[0]; } public int getMajorVersion() { return 0; } public int getMinorVersion() { return 0; } public boolean jdbcCompliant() { return false; } public Logger getParentLogger() { return null; } private class ConnectionStub implements Connection { private boolean closed; public boolean isValid(final int timeout) throws SQLException { return !closed; } public void close() throws SQLException { closed = true; } public boolean isClosed() throws SQLException { return closed; } public DatabaseMetaData getMetaData() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public boolean isReadOnly() throws SQLException { return true; } public void setReadOnly(final boolean readOnly) throws SQLException { } public String getCatalog() throws SQLException { return null; } public void setCatalog(final String catalog) throws SQLException { } public int getTransactionIsolation() throws SQLException { return 0; } public void setTransactionIsolation(final int level) throws SQLException { } public Statement createStatement() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public PreparedStatement prepareStatement(final String sql) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public CallableStatement prepareCall(final String sql) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public String nativeSQL(final String sql) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public boolean getAutoCommit() throws SQLException { return false; } public void setAutoCommit(final boolean autoCommit) throws SQLException { } public void commit() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void rollback() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public SQLWarning getWarnings() throws SQLException { return null; } public void clearWarnings() throws SQLException { } public Statement createStatement(final int resultSetType, final int resultSetConcurrency) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Map<String, Class<?>> getTypeMap() throws SQLException { return Collections.emptyMap(); } public void setTypeMap(final Map<String, Class<?>> map) throws SQLException { } public int getHoldability() throws SQLException { return 0; } public void setHoldability(final int holdability) throws SQLException { } public Savepoint setSavepoint() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Savepoint setSavepoint(final String name) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void rollback(final Savepoint savepoint) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void releaseSavepoint(final Savepoint savepoint) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Statement createStatement(final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public PreparedStatement prepareStatement(final String sql, final int[] columnIndexes) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public PreparedStatement prepareStatement(final String sql, final String[] columnNames) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Clob createClob() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Blob createBlob() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public NClob createNClob() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public SQLXML createSQLXML() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setClientInfo(final String name, final String value) throws SQLClientInfoException { throw new UnsupportedOperationException("Not supported yet."); } public String getClientInfo(final String name) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Properties getClientInfo() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setClientInfo(final Properties properties) throws SQLClientInfoException { throw new UnsupportedOperationException("Not supported yet."); } public Array createArrayOf(final String typeName, final Object[] elements) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Struct createStruct(final String typeName, final Object[] attributes) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public String getSchema() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setSchema(final String schema) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void abort(final Executor executor) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNetworkTimeout(final Executor executor, final int milliseconds) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public int getNetworkTimeout() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } @SuppressWarnings("unchecked") public <T> T unwrap(final Class<T> iface) throws SQLException { return (T) this; } public boolean isWrapperFor(final Class<?> iface) throws SQLException { return iface.isInstance(this); } } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/template/TestKillBillSqlDaoStringTemplateFactory.java
jdbi/src/test/java/org/killbill/commons/jdbi/template/TestKillBillSqlDaoStringTemplateFactory.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi.template; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.killbill.commons.jdbi.JDBITestBase; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.customizers.Define; import org.testng.Assert; import org.testng.annotations.Test; public class TestKillBillSqlDaoStringTemplateFactory extends JDBITestBase { @Test(groups = "slow") public void testSimple() throws Exception { final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); final int computed = somethingSqlDao.doMath(1); Assert.assertEquals(computed, 2); } @Test(groups = "slow") public void testWithProxy() throws Exception { final Class[] interfaces = {SomethingSqlDao.class}; final InvocationHandler h = new SomethingProxy(); final Object newSqlDaoObject = Proxy.newProxyInstance(SomethingSqlDao.class.getClassLoader(), interfaces, h); final SomethingSqlDao somethingSqlDao = SomethingSqlDao.class.cast(newSqlDaoObject); final int computed = somethingSqlDao.doMath(1); Assert.assertEquals(computed, 2); } @Test(groups = "slow") public void testSimpleInheritance() throws Exception { final ChildSomethingSqlDao childSomethingSqlDao = dbi.onDemand(ChildSomethingSqlDao.class); int computed = childSomethingSqlDao.odMath(1); Assert.assertEquals(computed, -2); computed = childSomethingSqlDao.doMath(1); Assert.assertEquals(computed, 2); } @KillBillSqlDaoStringTemplate("/org/killbill/commons/jdbi/Something.sql.stg") private interface SomethingSqlDao { @SqlQuery public int doMath(@Define("val") final int val); } @KillBillSqlDaoStringTemplate("/org/killbill/commons/jdbi/ChildSomething.sql.stg") private interface ChildSomethingSqlDao extends SomethingSqlDao { @SqlQuery public int odMath(@Define("val") final int val); } private class SomethingProxy implements InvocationHandler { @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); return somethingSqlDao.doMath((Integer) args[0]); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/mapper/TestLowerToCamelBeanMapper.java
jdbi/src/test/java/org/killbill/commons/jdbi/mapper/TestLowerToCamelBeanMapper.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi.mapper; import java.io.IOException; import org.skife.jdbi.v2.exceptions.DBIException; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.killbill.commons.jdbi.JDBITestBase; public class TestLowerToCamelBeanMapper extends JDBITestBase { @BeforeMethod(groups = "slow") public void cleanupDb() throws Exception { cleanupDb("drop table if exists something;\n" + "create table something (id int primary key, lower_cased_field varchar(100), another_lower_cased_field int)"); } @Test(groups = "slow") public void testWithoutArgument() throws IOException { final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); somethingSqlDao.create(1, "pierre", 12); try { somethingSqlDao.getSomething(1); Assert.fail(); } catch (final DBIException e) { Assert.assertEquals(e.getMessage(), "No mapper registered for org.killbill.commons.jdbi.mapper.TestLowerToCamelBeanMapper$SomethingBean"); } } @Test(groups = "slow") public void testWithArgument() throws Exception { dbi.registerMapper(new LowerToCamelBeanMapperFactory(SomethingBean.class)); final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); final int fieldBPierre = Integer.MAX_VALUE; somethingSqlDao.create(1, "pierre", fieldBPierre); final int fieldBStephane = 29361; somethingSqlDao.create(2, "stephane", fieldBStephane); final SomethingBean foundPierre = somethingSqlDao.getSomething(1); Assert.assertEquals(foundPierre.getLowerCasedField(), "pierre"); Assert.assertEquals(foundPierre.getAnotherLowerCasedField(), fieldBPierre); final SomethingBean foundStephane = somethingSqlDao.getSomething(2); Assert.assertEquals(foundStephane.getLowerCasedField(), "stephane"); Assert.assertEquals(foundStephane.getAnotherLowerCasedField(), fieldBStephane); } private interface SomethingSqlDao { @SqlUpdate("insert into something (id, lower_cased_field, another_lower_cased_field) values (:id, :fieldA, :fieldB)") public void create(@Bind("id") final int id, @Bind("fieldA") final String fieldA, @Bind("fieldB") final int fieldB); @SqlQuery("select lower_cased_field, another_lower_cased_field from something where id = :id") public SomethingBean getSomething(@Bind("id") final int id); } // Needs to be public for the reflection magic public static final class SomethingBean { private String lowerCasedField; private long anotherLowerCasedField; public String getLowerCasedField() { return lowerCasedField; } public long getAnotherLowerCasedField() { return anotherLowerCasedField; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/mapper/TestUUIDMapper.java
jdbi/src/test/java/org/killbill/commons/jdbi/mapper/TestUUIDMapper.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi.mapper; import java.io.IOException; import java.util.UUID; import org.skife.jdbi.v2.exceptions.DBIException; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.killbill.commons.jdbi.JDBITestBase; public class TestUUIDMapper extends JDBITestBase { @BeforeMethod(groups = "slow") public void cleanupDb() throws Exception { cleanupDb("drop table if exists something;\n" + "create table something (id int primary key, name varchar(100), unique_id varchar(100))"); } @Test(groups = "slow") public void testWithoutArgument() throws IOException { final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); somethingSqlDao.create(1, "pierre", UUID.randomUUID().toString()); try { somethingSqlDao.getUniqueId(1); Assert.fail(); } catch (final DBIException e) { Assert.assertEquals(e.getMessage(), "No mapper registered for java.util.UUID"); } } @Test(groups = "slow") public void testWithArgument() throws Exception { dbi.registerMapper(new UUIDMapper()); final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); final UUID idPierre = UUID.randomUUID(); somethingSqlDao.create(1, "pierre", idPierre.toString()); final UUID idStephane = UUID.randomUUID(); somethingSqlDao.create(2, "stephane", idStephane.toString()); final UUID idFoundPierre = somethingSqlDao.getUniqueId(1); Assert.assertEquals(idFoundPierre, idPierre); final UUID idFoundStephane = somethingSqlDao.getUniqueId(2); Assert.assertEquals(idFoundStephane, idStephane); } private interface SomethingSqlDao { @SqlUpdate("insert into something (id, name, unique_id) values (:id, :name, :uniqueId)") public void create(@Bind("id") final int id, @Bind("name") final String name, @Bind("uniqueId") final String uniqueId); @SqlQuery("select unique_id from something where id = :id") public UUID getUniqueId(@Bind("id") final int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestUUIDArgumentFactory.java
jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestUUIDArgumentFactory.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi.argument; import java.util.UUID; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.killbill.commons.jdbi.JDBITestBase; public class TestUUIDArgumentFactory extends JDBITestBase { @BeforeMethod(groups = "slow") public void cleanupDb() throws Exception { cleanupDb("drop table if exists something;\n" + "create table something (id int primary key, name varchar(100), unique_id varchar(100))"); } @Test(groups = "slow") public void testWithArgument() throws Exception { dbi.registerArgumentFactory(new UUIDArgumentFactory()); final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); final UUID idPierre = UUID.randomUUID(); somethingSqlDao.create(1, "pierre", idPierre); final UUID idStephane = UUID.randomUUID(); somethingSqlDao.create(2, "stephane", idStephane); final String idStringPierre = somethingSqlDao.getUniqueId(1); Assert.assertEquals(idStringPierre, idPierre.toString()); final String idStringStephane = somethingSqlDao.getUniqueId(2); Assert.assertEquals(idStringStephane, idStephane.toString()); } private interface SomethingSqlDao { @SqlUpdate("insert into something (id, name, unique_id) values (:id, :name, :uniqueId)") public void create(@Bind("id") final int id, @Bind("name") final String name, @Bind("uniqueId") final UUID uniqueId); @SqlQuery("select unique_id from something where id = :id") public String getUniqueId(@Bind("id") final int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestEnumArgumentFactory.java
jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestEnumArgumentFactory.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi.argument; import org.killbill.commons.jdbi.JDBITestBase; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestEnumArgumentFactory extends JDBITestBase { private enum Bier { hefeweizen, ipa } @BeforeMethod(groups = "slow") public void cleanupDb() throws Exception { cleanupDb("drop table if exists something;\n" + "create table something (id int primary key, name varchar(100), bier varchar(100))"); } @Test(groups = "slow") public void testWithArgument() throws Exception { final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); final Bier bierPierre = Bier.ipa; somethingSqlDao.create(1, "pierre", bierPierre); final Bier bierStephane = Bier.hefeweizen; somethingSqlDao.create(2, "stephane", bierStephane); final String bierStringPierre = somethingSqlDao.getBier(1); Assert.assertEquals(bierStringPierre, bierPierre.toString()); final String bierStringStephane = somethingSqlDao.getBier(2); Assert.assertEquals(bierStringStephane, bierStephane.toString()); } private interface SomethingSqlDao { @SqlUpdate("insert into something (id, name, bier) values (:id, :name, :bier)") public void create(@Bind("id") final int id, @Bind("name") final String name, @Bind("bier") final Bier bier); @SqlQuery("select bier from something where id = :id") public String getBier(@Bind("id") final int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestDateTimeArgumentFactory.java
jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestDateTimeArgumentFactory.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi.argument; import java.io.IOException; import java.sql.Timestamp; import org.h2.jdbc.JdbcSQLDataException; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.killbill.commons.jdbi.JDBITestBase; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestDateTimeArgumentFactory extends JDBITestBase { @BeforeMethod(groups = "slow") public void cleanupDb() throws Exception { cleanupDb("drop table if exists something;\n" + "create table something (id int primary key, name varchar(100), created_dt datetime)"); } @Test(groups = "slow") public void testWithoutArgument() throws IOException { final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); try { somethingSqlDao.create(1, "pierre", new DateTime(DateTimeZone.UTC)); Assert.fail(); } catch (final UnableToExecuteStatementException e) { Assert.assertTrue(e.getCause() instanceof JdbcSQLDataException); } } @Test(groups = "slow") public void testWithArgument() throws Exception { dbi.registerArgumentFactory(new DateTimeArgumentFactory()); final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); final DateTime dateTimePierre = new DateTime(2012, 10, 5, 8, 10, DateTimeZone.UTC); somethingSqlDao.create(1, "pierre", dateTimePierre); final DateTime dateTimeStephane = new DateTime(2009, 3, 1, 0, 1, DateTimeZone.UTC); somethingSqlDao.create(2, "stephane", dateTimeStephane); final Timestamp datePierre = somethingSqlDao.getCreatedDt(1); Assert.assertEquals(datePierre.getTime(), dateTimePierre.getMillis()); final Timestamp dateStephane = somethingSqlDao.getCreatedDt(2); Assert.assertEquals(dateStephane.getTime(), dateTimeStephane.getMillis()); } private interface SomethingSqlDao { @SqlUpdate("insert into something (id, name, created_dt) values (:id, :name, :createdDt)") public void create(@Bind("id") final int id, @Bind("name") final String name, @Bind("createdDt") final DateTime dateTime); @SqlQuery("select created_dt from something where id = :id") public Timestamp getCreatedDt(@Bind("id") final int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestDateTimeZoneArgumentFactory.java
jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestDateTimeZoneArgumentFactory.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi.argument; import java.io.IOException; import org.h2.jdbc.JdbcSQLDataException; import org.joda.time.DateTimeZone; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.killbill.commons.jdbi.JDBITestBase; public class TestDateTimeZoneArgumentFactory extends JDBITestBase { @BeforeMethod(groups = "slow") public void cleanupDb() throws Exception { cleanupDb("drop table if exists something;\n" + "create table something (id int primary key, name varchar(100), created_tz varchar(100))"); } @Test(groups = "slow") public void testWithoutArgument() throws IOException { final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); try { somethingSqlDao.create(1, "pierre", DateTimeZone.UTC); Assert.fail(); } catch (final UnableToExecuteStatementException e) { Assert.assertTrue(e.getCause() instanceof JdbcSQLDataException); } } @Test(groups = "slow") public void testWithArgument() throws Exception { dbi.registerArgumentFactory(new DateTimeZoneArgumentFactory()); final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); final DateTimeZone dateTimeZonePierre = DateTimeZone.UTC; somethingSqlDao.create(1, "pierre", dateTimeZonePierre); final DateTimeZone dateTimeZoneStephane = DateTimeZone.forID("Europe/London"); somethingSqlDao.create(2, "stephane", dateTimeZoneStephane); final String tzStringPierre = somethingSqlDao.getCreatedTZ(1); Assert.assertEquals(tzStringPierre, dateTimeZonePierre.toString()); final String tzStringStephane = somethingSqlDao.getCreatedTZ(2); Assert.assertEquals(tzStringStephane, dateTimeZoneStephane.toString()); } private interface SomethingSqlDao { @SqlUpdate("insert into something (id, name, created_tz) values (:id, :name, :createdTZ)") public void create(@Bind("id") final int id, @Bind("name") final String name, @Bind("createdTZ") final DateTimeZone dateTimeZone); @SqlQuery("select created_tz from something where id = :id") public String getCreatedTZ(@Bind("id") final int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestLocalDateArgumentFactory.java
jdbi/src/test/java/org/killbill/commons/jdbi/argument/TestLocalDateArgumentFactory.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.jdbi.argument; import java.io.IOException; import org.h2.jdbc.JdbcSQLDataException; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.killbill.commons.jdbi.JDBITestBase; public class TestLocalDateArgumentFactory extends JDBITestBase { @BeforeMethod(groups = "slow") public void cleanupDb() throws Exception { cleanupDb("drop table if exists something;\n" + "create table something (id int primary key, name varchar(100), created_dt varchar(100))"); } @Test(groups = "slow") public void testWithoutArgument() throws IOException { final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); try { somethingSqlDao.create(1, "pierre", new LocalDate(DateTimeZone.UTC)); Assert.fail(); } catch (final UnableToExecuteStatementException e) { Assert.assertTrue(e.getCause() instanceof JdbcSQLDataException); } } @Test(groups = "slow") public void testWithArgument() throws Exception { dbi.registerArgumentFactory(new LocalDateArgumentFactory()); final SomethingSqlDao somethingSqlDao = dbi.onDemand(SomethingSqlDao.class); final LocalDate localDatePierre = new LocalDate(2012, 5, 12); somethingSqlDao.create(1, "pierre", localDatePierre); final LocalDate localDateStephane = new LocalDate(2009, 3, 9); somethingSqlDao.create(2, "stephane", localDateStephane); final String localDateStringPierre = somethingSqlDao.getCreatedDt(1); Assert.assertEquals(localDateStringPierre, localDatePierre.toString()); final String localDateStringStephane = somethingSqlDao.getCreatedDt(2); Assert.assertEquals(localDateStringStephane, localDateStephane.toString()); } private interface SomethingSqlDao { @SqlUpdate("insert into something (id, name, created_dt) values (:id, :name, :createdDt)") public void create(@Bind("id") final int id, @Bind("name") final String name, @Bind("createdDt") final LocalDate createdDt); @SqlQuery("select created_dt from something where id = :id") public String getCreatedDt(@Bind("id") final int id); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/PreparedBatchPart.java
jdbi/src/main/java/org/skife/jdbi/v2/PreparedBatchPart.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.SQLLog; import org.skife.jdbi.v2.tweak.StatementBuilder; import org.skife.jdbi.v2.tweak.StatementCustomizer; import org.skife.jdbi.v2.tweak.StatementLocator; import org.skife.jdbi.v2.tweak.StatementRewriter; import java.util.Collections; /** * Represents a single statement in a prepared batch * * @see PreparedBatch */ public class PreparedBatchPart extends SQLStatement<PreparedBatchPart> { private final PreparedBatch batch; PreparedBatchPart(Binding binding, PreparedBatch batch, StatementLocator locator, StatementRewriter rewriter, Handle handle, StatementBuilder cache, String sql, ConcreteStatementContext context, SQLLog log, TimingCollector timingCollector, Foreman foreman, ContainerFactoryRegistry containerFactoryRegistry) { super(binding, locator, rewriter, handle, cache, sql, context, log, timingCollector, Collections.<StatementCustomizer>emptyList(), foreman, containerFactoryRegistry); this.batch = batch; } /** * Submit this statement to the batch, yielding the batch. The statement is already, * actually part of the batch before it is submitted. This method is really just * a convenient way to getAttribute the prepared batch back. * * @return the PreparedBatch which this is a part of */ public PreparedBatch submit() { return batch; } /** * Submit this part of the batch and open a fresh one * * @return a fresh PrepatedBatchPart on the same batch */ public PreparedBatchPart next() { return batch.add(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/DefaultStatementBuilderFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/DefaultStatementBuilderFactory.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.StatementBuilder; import org.skife.jdbi.v2.tweak.StatementBuilderFactory; import java.sql.Connection; /** * */ public class DefaultStatementBuilderFactory implements StatementBuilderFactory { /** * Obtain a StatementBuilder, called when a new handle is opened */ @Override public StatementBuilder createStatementBuilder(Connection conn) { return new DefaultStatementBuilder(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/PreparedBatch.java
jdbi/src/main/java/org/skife/jdbi/v2/PreparedBatch.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.tweak.RewrittenStatement; import org.skife.jdbi.v2.tweak.SQLLog; import org.skife.jdbi.v2.tweak.StatementBuilder; import org.skife.jdbi.v2.tweak.StatementCustomizer; import org.skife.jdbi.v2.tweak.StatementLocator; import org.skife.jdbi.v2.tweak.StatementRewriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * Represents a prepared batch statement. That is, a sql statement compiled as a prepared * statement, and then executed multiple times in a single batch. This is, generally, * a very efficient way to execute large numbers of the same statement where * the statement only varies by the arguments bound to it. */ public class PreparedBatch extends SQLStatement<PreparedBatch> { private final List<PreparedBatchPart> parts = new ArrayList<PreparedBatchPart>(); private Binding currentBinding; PreparedBatch(StatementLocator locator, StatementRewriter rewriter, Handle handle, StatementBuilder statementBuilder, String sql, ConcreteStatementContext ctx, SQLLog log, TimingCollector timingCollector, Collection<StatementCustomizer> statementCustomizers, Foreman foreman, ContainerFactoryRegistry containerFactoryRegistry) { super(new Binding(), locator, rewriter, handle, statementBuilder, sql, ctx, log, timingCollector, statementCustomizers, foreman, containerFactoryRegistry); this.currentBinding = new Binding(); } /** * Specify a value on the statement context for this batch * * @return self */ @Override public PreparedBatch define(String key, Object value) { getContext().setAttribute(key, value); return this; } /** * Adds all key/value pairs in the Map to the {@link StatementContext}. * * @param values containing key/value pairs. * @return this */ @Override public PreparedBatch define(final Map<String, ? extends Object> values) { if (values != null) { for (Map.Entry<String, ? extends Object> entry: values.entrySet()) { getContext().setAttribute(entry.getKey(), entry.getValue()); } } return this; } /** * Execute the batch * * @return the number of rows modified or inserted per batch part. */ public int[] execute() { return (int[]) internalBatchExecute(null, null); } @SuppressWarnings("unchecked") public <GeneratedKeyType> GeneratedKeys<GeneratedKeyType> executeAndGenerateKeys(final ResultSetMapper<GeneratedKeyType> mapper, String... columnNames) { return (GeneratedKeys<GeneratedKeyType>) internalBatchExecute(new QueryResultMunger<GeneratedKeys<GeneratedKeyType>>() { public GeneratedKeys<GeneratedKeyType> munge(Statement results) throws SQLException { return new GeneratedKeys<GeneratedKeyType>(mapper, PreparedBatch.this, results, getContext(), getContainerMapperRegistry()); } }, columnNames); } private <Result> Object internalBatchExecute(QueryResultMunger<Result> munger, String[] columnNames) { boolean generateKeys = munger != null; // short circuit empty batch if (parts.size() == 0) { if (generateKeys) { throw new IllegalArgumentException("Unable generate keys for a not prepared batch"); } return new int[]{}; } PreparedBatchPart current = parts.get(0); final String my_sql ; try { my_sql = getStatementLocator().locate(getSql(), getContext()); } catch (Exception e) { throw new UnableToCreateStatementException(String.format("Exception while locating statement for [%s]", getSql()), e, getContext()); } final RewrittenStatement rewritten = getRewriter().rewrite(my_sql, current.getParams(), getContext()); PreparedStatement stmt = null; try { try { Connection connection = getHandle().getConnection(); if (generateKeys) { if (columnNames != null && columnNames.length > 0) { stmt = connection.prepareStatement(rewritten.getSql(), columnNames); } else { stmt = connection.prepareStatement(rewritten.getSql(), Statement.RETURN_GENERATED_KEYS); } } else { stmt = connection.prepareStatement(rewritten.getSql(), Statement.NO_GENERATED_KEYS); } addCleanable(Cleanables.forStatement(stmt)); } catch (SQLException e) { throw new UnableToCreateStatementException(e, getContext()); } try { for (PreparedBatchPart part : parts) { rewritten.bind(part.getParams(), stmt); stmt.addBatch(); } } catch (SQLException e) { throw new UnableToExecuteStatementException("Exception while binding parameters", e, getContext()); } beforeExecution(stmt); try { final long start = System.nanoTime(); final int[] rs = stmt.executeBatch(); final long elapsedTime = System.nanoTime() - start; getLog().logPreparedBatch(elapsedTime / 1000000L, rewritten.getSql(), parts.size()); getTimingCollector().collect(elapsedTime, getContext()); afterExecution(stmt); return generateKeys ? munger.munge(stmt) : rs; } catch (SQLException e) { throw new UnableToExecuteStatementException(e, getContext()); } } finally { try { if (!generateKeys) { cleanup(); } } finally { this.parts.clear(); } } } /** * Add a statement (part) to this batch. You'll need to bindBinaryStream any arguments to the * part. * * @return A part which can be used to bindBinaryStream parts to the statement */ public PreparedBatchPart add() { PreparedBatchPart part = new PreparedBatchPart(this.currentBinding, this, getStatementLocator(), getRewriter(), getHandle(), getStatementBuilder(), getSql(), getConcreteContext(), getLog(), getTimingCollector(), getForeman(), getContainerMapperRegistry()); parts.add(part); this.currentBinding = new Binding(); return part; } public PreparedBatch add(Object... args) { PreparedBatchPart part = add(); for (int i = 0; i < args.length; ++i) { part.bind(i, args[i]); } return this; } /** * Create a new batch part by binding values looked up in <code>args</code> to * named parameters on the statement. * * @param args map to bind arguments from for named parameters on the statement * * @return the new batch part */ public PreparedBatchPart add(Map<String, ? extends Object> args) { PreparedBatchPart part = add(); part.bindFromMap(args); return part; } /** * The number of statements which are in this batch */ public int getSize() { return parts.size(); } /** * The number of statements which are in this batch */ public int size() { return parts.size(); } @Override protected Binding getParams() { return this.currentBinding; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/UnwrappedSingleValueFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/UnwrappedSingleValueFactory.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.ContainerFactory; class UnwrappedSingleValueFactory implements ContainerFactory<Object> { @Override public boolean accepts(Class<?> type) { return UnwrappedSingleValue.class.equals(type); } @Override public ContainerBuilder newContainerBuilderFor(Class<?> type) { return new ContainerBuilder<Object>() { private Object it; @Override public ContainerBuilder add(Object it) { this.it = it; return this; } @Override public Object build() { return it; } }; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/ShortArgument.java
jdbi/src/main/java/org/skife/jdbi/v2/ShortArgument.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.Argument; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * */ class ShortArgument implements Argument { private final Short value; ShortArgument(Short value) { this.value = value; } @Override public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException { if (value != null) { statement.setShort(position, value); } else { statement.setNull(position, Types.SMALLINT); } } @Override public String toString() { return String.valueOf(value); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/QueryResultSetMunger.java
jdbi/src/main/java/org/skife/jdbi/v2/QueryResultSetMunger.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.exceptions.NoResultsException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; abstract class QueryResultSetMunger<T> implements QueryResultMunger<T> { private BaseStatement stmt; QueryResultSetMunger(final BaseStatement stmt) { this.stmt = stmt; } @Override public final T munge(Statement results) throws SQLException { ResultSet rs = results.getResultSet(); if (rs == null) { throw new NoResultsException("Query did not have a result set, perhaps you meant update?", stmt.getContext()); } stmt.addCleanable(Cleanables.forResultSet(rs)); return munge(rs); } protected abstract T munge(ResultSet rs) throws SQLException; }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/Transaction.java
jdbi/src/main/java/org/skife/jdbi/v2/Transaction.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; public interface Transaction<ReturnType, ConnectionType> { /** * Execute in a transaction. Will be committed afterwards, or rolled back if a transaction * is thrown. * <p> * If the transaction fails a {@link org.skife.jdbi.v2.exceptions.TransactionFailedException} * will be thrown from the {@link Handle#inTransaction(TransactionCallback)} * * @param transactional The object communicating with the database. * @param status a handle on the transaction, kind of * @return Something to return from {@link Handle#inTransaction(TransactionCallback)} * @throws Exception will cause the transaction be aborted */ ReturnType inTransaction(ConnectionType transactional, TransactionStatus status) throws Exception; }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/StatementCustomizers.java
jdbi/src/main/java/org/skife/jdbi/v2/StatementCustomizers.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.BaseStatementCustomizer; import org.skife.jdbi.v2.tweak.StatementCustomizer; import java.sql.PreparedStatement; import java.sql.SQLException; public final class StatementCustomizers { private StatementCustomizers() { } /** * Hint to the statement, that we want only a single row. Used by {@link Query#first()} to limit the number * of rows returned by the database. */ public static final StatementCustomizer MAX_ROW_ONE = new MaxRowsCustomizer(1); /** * Sets the fetch direction on a query. Can be used as a Statement customizer or a SqlStatementCustomizer. */ public static class FetchDirectionStatementCustomizer extends BaseStatementCustomizer { private final Integer direction; public FetchDirectionStatementCustomizer(final Integer direction) { this.direction = direction; } @Override public void beforeExecution(final PreparedStatement stmt, final StatementContext ctx) throws SQLException { stmt.setFetchDirection(direction); } public void apply(SQLStatement q) throws SQLException { q.setFetchDirection(direction); } } public static final class QueryTimeoutCustomizer extends BaseStatementCustomizer { private final int seconds; public QueryTimeoutCustomizer(final int seconds) { this.seconds = seconds; } @Override public void beforeExecution(final PreparedStatement stmt, final StatementContext ctx) throws SQLException { stmt.setQueryTimeout(seconds); } } public static final class FetchSizeCustomizer extends BaseStatementCustomizer { private final int fetchSize; public FetchSizeCustomizer(final int fetchSize) { this.fetchSize = fetchSize; } @Override public void beforeExecution(final PreparedStatement stmt, final StatementContext ctx) throws SQLException { stmt.setFetchSize(fetchSize); } } public static final class MaxRowsCustomizer extends BaseStatementCustomizer { private final int maxRows; public MaxRowsCustomizer(final int maxRows) { this.maxRows = maxRows; } @Override public void beforeExecution(final PreparedStatement stmt, final StatementContext ctx) throws SQLException { stmt.setMaxRows(maxRows); } } public static final class MaxFieldSizeCustomizer extends BaseStatementCustomizer { private final int maxFieldSize; public MaxFieldSizeCustomizer(final int maxFieldSize) { this.maxFieldSize = maxFieldSize; } @Override public void beforeExecution(final PreparedStatement stmt, final StatementContext ctx) throws SQLException { stmt.setMaxFieldSize(maxFieldSize); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/BasicHandle.java
jdbi/src/main/java/org/skife/jdbi/v2/BasicHandle.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.exceptions.UnableToCloseResourceException; import org.skife.jdbi.v2.exceptions.UnableToManipulateTransactionIsolationLevelException; import org.skife.jdbi.v2.sqlobject.SqlObjectBuilder; import org.skife.jdbi.v2.tweak.ArgumentFactory; import org.skife.jdbi.v2.tweak.ContainerFactory; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.tweak.SQLLog; import org.skife.jdbi.v2.tweak.StatementBuilder; import org.skife.jdbi.v2.tweak.StatementCustomizer; import org.skife.jdbi.v2.tweak.StatementLocator; import org.skife.jdbi.v2.tweak.StatementRewriter; import org.skife.jdbi.v2.tweak.TransactionHandler; import java.sql.Connection; import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; class BasicHandle implements Handle { private static final DefaultMapper DEFAULT_MAPPER = new DefaultMapper(); private StatementRewriter statementRewriter; private StatementLocator statementLocator; private SQLLog log; private TimingCollector timingCollector; private StatementBuilder statementBuilder; private boolean closed = false; private final Map<String, Object> globalStatementAttributes; private final MappingRegistry mappingRegistry; private final ContainerFactoryRegistry containerFactoryRegistry; private final Foreman foreman; private final TransactionHandler transactions; private final Connection connection; BasicHandle(TransactionHandler transactions, StatementLocator statementLocator, StatementBuilder preparedStatementCache, StatementRewriter statementRewriter, Connection connection, Map<String, Object> globalStatementAttributes, SQLLog log, TimingCollector timingCollector, MappingRegistry mappingRegistry, Foreman foreman, ContainerFactoryRegistry containerFactoryRegistry) { this.statementBuilder = preparedStatementCache; this.statementRewriter = statementRewriter; this.transactions = transactions; this.connection = connection; this.statementLocator = statementLocator; this.log = log; this.timingCollector = timingCollector; this.mappingRegistry = mappingRegistry; this.foreman = foreman; this.globalStatementAttributes = new HashMap<String, Object>(); this.globalStatementAttributes.putAll(globalStatementAttributes); this.containerFactoryRegistry = containerFactoryRegistry.createChild(); } @Override public Query<Map<String, Object>> createQuery(String sql) { return new Query<Map<String, Object>>(new Binding(), DEFAULT_MAPPER, statementLocator, statementRewriter, this, statementBuilder, sql, new ConcreteStatementContext(globalStatementAttributes), log, timingCollector, Collections.<StatementCustomizer>emptyList(), mappingRegistry.createChild(), foreman.createChild(), containerFactoryRegistry.createChild()); } /** * Get the JDBC Connection this Handle uses * * @return the JDBC Connection this Handle uses */ @Override public Connection getConnection() { return this.connection; } @Override public void close() { if (!closed) { statementBuilder.close(getConnection()); try { connection.close(); } catch (SQLException e) { throw new UnableToCloseResourceException("Unable to close Connection", e); } finally { log.logReleaseHandle(this); closed = true; } } } boolean isClosed() { return closed; } @Override public void define(String key, Object value) { this.globalStatementAttributes.put(key, value); } /** * Start a transaction */ @Override public Handle begin() { transactions.begin(this); log.logBeginTransaction(this); return this; } /** * Commit a transaction */ @Override public Handle commit() { final long start = System.nanoTime(); transactions.commit(this); log.logCommitTransaction((System.nanoTime() - start) / 1000000L, this); return this; } /** * Rollback a transaction */ @Override public Handle rollback() { final long start = System.nanoTime(); transactions.rollback(this); log.logRollbackTransaction((System.nanoTime() - start) / 1000000L, this); return this; } /** * Create a transaction checkpoint (savepoint in JDBC terminology) with the name provided. * * @param name The name of the checkpoint * * @return The same handle */ @Override public Handle checkpoint(String name) { transactions.checkpoint(this, name); log.logCheckpointTransaction(this, name); return this; } /** * Release the named checkpoint, making rollback to it not possible. * * @return The same handle */ @Override public Handle release(String checkpointName) { transactions.release(this, checkpointName); log.logReleaseCheckpointTransaction(this, checkpointName); return this; } @Override public void setStatementBuilder(StatementBuilder builder) { this.statementBuilder = builder; } @Override public void setSQLLog(SQLLog log) { this.log = log; } @Override public void setTimingCollector(final TimingCollector timingCollector) { if (timingCollector == null) { this.timingCollector = TimingCollector.NOP_TIMING_COLLECTOR; } else { this.timingCollector = timingCollector; } } /** * Rollback a transaction to a named checkpoint * * @param checkpointName the name of the checkpoint, previously declared with {@see Handle#checkpoint} */ @Override public Handle rollback(String checkpointName) { final long start = System.nanoTime(); transactions.rollback(this, checkpointName); log.logRollbackToCheckpoint((System.nanoTime() - start) / 1000000L, this, checkpointName); return this; } @Override public boolean isInTransaction() { return transactions.isInTransaction(this); } @Override public Update createStatement(String sql) { return new Update(this, statementLocator, statementRewriter, statementBuilder, sql, new ConcreteStatementContext(globalStatementAttributes), log, timingCollector, foreman, containerFactoryRegistry); } @Override public Call createCall(String sql) { return new Call(this, statementLocator, statementRewriter, statementBuilder, sql, new ConcreteStatementContext(globalStatementAttributes), log, timingCollector, Collections.<StatementCustomizer>emptyList(), foreman, containerFactoryRegistry); } @Override public int insert(String sql, Object... args) { return update(sql, args); } @Override public int update(String sql, Object... args) { Update stmt = createStatement(sql); int position = 0; for (Object arg : args) { stmt.bind(position++, arg); } return stmt.execute(); } @Override public PreparedBatch prepareBatch(String sql) { return new PreparedBatch(statementLocator, statementRewriter, this, statementBuilder, sql, new ConcreteStatementContext(this.globalStatementAttributes), log, timingCollector, Collections.<StatementCustomizer>emptyList(), foreman, containerFactoryRegistry); } @Override public Batch createBatch() { return new Batch(this.statementRewriter, this.connection, globalStatementAttributes, log, timingCollector, foreman.createChild()); } @Override public <ReturnType> ReturnType inTransaction(TransactionCallback<ReturnType> callback) { return transactions.inTransaction(this, callback); } @Override public <ReturnType> ReturnType inTransaction(TransactionIsolationLevel level, TransactionCallback<ReturnType> callback) { final TransactionIsolationLevel initial = getTransactionIsolationLevel(); boolean failed = true; try { setTransactionIsolation(level); ReturnType result = transactions.inTransaction(this, level, callback); failed = false; return result; } finally { try { setTransactionIsolation(initial); } catch (RuntimeException e) { if (! failed) { throw e; } // Ignore, there was already an exceptional condition and we don't want to clobber it. } } } @Override public List<Map<String, Object>> select(String sql, Object... args) { Query<Map<String, Object>> query = this.createQuery(sql); int position = 0; for (Object arg : args) { query.bind(position++, arg); } return query.list(); } @Override public void setStatementLocator(StatementLocator locator) { this.statementLocator = locator; } @Override public void setStatementRewriter(StatementRewriter rewriter) { this.statementRewriter = rewriter; } @Override public Script createScript(String name) { return new Script(this, statementLocator, name, globalStatementAttributes); } @Override public void execute(String sql, Object... args) { this.update(sql, args); } @Override public void registerMapper(ResultSetMapper mapper) { //mappingRegistry.add(mapper); throw new UnsupportedOperationException("[OPTIMIZATION] Registering a custom ResultSetMapper on a Handle is disabled"); } @Override public void registerMapper(ResultSetMapperFactory factory) { //mappingRegistry.add(factory); throw new UnsupportedOperationException("[OPTIMIZATION] Registering a custom ResultSetMapperFactory on a Handle is disabled"); } @Override public <SqlObjectType> SqlObjectType attach(Class<SqlObjectType> sqlObjectType) { return SqlObjectBuilder.attach(this, sqlObjectType); } @Override public void setTransactionIsolation(TransactionIsolationLevel level) { setTransactionIsolation(level.intValue()); } @Override public void setTransactionIsolation(int level) { try { if (connection.getTransactionIsolation() == level) { // already set, noop return; } connection.setTransactionIsolation(level); } catch (SQLException e) { throw new UnableToManipulateTransactionIsolationLevelException(level, e); } } @Override public TransactionIsolationLevel getTransactionIsolationLevel() { try { return TransactionIsolationLevel.valueOf(connection.getTransactionIsolation()); } catch (SQLException e) { throw new UnableToManipulateTransactionIsolationLevelException("unable to access current setting", e); } } @Override public void registerArgumentFactory(ArgumentFactory argumentFactory) { //this.foreman.register(argumentFactory); throw new UnsupportedOperationException("[OPTIMIZATION] Registering a custom ArgumentFactory on a Handle is disabled"); } @Override public void registerContainerFactory(ContainerFactory<?> factory) { this.containerFactoryRegistry.register(factory); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/Foreman.java
jdbi/src/main/java/org/skife/jdbi/v2/Foreman.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.Argument; import org.skife.jdbi.v2.tweak.ArgumentFactory; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; class Foreman { private final Map<Class<?>, ArgumentFactory> cache = new ConcurrentHashMap<Class<?>, ArgumentFactory>(); private final List<ArgumentFactory> factories = new CopyOnWriteArrayList<ArgumentFactory>(); public Foreman() { factories.add(BUILT_INS); } public Foreman(List<ArgumentFactory> factories) { this.factories.addAll(factories); } Argument waffle(Class expectedType, Object it, StatementContext ctx) { if (cache.containsKey(expectedType)) { return cache.get(expectedType).build(expectedType, it, ctx); } ArgumentFactory candidate = null; for (int i = factories.size() - 1; i >= 0; i--) { ArgumentFactory factory = factories.get(i); if (factory.accepts(expectedType, it, ctx)) { // Note! Cache assumes all ArgumentFactory#accepts implementations don't care about the Object it itself cache.put(expectedType, factory); return factory.build(expectedType, it, ctx); } // Fall back to any factory accepting Object if necessary but // prefer any more specific factory first. if (candidate == null && factory.accepts(Object.class, it, ctx)) { candidate = factory; } } if (candidate != null) { cache.put(Object.class, candidate); return candidate.build(Object.class, it, ctx); } throw new IllegalStateException("Unbindable argument passed: " + String.valueOf(it)); } private static final ArgumentFactory BUILT_INS = new BuiltInArgumentFactory(); public void register(ArgumentFactory<?> argumentFactory) { // [OPTIMIZATION] Only allowed at a global level (DBI) factories.add(argumentFactory); } public Foreman createChild() { // [OPTIMIZATION] See above //return new Foreman(factories); return this; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/PrimitivesMapperFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/PrimitivesMapperFactory.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.util.BigDecimalMapper; import org.skife.jdbi.v2.util.BooleanMapper; import org.skife.jdbi.v2.util.ByteArrayMapper; import org.skife.jdbi.v2.util.ByteMapper; import org.skife.jdbi.v2.util.DoubleMapper; import org.skife.jdbi.v2.util.FloatMapper; import org.skife.jdbi.v2.util.IntegerMapper; import org.skife.jdbi.v2.util.LongMapper; import org.skife.jdbi.v2.util.ShortMapper; import org.skife.jdbi.v2.util.StringMapper; import org.skife.jdbi.v2.util.TimestampMapper; import org.skife.jdbi.v2.util.URLMapper; import java.math.BigDecimal; import java.net.URL; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; /** * Result set mapper factory which knows how to construct java primitive types. */ public class PrimitivesMapperFactory implements ResultSetMapperFactory { private static final Map<Class, ResultSetMapper> mappers = new HashMap<Class, ResultSetMapper>(); static { mappers.put(BigDecimal.class, BigDecimalMapper.FIRST); mappers.put(Boolean.class, BooleanMapper.FIRST); mappers.put(boolean.class, BooleanMapper.FIRST); mappers.put(byte[].class, ByteArrayMapper.FIRST); mappers.put(short.class, ShortMapper.FIRST); mappers.put(Short.class, ShortMapper.FIRST); mappers.put(Float.class, FloatMapper.FIRST); mappers.put(float.class, FloatMapper.FIRST); mappers.put(Double.class, DoubleMapper.FIRST); mappers.put(double.class, DoubleMapper.FIRST); mappers.put(Byte.class, ByteMapper.FIRST); mappers.put(byte.class, ByteMapper.FIRST); mappers.put(URL.class, URLMapper.FIRST); mappers.put(int.class, IntegerMapper.FIRST); mappers.put(Integer.class, IntegerMapper.FIRST); mappers.put(long.class, LongMapper.FIRST); mappers.put(Long.class, LongMapper.FIRST); mappers.put(Timestamp.class, TimestampMapper.FIRST); mappers.put(String.class, StringMapper.FIRST); } @Override public boolean accepts(Class type, StatementContext ctx) { return mappers.containsKey(type); } @Override public ResultSetMapper mapperFor(Class type, StatementContext ctx) { return mappers.get(type); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/ContainerBuilder.java
jdbi/src/main/java/org/skife/jdbi/v2/ContainerBuilder.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; public interface ContainerBuilder<ContainerType> { ContainerBuilder<ContainerType> add(Object it); ContainerType build(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/UnwrappedSingleValue.java
jdbi/src/main/java/org/skife/jdbi/v2/UnwrappedSingleValue.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; class UnwrappedSingleValue { }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/Call.java
jdbi/src/main/java/org/skife/jdbi/v2/Call.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.Argument; import org.skife.jdbi.v2.tweak.SQLLog; import org.skife.jdbi.v2.tweak.StatementBuilder; import org.skife.jdbi.v2.tweak.StatementCustomizer; import org.skife.jdbi.v2.tweak.StatementLocator; import org.skife.jdbi.v2.tweak.StatementRewriter; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Used for invoking stored procedures. */ public class Call extends SQLStatement<Call> { private final List<OutParamArgument> params = new ArrayList<OutParamArgument>(); Call(Handle handle, StatementLocator locator, StatementRewriter rewriter, StatementBuilder cache, String sql, ConcreteStatementContext ctx, SQLLog log, TimingCollector timingCollector, Collection<StatementCustomizer> customizers, Foreman foreman, ContainerFactoryRegistry containerFactoryRegistry ) { super(new Binding(), locator, rewriter, handle, cache, sql, ctx, log, timingCollector, customizers, foreman, containerFactoryRegistry); } /** * Register output parameter */ public Call registerOutParameter(int position, int sqlType) { return registerOutParameter(position, sqlType, null); } public Call registerOutParameter(int position, int sqlType, CallableStatementMapper mapper) { getParams().addPositional(position, new OutParamArgument(sqlType, mapper, null)); return this; } /** * Register output parameter */ public Call registerOutParameter(String name, int sqlType) { return registerOutParameter(name, sqlType, null); } public Call registerOutParameter(String name, int sqlType, CallableStatementMapper mapper) { getParams().addNamed(name, new OutParamArgument(sqlType, mapper, name)); return this; } /** * Invoke the callable statement */ public OutParameters invoke() { try { return this.internalExecute(new QueryResultMunger<OutParameters>() { @Override public OutParameters munge(Statement results) throws SQLException { OutParameters out = new OutParameters(); for ( OutParamArgument param : params ) { Object obj = param.map((CallableStatement)results); out.getMap().put(param.position, obj); if ( param.name != null ) { out.getMap().put(param.name, obj); } } return out; } }, null); } finally { cleanup(); } } private class OutParamArgument implements Argument { private final int sqlType; private final CallableStatementMapper mapper; private final String name; private int position ; public OutParamArgument(int sqlType, CallableStatementMapper mapper, String name) { this.sqlType = sqlType; this.mapper = mapper; this.name = name; params.add(this); } @Override public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException { ((CallableStatement)statement).registerOutParameter(position, sqlType); this.position = position ; } public Object map(CallableStatement stmt) throws SQLException { if ( mapper != null ) { return mapper.map(position, stmt); } switch ( sqlType ) { case Types.CLOB : case Types.VARCHAR : case Types.LONGNVARCHAR : case Types.LONGVARCHAR : case Types.NCLOB : case Types.NVARCHAR : return stmt.getString(position) ; case Types.BLOB : case Types.VARBINARY : return stmt.getBytes(position) ; case Types.SMALLINT : return stmt.getShort(position); case Types.INTEGER : return stmt.getInt(position); case Types.BIGINT : return stmt.getLong(position); case Types.TIMESTAMP : case Types.TIME : return stmt.getTimestamp(position) ; case Types.DATE : return stmt.getDate(position) ; case Types.FLOAT : return stmt.getFloat(position); case Types.DECIMAL : case Types.DOUBLE : return stmt.getDouble(position); default : return stmt.getObject(position); } } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/CachingStatementBuilder.java
jdbi/src/main/java/org/skife/jdbi/v2/CachingStatementBuilder.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import org.skife.jdbi.v2.tweak.StatementBuilder; /** * A StatementBuilder which decorates another StatementBuilder and caches * @deprecated This should be done in the JDBC driver, not here */ @Deprecated public class CachingStatementBuilder implements StatementBuilder { private Map<String, PreparedStatement> cache = new HashMap<String, PreparedStatement>(); private final StatementBuilder builder; /** * Create a new CachingStatementBuilder which decorates the one passed in. * * @param builder The StatementBuilder used to actual PreparedStatement creation */ public CachingStatementBuilder(StatementBuilder builder) { this.builder = builder; } /** * Return either a cached PreparedStatement or a new one which has just been added to the cache * @return A new, or cached, PreparedStatement */ @Override public PreparedStatement create(Connection conn, String sql, String columnNames[], StatementContext ctx) throws SQLException { if (cache.containsKey(sql)) { PreparedStatement cached = cache.get(sql); cached.clearParameters(); return cached; } PreparedStatement stmt = builder.create(conn, sql, columnNames, ctx); cache.put(sql, stmt); return stmt; } /** * NOOP, statements will be closed when the handle is closed */ @Override public void close(Connection conn, String sql, Statement stmt) throws SQLException { } /** * Iterate over all cached statements and ask the wrapped StatementBuilder to close * each one. */ @Override @SuppressWarnings("PMD.EmptyCatchBlock") public void close(Connection conn) { for (Map.Entry<String,PreparedStatement> statement : cache.entrySet()) { try { builder.close(conn, statement.getKey(), statement.getValue()); } catch (SQLException e) { // nothing we can do! } } } @Override public CallableStatement createCall(Connection conn, String sql, StatementContext ctx) throws SQLException { if (cache.containsKey(sql)) { CallableStatement cached = (CallableStatement) cache.get(sql); cached.clearParameters(); return cached; } CallableStatement stmt = builder.createCall(conn, sql, ctx); cache.put(sql, stmt); return stmt; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/CachingStatementBuilderFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/CachingStatementBuilderFactory.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.StatementBuilder; import org.skife.jdbi.v2.tweak.StatementBuilderFactory; import java.sql.Connection; /** * Provides StatementBuilder instances * which cache all prepared statements for a given handle instance. * @deprecated let the data source handle prepared statement caching */ public class CachingStatementBuilderFactory implements StatementBuilderFactory { /** * Return a new, or cached, prepared statement */ @Override public StatementBuilder createStatementBuilder(Connection conn) { return new CachingStatementBuilder(new DefaultStatementBuilder()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/DefaultStatementBuilder.java
jdbi/src/main/java/org/skife/jdbi/v2/DefaultStatementBuilder.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.StatementBuilder; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; /** * A StatementBuilder which will always create a new PreparedStatement */ public class DefaultStatementBuilder implements StatementBuilder { /** * Create a new DefaultStatementBuilder which will always create a new PreparedStatement from * the Connection * * @param conn Used to prepare the statement * @param sql Translated SQL statement * @param columnNames an array of column names indicating the columns * that should be returned from the inserted row or rows * @param ctx Unused * * @return a new PreparedStatement */ @Override public PreparedStatement create(Connection conn, String sql, String columnNames[], StatementContext ctx) throws SQLException { if (ctx.isReturningGeneratedKeys()) { if (columnNames != null && columnNames.length > 0) { return conn.prepareStatement(sql, columnNames); } else { return conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); } } else { return conn.prepareStatement(sql); } } /** * Called to close an individual prepared statement created from this builder. * In this case, it closes imemdiately * * @param sql the translated SQL which was prepared * @param stmt the statement * * @throws java.sql.SQLException if anything goes wrong closing the statement */ @Override public void close(Connection conn, String sql, Statement stmt) throws SQLException { if (stmt != null) { stmt.close(); } } /** * In this case, a NOOP */ @Override public void close(Connection conn) { } /** * Called each time a Callable statement needs to be created * * @param conn the JDBC Connection the statement is being created for * @param sql the translated SQL which should be prepared * @param ctx Statement context associated with the SQLStatement this is building for */ @Override public CallableStatement createCall(Connection conn, String sql, StatementContext ctx) throws SQLException { return conn.prepareCall(sql); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/BeanPropertyArguments.java
jdbi/src/main/java/org/skife/jdbi/v2/BeanPropertyArguments.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.exceptions.UnableToCreateStatementException; import org.skife.jdbi.v2.tweak.Argument; import org.skife.jdbi.v2.tweak.NamedArgumentFinder; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; /** * */ class BeanPropertyArguments implements NamedArgumentFinder { private final Object bean; private final StatementContext ctx; private final Foreman foreman; private BeanInfo info; BeanPropertyArguments(Object bean, StatementContext ctx, Foreman foreman) { this.bean = bean; this.ctx = ctx; this.foreman = foreman; try { this.info = Introspector.getBeanInfo(bean.getClass()); } catch (IntrospectionException e) { throw new UnableToCreateStatementException("Failed to introspect object which is supposed ot be used to" + " set named args for a statement via JavaBean properties", e, ctx); } } @Override public Argument find(String name) { for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) { if (descriptor.getName().equals(name)) { try { return foreman.waffle(descriptor.getReadMethod().getReturnType(), descriptor.getReadMethod().invoke(bean), ctx); } catch (IllegalAccessException e) { throw new UnableToCreateStatementException(String.format("Access excpetion invoking getter for " + "bean property [%s] on [%s]", name, bean), e, ctx); } catch (InvocationTargetException e) { throw new UnableToCreateStatementException(String.format("Invocation target exception invoking " + "getter for bean property [%s] on [%s]", name, bean), e, ctx); } } } return null; } @Override public String toString() { return new StringBuilder().append("{lazy bean proprty arguments \"").append(bean).append("\"").toString(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/ResultSetMapperFactory.java
jdbi/src/main/java/org/skife/jdbi/v2/ResultSetMapperFactory.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.ResultSetMapper; /** * Factory interface used to produce result set mappers. */ public interface ResultSetMapperFactory { /** * Can this factory provide a result set mapper which maps to the desired type * @param type the target type to map to * @return true if it can, false if it cannot */ boolean accepts(Class type, StatementContext ctx); /** * Supplies a result set mapper which will map result sets to type */ ResultSetMapper mapperFor(Class type, StatementContext ctx); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/TransactionStatus.java
jdbi/src/main/java/org/skife/jdbi/v2/TransactionStatus.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; /** * Allows rolling back a transaction in a TransactionCallback */ public interface TransactionStatus { /** * Force the transaction to be rolled back */ void setRollbackOnly(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/ResultIterator.java
jdbi/src/main/java/org/skife/jdbi/v2/ResultIterator.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import java.io.Closeable; import java.util.Iterator; /** * Represents a forward-only iterator over a result set, which will lazily iterate * the results. The underlying <code>ResultSet</code> can be closed by calling the * {@link org.skife.jdbi.v2.ResultIterator#close()} method. * <p> * The default implementation of <code>ResultIterator</code> will automatically close * the result set after the last element has been retrieved via <code>next()</code> and * <code>hasNext()</code> is called (which will return false). This allows for iteration * over the results with automagic resource cleanup. * <p> * The <code>remove()</code> operation is not supported in the default * version, and will raise an <code>UnsupportedOperationException</code> */ public interface ResultIterator<Type> extends Iterator<Type>, Closeable { @Override /** * Close the underlying result set. */ void close(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/Cleanables.java
jdbi/src/main/java/org/skife/jdbi/v2/Cleanables.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.StatementBuilder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Resource management for JDBI. Cleanables can be registered on a SQL statement and they get cleaned up when the * statement finishes or (in the case of a ResultIterator), the object representing the results is closed. * * Resources managed by JDBI are {@link ResultSet}, {@link Statement}, {@link Handle} and {@link StatementBuilder} for historical reasons. */ class Cleanables { private Cleanables() { throw new AssertionError("do not instantiate"); } static Cleanable forResultSet(final ResultSet rs) { return new ResultSetCleanable(rs); } static Cleanable forStatement(final Statement stmt) { return new StatementCleanable(stmt); } static Cleanable forHandle(final Handle handle, final TransactionState state) { return new HandleCleanable(handle, state); } private static final class ResultSetCleanable implements Cleanable { private final ResultSet rs; private ResultSetCleanable(ResultSet rs) { this.rs = rs; } @Override public void cleanup() throws SQLException { if (rs != null) { rs.close(); } } @Override public int hashCode() { return rs == null ? 0 : rs.hashCode(); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o == null || o.getClass() != this.getClass()) { return false; } ResultSetCleanable that = (ResultSetCleanable) o; if (this.rs == null) { return that.rs == null; } return this.rs.equals(that.rs); } } private static final class StatementCleanable implements Cleanable { private final Statement stmt; private StatementCleanable(Statement stmt) { this.stmt = stmt; } @Override public void cleanup() throws SQLException { if (stmt != null) { stmt.close(); } } @Override public int hashCode() { return stmt == null ? 0 : stmt.hashCode(); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o == null || o.getClass() != this.getClass()) { return false; } StatementCleanable that = (StatementCleanable) o; if (this.stmt == null) { return that.stmt == null; } return this.stmt.equals(that.stmt); } } private static final class HandleCleanable implements Cleanable { private final Handle handle; private final TransactionState state; private HandleCleanable(Handle handle, TransactionState state) { this.handle = handle; this.state = state; } @Override public void cleanup() throws SQLException { if (handle != null) { if (handle.isInTransaction()) { if (state == TransactionState.COMMIT) { handle.commit(); } else { handle.rollback(); } } handle.close(); } } @Override public int hashCode() { return handle == null ? 0 : handle.hashCode(); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o == null || o.getClass() != this.getClass()) { return false; } HandleCleanable that = (HandleCleanable) o; if (this.handle == null) { return that.handle == null; } return this.handle.equals(that.handle); } } /** * In the {@link SQLStatement} derived classes, the {@link Statement} is not managed directly but through the * {@link StatementBuilder}, which allows the {@link CachingStatementBuilder} to hook in and provide {@link java.sql.PreparedStatement} caching. */ static class StatementBuilderCleanable implements Cleanable { private final StatementBuilder statementBuilder; private final Connection conn; private final String sql; private final Statement stmt; StatementBuilderCleanable(final StatementBuilder statementBuilder, final Connection conn, final String sql, final Statement stmt) { this.statementBuilder = statementBuilder; this.conn = conn; this.sql = sql; this.stmt = stmt; } @Override public void cleanup() throws SQLException { if (statementBuilder != null) { statementBuilder.close(conn, sql, stmt); } } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/ByteArgument.java
jdbi/src/main/java/org/skife/jdbi/v2/ByteArgument.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.Argument; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * */ class ByteArgument implements Argument { private final Byte value; ByteArgument(Byte value) { this.value = value; } @Override public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException { if (value == null) { statement.setNull(position, Types.TINYINT); } else { statement.setByte(position, value); } } @Override public String toString() { return String.valueOf(value); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/BaseResultSetMapper.java
jdbi/src/main/java/org/skife/jdbi/v2/BaseResultSetMapper.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.util.Map; /** * Convenience class which allows definition of result set mappers which getAttribute the * row as a map instead of a result set. This can be useful. */ public abstract class BaseResultSetMapper<ResultType> implements ResultSetMapper<ResultType> { private static final DefaultMapper mapper = new DefaultMapper(); /** * Defers to mapInternal */ @Override public final ResultType map(int index, ResultSet r, StatementContext ctx) { return this.mapInternal(index, mapper.map(index, r, ctx)); } /** * Subclasses should implement this method in order to map the result * * @param index The row, starting at 0 * @param row The result of a {@link org.skife.jdbi.v2.tweak.ResultSetMapper#map} call * @return the value to pt into the results from a query */ protected abstract ResultType mapInternal(int index, Map<String, Object> row); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/URLArgument.java
jdbi/src/main/java/org/skife/jdbi/v2/URLArgument.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.Argument; import java.net.URL; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * */ class URLArgument implements Argument { private final URL value; URLArgument(URL value) { this.value = value; } @Override public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException { if (value != null) { statement.setURL(position, value); } else { statement.setNull(position, Types.DATALINK); } } @Override public String toString() { return String.valueOf(value); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/QueryResultMunger.java
jdbi/src/main/java/org/skife/jdbi/v2/QueryResultMunger.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import java.sql.SQLException; import java.sql.Statement; interface QueryResultMunger<Result> { Result munge(Statement results) throws SQLException; }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/BigDecimalArgument.java
jdbi/src/main/java/org/skife/jdbi/v2/BigDecimalArgument.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.Argument; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * */ class BigDecimalArgument implements Argument { private final BigDecimal value; BigDecimalArgument(BigDecimal value) { this.value = value; } @Override public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException { if (value != null) { statement.setBigDecimal(position, value); } else { statement.setNull(position, Types.NUMERIC); } } @Override public String toString() { return String.valueOf(value); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/InputStreamArgument.java
jdbi/src/main/java/org/skife/jdbi/v2/InputStreamArgument.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.Argument; import java.io.InputStream; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * */ class InputStreamArgument implements Argument { private final InputStream value; private final int length; private final boolean ascii; InputStreamArgument(InputStream value, int length, boolean ascii) { this.value = value; this.length = length; this.ascii = ascii; } @Override public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException { if (ascii) { if (value != null) { statement.setAsciiStream(position, value, length); } else { statement.setNull(position, Types.LONGVARCHAR); } } else { if (value != null) { statement.setBinaryStream(position, value, length); } else { statement.setNull(position, Types.LONGVARBINARY); } } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/JavaDateArgument.java
jdbi/src/main/java/org/skife/jdbi/v2/JavaDateArgument.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.Argument; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.util.Date; /** * Binds a @{link Date) argument to a prepared statement. A Java Date is really a timestamp because * it contains both a time and a date. If you need explicit binding for only time or only date, use * {@link SqlDateArgument} or {@link TimeArgument}. */ class JavaDateArgument implements Argument { private final Date value; JavaDateArgument(Date value) { this.value = value; } @Override public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException { if (value != null) { statement.setTimestamp(position, new Timestamp(value.getTime())); } else { statement.setNull(position, Types.TIMESTAMP); } } @Override public String toString() { return String.valueOf(value); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/jdbi/src/main/java/org/skife/jdbi/v2/RegisteredMapper.java
jdbi/src/main/java/org/skife/jdbi/v2/RegisteredMapper.java
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; class RegisteredMapper<T> implements ResultSetMapper<T> { private final Class<T> type; private final MappingRegistry registry; public RegisteredMapper(Class<T> type, MappingRegistry registry) { this.type = type; this.registry = registry; } @Override public T map(int index, ResultSet r, StatementContext ctx) throws SQLException { return (T) registry.mapperFor(type, ctx).map(index, r, ctx); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false