View Javadoc
1   /*
2    * Copyright (c) 2012-2023, jcabi.com
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met: 1) Redistributions of source code must retain the above
8    * copyright notice, this list of conditions and the following
9    * disclaimer. 2) Redistributions in binary form must reproduce the above
10   * copyright notice, this list of conditions and the following
11   * disclaimer in the documentation and/or other materials provided
12   * with the distribution. 3) Neither the name of the jcabi.com nor
13   * the names of its contributors may be used to endorse or promote
14   * products derived from this software without specific prior written
15   * permission.
16   *
17   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18   * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
19   * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20   * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21   * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22   * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25   * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28   * OF THE POSSIBILITY OF SUCH DAMAGE.
29   */
30  package com.jcabi.jdbc;
31  
32  import com.jolbox.bonecp.BoneCPDataSource;
33  import java.sql.CallableStatement;
34  import java.sql.PreparedStatement;
35  import java.sql.SQLException;
36  import java.sql.Types;
37  import java.util.Date;
38  import java.util.UUID;
39  import javax.sql.DataSource;
40  import org.apache.commons.lang3.StringUtils;
41  import org.hamcrest.MatcherAssert;
42  import org.hamcrest.Matchers;
43  import org.junit.jupiter.api.Test;
44  import org.testcontainers.containers.JdbcDatabaseContainer;
45  import org.testcontainers.containers.PostgreSQLContainer;
46  import org.testcontainers.junit.jupiter.Container;
47  import org.testcontainers.junit.jupiter.Testcontainers;
48  
49  /**
50   * Integration case for {@link JdbcSession}.
51   * @since 0.1
52   */
53  @Testcontainers(disabledWithoutDocker = true)
54  final class JdbcSessionITCase {
55  
56      /**
57       * The database container.
58       */
59      @Container
60      private final JdbcDatabaseContainer<?> container =
61          new PostgreSQLContainer<>("postgres:9.6.12");
62  
63      /**
64       * JdbcSession can do PostgreSQL manipulations.
65       *
66       * @throws Exception If there is some problem inside
67       */
68      @Test
69      void manipulatesPostgresql() throws Exception {
70          final DataSource source = this.source();
71          new JdbcSession(source)
72              .autocommit(false)
73              .sql("CREATE TABLE IF NOT EXISTS foo (name VARCHAR(50))")
74              .execute()
75              .sql("INSERT INTO foo (name) VALUES (?)")
76              .set("Jeff Lebowski")
77              .execute()
78              .commit();
79      }
80  
81      /**
82       * JdbcSession can manipulate UUID types.
83       *
84       * @throws Exception If there is some problem inside
85       */
86      @Test
87      void manipulatesUuidTypes() throws Exception {
88          final DataSource source = this.source();
89          final UUID uuid = UUID.randomUUID();
90          new JdbcSession(source)
91              .autocommit(false)
92              .sql("CREATE TABLE uuidtb (id UUID)")
93              .execute()
94              .sql("INSERT INTO uuidtb (id) VALUES (?)")
95              .set(uuid)
96              .execute()
97              .commit();
98          final UUID id = new JdbcSession(source)
99              .sql("SELECT id FROM uuidtb")
100             .select(new SingleOutcome<>(UUID.class));
101         MatcherAssert.assertThat(id, Matchers.equalTo(uuid));
102     }
103 
104     /**
105      * JdbcSession can change transaction isolation level.
106      *
107      * @throws Exception If there is some problem inside
108      */
109     @Test
110     void changesTransactionIsolationLevel() throws Exception {
111         final DataSource source = this.source();
112         new JdbcSession(source).sql("VACUUM").execute();
113     }
114 
115     /**
116      * JdbcSession can run a function (stored procedure) with
117      * output parameters.
118      *
119      * @throws Exception If something goes wrong
120      */
121     @Test
122     void callsFunctionWithOutParam() throws Exception {
123         final DataSource source = this.source();
124         new JdbcSession(source).autocommit(false).sql(
125             "CREATE TABLE IF NOT EXISTS users (name VARCHAR(50))"
126         ).execute().sql("INSERT INTO users (name) VALUES (?)")
127         .set("Jeff Charles").execute().sql(
128             StringUtils.join(
129                 "CREATE OR REPLACE FUNCTION fetchUser(username OUT text,",
130                 " day OUT date)",
131                 " AS $$ BEGIN SELECT name, CURRENT_DATE INTO username, day",
132                 " FROM users; END; $$ LANGUAGE plpgsql;"
133             )
134         ).execute().commit();
135         final Object[] result = new JdbcSession(source)
136             .sql("{call fetchUser(?, ?)}")
137             .prepare(
138                 new Preparation() {
139                     @Override
140                     public void
141                         prepare(final PreparedStatement stmt)
142                         throws SQLException {
143                             final CallableStatement cstmt =
144                                 (CallableStatement) stmt;
145                             cstmt.registerOutParameter(1, Types.VARCHAR);
146                             cstmt.registerOutParameter(2, Types.DATE);
147                     }
148                 }
149              )
150             .call(new StoredProcedureOutcome<Object[]>(1, 2));
151         MatcherAssert.assertThat(result.length, Matchers.is(2));
152         MatcherAssert.assertThat(
153             result[0].toString(),
154             Matchers.containsString("Charles")
155         );
156         MatcherAssert.assertThat(
157             (Date) result[1],
158             Matchers.notNullValue()
159         );
160     }
161 
162     /**
163      * JdbcSession can run a function (stored procedure) with
164      * input and output parameters.
165      *
166      * @throws Exception If something goes wrong
167      */
168     @Test
169     void callsFunctionWithInOutParam() throws Exception {
170         final DataSource source = this.source();
171         new JdbcSession(source).autocommit(false).sql(
172             "CREATE TABLE IF NOT EXISTS usersids (id INTEGER, name VARCHAR(50))"
173         ).execute().sql("INSERT INTO usersids (id, name) VALUES (?, ?)")
174         .set(1).set("Marco Polo").execute().sql(
175             StringUtils.join(
176                 "CREATE OR REPLACE FUNCTION fetchUserById(uid IN INTEGER,",
177                 " usrnm OUT text) AS $$ BEGIN",
178                 " SELECT name INTO usrnm FROM usersids WHERE id=uid;",
179                 " END; $$ LANGUAGE plpgsql;"
180             )
181         ).execute().commit();
182         final Object[] result = new JdbcSession(source)
183             .sql("{call fetchUserById(?, ?)}")
184             .set(1)
185             .prepare(
186                 new Preparation() {
187                     @Override
188                     public void
189                         prepare(final PreparedStatement stmt)
190                         throws SQLException {
191                             ((CallableStatement) stmt)
192                                 .registerOutParameter(2, Types.VARCHAR);
193                     }
194                 }
195              )
196             .call(new StoredProcedureOutcome<Object[]>(2));
197         MatcherAssert.assertThat(result.length, Matchers.is(1));
198         MatcherAssert.assertThat(
199             result[0].toString(),
200             Matchers.containsString("Polo")
201         );
202     }
203 
204     /**
205      * Get data source.
206      *
207      * @return Source
208      */
209     private DataSource source() {
210         final BoneCPDataSource src = new BoneCPDataSource();
211         src.setDriverClass(this.container.getDriverClassName());
212         src.setJdbcUrl(this.container.getJdbcUrl());
213         src.setUser(this.container.getUsername());
214         src.setPassword(this.container.getPassword());
215         src.setPartitionCount(3);
216         src.setMaxConnectionsPerPartition(1);
217         src.setMinConnectionsPerPartition(1);
218         src.setAcquireIncrement(1);
219         src.setDisableConnectionTracking(true);
220         return src;
221     }
222 
223 }