|
| 1 | +package org.h2.test.synth; |
| 2 | + |
| 3 | +import java.sql.Connection; |
| 4 | +import java.sql.PreparedStatement; |
| 5 | +import java.sql.ResultSet; |
| 6 | +import java.sql.SQLException; |
| 7 | + |
| 8 | +import org.h2.test.TestBase; |
| 9 | + |
| 10 | +/** |
| 11 | + * Test for check compatibility with posgresql function string_agg() |
| 12 | + * |
| 13 | + * */ |
| 14 | +public class TestStringAggCompatibility extends TestBase { |
| 15 | + |
| 16 | + public static final String STRING_AGG_DB = "stringAgg"; |
| 17 | + |
| 18 | + private Connection conn; |
| 19 | + |
| 20 | + public static void main(String[] args) throws Exception { |
| 21 | + TestBase.createCaller().init().test(); |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public void test() throws Exception { |
| 26 | + deleteDb(STRING_AGG_DB); |
| 27 | + |
| 28 | + conn = getConnection(STRING_AGG_DB); |
| 29 | + |
| 30 | + prepareDb(); |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | + testWhenOrderByMissing(); |
| 37 | + testWithOrderBy(); |
| 38 | + } |
| 39 | + |
| 40 | + private void testWithOrderBy() throws SQLException { |
| 41 | + ResultSet result = query("select string_agg(b, ', ' order by b desc) from stringAgg group by a; "); |
| 42 | + |
| 43 | + assertTrue(result.next()); |
| 44 | + assertEquals("3, 2, 1", result.getString(1)); |
| 45 | + } |
| 46 | + |
| 47 | + private void testWhenOrderByMissing() throws SQLException { |
| 48 | + ResultSet result = query("select string_agg(b, ', ') from stringAgg group by a; "); |
| 49 | + |
| 50 | + assertTrue(result.next()); |
| 51 | + assertEquals("1, 2, 3", result.getString(1)); |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | + private ResultSet query(String q) throws SQLException { |
| 56 | + PreparedStatement st = conn.prepareStatement(q); |
| 57 | + |
| 58 | + st.execute(); |
| 59 | + |
| 60 | + return st.getResultSet(); |
| 61 | + } |
| 62 | + |
| 63 | + private void prepareDb() throws SQLException { |
| 64 | + exec("create table stringAgg(\n" + |
| 65 | + " a int not null,\n" + |
| 66 | + " b varchar(50) not null\n" + |
| 67 | + ");"); |
| 68 | + |
| 69 | + exec("insert into stringAgg values(1, '1')"); |
| 70 | + exec("insert into stringAgg values(1, '2')"); |
| 71 | + exec("insert into stringAgg values(1, '3')"); |
| 72 | + |
| 73 | + } |
| 74 | + |
| 75 | + private void exec(String sql) throws SQLException { |
| 76 | + conn.prepareStatement(sql).execute(); |
| 77 | + } |
| 78 | +} |
0 commit comments