Java Code Examples for io.vertx.sqlclient.RowIterator

The following examples show how to use io.vertx.sqlclient.RowIterator. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void testMappedQuery(TestContext ctx) {
  Async async = ctx.async();
  PgConnection.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> {
    conn.prepare("SELECT $1 :: INT4", ctx.asyncAssertSuccess(ps -> {
      ps.query()
        .mapping(row -> "" + row.getInteger(0))
        .execute(Tuple.of(1), ctx.asyncAssertSuccess(results -> {
        ctx.assertEquals(1, results.size());
        RowSet<String> rows = results.value();
        ctx.assertEquals(rows.size(), 1);
        RowIterator<String> it = rows.iterator();
        ctx.assertEquals("1", it.next());
        ps.close(ctx.asyncAssertSuccess(result -> {
          async.complete();
        }));
      }));
    }));
  }));
}
 
Example 2
Source Project: vertx-sql-client   Source File: JavaEnumTest.java    License: Apache License 2.0 6 votes vote down vote up
private void testJavaEnumToArrayParam(TestContext ctx, Object expected, String sqlType) {
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn
      .preparedQuery("SELECT $1 :: " + sqlType + " \"c\"")
      .execute(Tuple.of(new Mood[]{Mood.happy}), ctx.asyncAssertSuccess(v -> {
        RowIterator<Row> it = v.iterator();
        ctx.assertTrue(it.hasNext());
        Row row = it.next();
        Object value = row.getValue(0);
        ctx.assertTrue(value instanceof Object[]);
        Object[] array = (Object[]) value;
        ctx.assertEquals(1, array.length);
        ctx.assertEquals(expected, array[0]);
      }));
  }));
}
 
Example 3
Source Project: vertx-sql-client   Source File: QueryVariationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRenamedColumns(TestContext ctx) {
  connect(ctx.asyncAssertSuccess(conn -> {
    conn.query("SELECT id AS THE_ID," +
                 "message AS \"the message\"" +
        "FROM immutable " +
        "WHERE id = 10").execute(
        ctx.asyncAssertSuccess(rowSet -> {
      ctx.assertEquals(1, rowSet.size());
      ctx.assertEquals(Arrays.asList("THE_ID", "the message"), rowSet.columnsNames());
      RowIterator<Row> rows = rowSet.iterator();
      ctx.assertTrue(rows.hasNext());
      Row row = rows.next();
      ctx.assertEquals(10, row.getInteger(0));
      ctx.assertEquals(10, row.getInteger("THE_ID"));
      ctx.assertEquals("Computers make very fast, very accurate mistakes.", row.getString(1));
      ctx.assertEquals("Computers make very fast, very accurate mistakes.", row.getString("the message"));
      ctx.assertFalse(rows.hasNext());
      conn.close();
    }));
  }));
}
 
Example 4
Source Project: vertx-sql-client   Source File: QueryVariationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSubquery(TestContext ctx) {
  connect(ctx.asyncAssertSuccess(conn -> {
    conn.query("SELECT id,message FROM immutable " +
        "WHERE message IN " +
        "(SELECT message FROM immutable WHERE id = '4' OR id = '7')").execute(
        ctx.asyncAssertSuccess(rowSet -> {
      ctx.assertEquals(2, rowSet.size());
      ctx.assertEquals(Arrays.asList("ID", "MESSAGE"), rowSet.columnsNames());
      RowIterator<Row> rows = rowSet.iterator();
      ctx.assertTrue(rows.hasNext());
      Row row = rows.next();
      ctx.assertEquals(4, row.getInteger(0));
      ctx.assertEquals("A bad random number generator: 1, 1, 1, 1, 1, 4.33e+67, 1, 1, 1", row.getString(1));
      ctx.assertTrue(rows.hasNext());
      row = rows.next();
      ctx.assertEquals(7, row.getInteger(0));
      ctx.assertEquals("Any program that runs right is obsolete.", row.getString(1));
      conn.close();
    }));
  }));
}
 
Example 5
Source Project: vertx-sql-client   Source File: QueryVariationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSubqueryPrepared(TestContext ctx) {
  connect(ctx.asyncAssertSuccess(conn -> {
    conn.preparedQuery("SELECT id,message FROM immutable " +
        "WHERE message IN " +
        "(SELECT message FROM immutable WHERE id = ? OR id = ?)").execute(
        Tuple.of(4, 7),
        ctx.asyncAssertSuccess(rowSet -> {
      ctx.assertEquals(2, rowSet.size());
      ctx.assertEquals(Arrays.asList("ID", "MESSAGE"), rowSet.columnsNames());
      RowIterator<Row> rows = rowSet.iterator();
      ctx.assertTrue(rows.hasNext());
      Row row = rows.next();
      ctx.assertEquals(4, row.getInteger(0));
      ctx.assertEquals("A bad random number generator: 1, 1, 1, 1, 1, 4.33e+67, 1, 1, 1", row.getString(1));
      ctx.assertTrue(rows.hasNext());
      row = rows.next();
      ctx.assertEquals(7, row.getInteger(0));
      ctx.assertEquals("Any program that runs right is obsolete.", row.getString(1));
      conn.close();
    }));
  }));
}
 
Example 6
Source Project: vertx-sql-client   Source File: QueryVariationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLikeQuery(TestContext ctx) {
  connect(ctx.asyncAssertSuccess(conn -> {
    conn.query("SELECT id,message FROM immutable " +
        "WHERE message LIKE '%computer%'").execute(
        ctx.asyncAssertSuccess(rowSet -> {
      ctx.assertEquals(2, rowSet.size());
      ctx.assertEquals(Arrays.asList("ID", "MESSAGE"), rowSet.columnsNames());
      RowIterator<Row> rows = rowSet.iterator();
      ctx.assertTrue(rows.hasNext());
      Row row = rows.next();
      ctx.assertEquals(2, row.getInteger(0));
      ctx.assertEquals("A computer scientist is someone who fixes things that aren't broken.", row.getString(1));
      ctx.assertTrue(rows.hasNext());
      row = rows.next();
      ctx.assertEquals(5, row.getInteger(0));
      ctx.assertEquals("A computer program does what you tell it to do, not what you want it to do.", row.getString(1));
      conn.close();
    }));
  }));
}
 
Example 7
Source Project: raml-module-builder   Source File: PgUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static <T, C> C collection(Class<T> clazz, Class<C> collectionClazz, RowSet<Row> resultSet, int offset, int limit)
    throws ReflectiveOperationException, IOException {

  int totalRecords = 0;
  int resultSize = resultSet.size();
  List<T> recordList = new ArrayList<>(resultSize);
  RowIterator<Row> iterator = resultSet.iterator();
  while (iterator.hasNext()) {
    Row row = iterator.next();
    String jsonb = row.getValue(JSON_COLUMN).toString();
    recordList.add(OBJECT_MAPPER.readValue(jsonb, clazz));
    totalRecords = row.getInteger(PostgresClient.COUNT_FIELD);
  }
  totalRecords = PostgresClient.getTotalRecords(resultSize, totalRecords, offset, limit);
  return collection(collectionClazz, recordList, totalRecords);
}
 
Example 8
public CompletionStage<Long> updateReturning(String sql, Tuple parameters) {
	return preparedQuery( sql, parameters )
			.thenApply( rows -> {
				RowIterator<Row> iterator = rows.iterator();
				return iterator.hasNext() ?
						iterator.next().getLong(0) :
						rows.property(getMySqlLastInsertedId());
			} );
}
 
Example 9
Source Project: vertx-sql-client   Source File: JavaEnumTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testJavaEnumToColumn(TestContext ctx, String value, String sqlType) {
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn
      .preparedQuery("SELECT * FROM (VALUES (" + value + " :: " + sqlType + ")) AS t (c)")
      .execute(ctx.asyncAssertSuccess(v -> {
        RowIterator<Row> it = v.iterator();
        ctx.assertTrue(it.hasNext());
        Row row = it.next();
        ctx.assertEquals(Mood.unhappy, row.get(Mood.class, 0));
      }));
  }));
}
 
Example 10
Source Project: vertx-sql-client   Source File: JavaEnumTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testJavaEnumToArrayColumn(TestContext ctx, String value, String sqlType) {
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn
      .preparedQuery("SELECT * FROM (VALUES (" + value + " :: " + sqlType + ")) AS t (c)")
      .execute(ctx.asyncAssertSuccess(v -> {
        RowIterator<Row> it = v.iterator();
        ctx.assertTrue(it.hasNext());
        Row row = it.next();
        Mood[] result = row.get(Mood[].class, "c");
        ctx.assertEquals(1, result.length);
        ctx.assertEquals(Mood.unhappy, result[0]);
      }));
  }));
}
 
Example 11
Source Project: vertx-sql-client   Source File: JavaEnumTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testJavaEnumToParam(TestContext ctx, Object expected, String sqlType) {
  PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn
      .preparedQuery("SELECT $1 :: " + sqlType + " \"c\"")
      .execute(Tuple.of(Mood.happy), ctx.asyncAssertSuccess(v -> {
        RowIterator<Row> it = v.iterator();
        ctx.assertTrue(it.hasNext());
        Row row = it.next();
        ctx.assertEquals(expected, row.getValue(0));
      }));
  }));
}
 
Example 12
Source Project: vertx-sql-client   Source File: QueryVariationsTest.java    License: Apache License 2.0 5 votes vote down vote up
private int assertSequenceResult(TestContext ctx, RowSet<Row> rowSet, Consumer<Integer> validation) {
  ctx.assertEquals(1, rowSet.size());
  RowIterator<Row> rows = rowSet.iterator();
      ctx.assertTrue(rows.hasNext());
      Row row = rows.next();
      ctx.assertNotNull(row);
      int seqVal = row.getInteger(0);
      validation.accept(seqVal);
      return seqVal;
}
 
Example 13
Source Project: vertx-sql-client   Source File: RowSetImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RowIterator<R> iterator() {
  Iterator<R> i = list.iterator();
  return new RowIterator<R>() {
    @Override
    public boolean hasNext() {
      return i.hasNext();
    }
    @Override
    public R next() {
      return i.next();
    }
  };
}
 
Example 14
Source Project: vertx-sql-client   Source File: NumericDataTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBinaryEncodeCastShortToDecimal(TestContext ctx) {
  testBinaryDecode(ctx, "SELECT * FROM basicdatatype WHERE id = 1 AND test_decimal = ?", Tuple.of((short) 12345), result -> {
    ctx.assertEquals(1, result.size());
    RowIterator<Row> iterator = result.iterator();
    Row row = iterator.next();
    ctx.assertEquals(1, row.getInteger("id"));
    ctx.assertEquals(Numeric.create(12345), row.getValue("test_decimal"));
  });
}
 
Example 15
Source Project: vertx-sql-client   Source File: NumericDataTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBinaryEncodeCastLongToShort(TestContext ctx) {
  testBinaryDecode(ctx, "SELECT * FROM basicdatatype WHERE id = 1 AND test_int_2 = ?", Tuple.of(32767L), result -> {
    ctx.assertEquals(1, result.size());
    RowIterator<Row> iterator = result.iterator();
    Row row = iterator.next();
    ctx.assertEquals(1, row.getInteger("id"));
    ctx.assertEquals((short) 32767, row.getValue("test_int_2"));
  });
}
 
Example 16
Source Project: vertx-sql-client   Source File: DateTimeBinaryCodecTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeCastStringToDate(TestContext ctx) {
  testBinaryDecode(ctx, "SELECT * FROM basicdatatype WHERE id = 1 AND `test_date` = ?", Tuple.of("2019-01-01"), result -> {
    ctx.assertEquals(1, result.size());
    RowIterator<Row> iterator = result.iterator();
    Row row = iterator.next();
    ctx.assertEquals(1, row.getInteger("id"));
    ctx.assertEquals(LocalDate.of(2019, 1, 1), row.getLocalDate("test_date"));
  });
}
 
Example 17
Source Project: vertx-sql-client   Source File: DateTimeBinaryCodecTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeCastStringToTime(TestContext ctx) {
  testBinaryDecode(ctx, "SELECT * FROM basicdatatype WHERE id = 1 AND `test_time` = ?", Tuple.of("18:45:02"), result -> {
    ctx.assertEquals(1, result.size());
    RowIterator<Row> iterator = result.iterator();
    Row row = iterator.next();
    ctx.assertEquals(1, row.getInteger("id"));
    Duration expected = Duration.ZERO.plusHours(18).plusMinutes(45).plusSeconds(2);
    ctx.assertEquals(expected, row.getValue("test_time"));
  });
}
 
Example 18
Source Project: vertx-sql-client   Source File: MySQLCollationTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testText(TestContext ctx, String prepareDataSql) {
  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.query(prepareDataSql).execute(ctx.asyncAssertSuccess(res0 -> {
      conn.query("SELECT id, city_name FROM chinese_city").execute(ctx.asyncAssertSuccess(res1 -> {
        ctx.assertEquals(6, res1.size());
        RowIterator<Row> iterator = res1.iterator();
        Row row1 = iterator.next();
        ctx.assertEquals(1, row1.getInteger("id"));
        ctx.assertEquals("\u5317\u4EAC", row1.getString("city_name"));
        Row row2 = iterator.next();
        ctx.assertEquals(2, row2.getInteger("id"));
        ctx.assertEquals("\u4E0A\u6D77", row2.getString("city_name"));
        Row row3 = iterator.next();
        ctx.assertEquals(3, row3.getInteger("id"));
        ctx.assertEquals("\u5E7F\u5DDE", row3.getString("city_name"));
        Row row4 = iterator.next();
        ctx.assertEquals(4, row4.getInteger("id"));
        ctx.assertEquals("\u6DF1\u5733", row4.getString("city_name"));
        Row row5 = iterator.next();
        ctx.assertEquals(5, row5.getInteger("id"));
        ctx.assertEquals("\u6B66\u6C49", row5.getString("city_name"));
        Row row6 = iterator.next();
        ctx.assertEquals(6, row6.getInteger("id"));
        ctx.assertEquals("\u6210\u90FD", row6.getString("city_name"));
        conn.close();
      }));
    }));
  }));
}
 
Example 19
Source Project: raml-module-builder   Source File: PostgresClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param resultsHelper
 */
<T> void deserializeResults(ResultsHelper<T> resultsHelper) {

  if (resultsHelper.resultSet == null) {
    return;
  }
  boolean isAuditFlavored = isAuditFlavored(resultsHelper.clazz);

  Map<String, Method> externalColumnSetters = new HashMap<>();
  collectExternalColumnSetters(
      resultsHelper.resultSet.columnsNames(),
      resultsHelper.clazz,
      isAuditFlavored,
      externalColumnSetters
  );
  RowIterator<Row> iterator = resultsHelper.resultSet.iterator();
  while (iterator.hasNext()) {
    Row row = iterator.next();
    try {
      T objRow = (T) deserializeRow(resultsHelper, externalColumnSetters, isAuditFlavored, row);
      if (!resultsHelper.facet) {
        resultsHelper.list.add(objRow);
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      resultsHelper.list.add(null);
    }
  }
}
 
Example 20
Source Project: raml-module-builder   Source File: PostgresClient.java    License: Apache License 2.0 5 votes vote down vote up
static void queryAndAnalyze(PgConnection conn, String sql, String statMethod,
  Handler<AsyncResult<RowSet<Row>>> replyHandler) {

  long start = System.nanoTime();
  conn.query(sql).execute(res -> {
    long queryTime = (System.nanoTime() - start);
    StatsTracker.addStatElement(STATS_KEY + statMethod, queryTime);
    if (res.failed()) {
      log.error("queryAndAnalyze: " + res.cause().getMessage() + " - "
        + sql, res.cause());
      replyHandler.handle(Future.failedFuture(res.cause()));
      return;
    }
    if (queryTime >= explainQueryThreshold * 1000000) {
      final String explainQuery = "EXPLAIN ANALYZE " + sql;
      conn.query(explainQuery).execute(explain -> {
        replyHandler.handle(res); // not before, so we have conn if it gets closed
        if (explain.failed()) {
          log.warn(explainQuery + ": ", explain.cause().getMessage(), explain.cause());
          return;
        }
        StringBuilder e = new StringBuilder(explainQuery);
        RowIterator<Row> iterator = explain.result().iterator();
        while (iterator.hasNext()) {
          Row row = iterator.next();
          e.append('\n').append(row.getString(0));
        }
        log.warn(e.toString());
      });
    } else {
      replyHandler.handle(res);
    }
  });
}
 
Example 21
Source Project: raml-module-builder   Source File: OutStream.java    License: Apache License 2.0 5 votes vote down vote up
public OutStream(RowSet<Row> result) {
  JsonArray ar = new JsonArray();
  RowIterator<Row> it = result.iterator();
  while (it.hasNext()) {
    Row row = it.next();
    JsonObject o = new JsonObject();
    for (int i = 0; i < row.size(); i++) {
      o.put(row.getColumnName(i), row.getValue(i));
    }
    ar.add(o);
  }
  data = ar.encode();
}
 
Example 22
Source Project: raml-module-builder   Source File: PostgresClientIT.java    License: Apache License 2.0 5 votes vote down vote up
private String intsAsString(RowSet<Row> resultSet) {
  StringBuilder s = new StringBuilder();
  RowIterator<Row> iterator = resultSet.iterator();
  while (iterator.hasNext()) {
    if (s.length() > 0) {
      s.append(", ");
    }
    s.append(iterator.next().getInteger(0));
  }
  return s.toString();
}
 
Example 23
public boolean singleRestRequest(HTTPRequestReader request) { 

		final ResultObject target = DBRestInFlight.headObject();

		if (null!=target && -1==target.getStatus()) {
			target.setConnectionId(request.getConnectionId());
			target.setSequenceId(request.getSequenceCode());
			assert(target.getStatus()==-1);//waiting for work
			target.setStatus(-2);//out for work	
			target.setGroupSize(0);//do not put in a list so mark as 0.
		
			pm.pool().preparedQuery("SELECT * FROM world WHERE id=$1", Tuple.of(randomValue()), r -> {
					if (r.succeeded()) {
						
						RowIterator<Row> resultSet = r.result().iterator();
				        Row row = resultSet.next();			        
				        
				        target.setId((Integer)row.getInteger(0));
				        target.setResult((Integer)row.getInteger(1));					
						target.setStatus(200);
						
					} else {
						System.out.println("fail: "+r.cause().getLocalizedMessage());
						target.setStatus(500);
					}				
				});
	   			
			DBRestInFlight.moveHeadForward(); //always move to ensure this can be read.
			return true;
		} else {
			return false;//can not pick up new work now			
		}
	}
 
Example 24
Source Project: vertx-sql-client   Source File: MySQLQueryTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testLocalInfileRequest(TestContext ctx) {
  FileSystem fileSystem = vertx.fileSystem();
  Buffer fileData = Buffer.buffer();
  for (int i = 0; i < 10000; i++) {
    fileData.appendString("Fluffy,Harold,cat,f,1993-02-04,NULL")
      .appendString("\n")
      .appendString("Bowser,Diane,dog,m,1979-08-31,1995-07-29")
      .appendString("\n")
      .appendString("Whistler,Gwen,bird,NULL,1997-12-09,NULL")
      .appendString("\n");
  }
  fileSystem.createTempFile(null, null, ctx.asyncAssertSuccess(filename -> {
    fileSystem.writeFile(filename, fileData, ctx.asyncAssertSuccess(write -> {
      MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
        conn.query("TRUNCATE TABLE localinfile").execute(ctx.asyncAssertSuccess(cleanup -> {
          conn.query("LOAD DATA LOCAL INFILE '" + filename + "' INTO TABLE localinfile FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n';").execute(ctx.asyncAssertSuccess(v -> {
            conn.query("SELECT * FROM localinfile").execute(ctx.asyncAssertSuccess(rowSet -> {
              ctx.assertEquals(30000, rowSet.size());
              RowIterator<Row> iterator = rowSet.iterator();
              for (int i = 0; i < 10000; i++) {
                Row row1 = iterator.next();
                ctx.assertEquals("Fluffy", row1.getValue(0));
                ctx.assertEquals("Harold", row1.getValue(1));
                ctx.assertEquals("cat", row1.getValue(2));
                ctx.assertEquals("f", row1.getValue(3));
                ctx.assertEquals(LocalDate.of(1993, 2, 4), row1.getValue(4));
                ctx.assertEquals(null, row1.getValue(5));
                Row row2 = iterator.next();
                ctx.assertEquals("Bowser", row2.getValue(0));
                ctx.assertEquals("Diane", row2.getValue(1));
                ctx.assertEquals("dog", row2.getValue(2));
                ctx.assertEquals("m", row2.getValue(3));
                ctx.assertEquals(LocalDate.of(1979, 8, 31), row2.getValue(4));
                ctx.assertEquals(LocalDate.of(1995, 7, 29), row2.getValue(5));
                Row row3 = iterator.next();
                ctx.assertEquals("Whistler", row3.getValue(0));
                ctx.assertEquals("Gwen", row3.getValue(1));
                ctx.assertEquals("bird", row3.getValue(2));
                ctx.assertEquals(null, row3.getValue(3));
                ctx.assertEquals(LocalDate.of(1997, 12, 9), row3.getValue(4));
                ctx.assertEquals(null, row3.getValue(5));
              }
              conn.close();
            }));
          }));
        }));
      }));
    }));
  }));
}
 
Example 25
Source Project: vertx-sql-client   Source File: MySQLQueryTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testLocalInfileRequestInPackets(TestContext ctx) {
  FileSystem fileSystem = vertx.fileSystem();
  Buffer fileData = Buffer.buffer();
  for (int i = 0; i < 200000; i++) {
    fileData.appendString("Fluffy,Harold,cat,f,1993-02-04,NULL")
      .appendString("\n")
      .appendString("Bowser,Diane,dog,m,1979-08-31,1995-07-29")
      .appendString("\n")
      .appendString("Whistler,Gwen,bird,NULL,1997-12-09,NULL")
      .appendString("\n");
  }
  ctx.assertTrue(fileData.length() > 0xFFFFFF);
  fileSystem.createTempFile(null, null, ctx.asyncAssertSuccess(filename -> {
    fileSystem.writeFile(filename, fileData, ctx.asyncAssertSuccess(write -> {
      MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
        conn.query("TRUNCATE TABLE localinfile").execute(ctx.asyncAssertSuccess(cleanup -> {
          conn.query("LOAD DATA LOCAL INFILE '" + filename + "' INTO TABLE localinfile FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n';").execute(ctx.asyncAssertSuccess(v -> {
            conn.query("SELECT * FROM localinfile").execute(ctx.asyncAssertSuccess(rowSet -> {
              ctx.assertEquals(600000, rowSet.size());
              RowIterator<Row> iterator = rowSet.iterator();
              for (int i = 0; i < 200000; i++) {
                Row row1 = iterator.next();
                ctx.assertEquals("Fluffy", row1.getValue(0));
                ctx.assertEquals("Harold", row1.getValue(1));
                ctx.assertEquals("cat", row1.getValue(2));
                ctx.assertEquals("f", row1.getValue(3));
                ctx.assertEquals(LocalDate.of(1993, 2, 4), row1.getValue(4));
                ctx.assertEquals(null, row1.getValue(5));
                Row row2 = iterator.next();
                ctx.assertEquals("Bowser", row2.getValue(0));
                ctx.assertEquals("Diane", row2.getValue(1));
                ctx.assertEquals("dog", row2.getValue(2));
                ctx.assertEquals("m", row2.getValue(3));
                ctx.assertEquals(LocalDate.of(1979, 8, 31), row2.getValue(4));
                ctx.assertEquals(LocalDate.of(1995, 7, 29), row2.getValue(5));
                Row row3 = iterator.next();
                ctx.assertEquals("Whistler", row3.getValue(0));
                ctx.assertEquals("Gwen", row3.getValue(1));
                ctx.assertEquals("bird", row3.getValue(2));
                ctx.assertEquals(null, row3.getValue(3));
                ctx.assertEquals(LocalDate.of(1997, 12, 9), row3.getValue(4));
                ctx.assertEquals(null, row3.getValue(5));
              }
              conn.close();
            }));
          }));
        }));
      }));
    }));
  }));
}
 
Example 26
Source Project: vertx-sql-client   Source File: MySQLStoredProgramsTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testMultiResult(TestContext ctx) {
  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    conn.query("CREATE TEMPORARY TABLE ins ( id INT );").execute(ctx.asyncAssertSuccess(createTable -> {
      conn.query("DROP PROCEDURE IF EXISTS multi;").execute(ctx.asyncAssertSuccess(cleanProcedure -> {
        conn.query("CREATE PROCEDURE multi()\n" +
          "BEGIN\n" +
          "    SELECT 123;\n" +
          "    SELECT 456;\n" +
          "    INSERT INTO ins VALUES (1);\n" +
          "    INSERT INTO ins VALUES (2);\n" +
          "END;").execute(ctx.asyncAssertSuccess(createProcedure -> {
          conn.query("CALL multi();").execute(ctx.asyncAssertSuccess(result -> {
            // example borrowed from https://dev.mysql.com/doc/dev/mysql-server/8.0.12/page_protocol_command_phase_sp.html#sect_protocol_command_phase_sp_multi_resultset
            ctx.assertEquals(1, result.size());
            ctx.assertEquals(123, result.iterator().next().getInteger(0));

            RowSet<Row> secondResult = result.next();
            ctx.assertEquals(1, secondResult.size());
            ctx.assertEquals(456, secondResult.iterator().next().getInteger(0));

            RowSet<Row> thirdResult = secondResult.next();
            ctx.assertEquals(0, thirdResult.size());
            if (rule.isUsingMariaDB()) {
              ctx.assertEquals(2, thirdResult.rowCount());
            } else {
              ctx.assertEquals(1, thirdResult.rowCount()); // will only return the affected_rows of the last INSERT statement
            }

            conn.query("SELECT id FROM ins").execute(ctx.asyncAssertSuccess(queryRes -> {
              ctx.assertEquals(2, queryRes.size());
              RowIterator<Row> rowIterator = queryRes.iterator();
              Row row1 = rowIterator.next();
              ctx.assertEquals(1, row1.getValue(0));
              Row row2 = rowIterator.next();
              ctx.assertEquals(2, row2.getValue(0));
              conn.close();
            }));
          }));
        }));
      }));
    }));
  }));
}
 
Example 27
Source Project: raml-module-builder   Source File: LocalRowSet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public RowIterator<Row> iterator() {
  return new FakeRowIterator(rows);
}
 
Example 28
Source Project: raml-module-builder   Source File: AdminAPI.java    License: Apache License 2.0 4 votes vote down vote up
@Validate
@Override
public void putAdminPostgresDropIndexes(Map<String, String> okapiHeaders,
    Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {

  String tenantId = TenantTool.calculateTenantId( okapiHeaders.get(ClientGenerator.OKAPI_HEADER_TENANT) );

  if(tenantId == null){
    asyncResultHandler.handle(io.vertx.core.Future.failedFuture("tenantId cannot be null"));
    return;
  }
  String moduleName = PomReader.INSTANCE.getModuleName();
  String schema = tenantId.toLowerCase() + "_" + moduleName;
  String query =
      "SELECT * FROM pg_catalog.pg_class c JOIN pg_catalog.pg_index i ON (c.oid = i.indexrelid ) "
      + "JOIN pg_class t ON (i.indrelid = t.oid ) JOIN pg_namespace n ON (c.relnamespace = n.oid ) "
      + "WHERE c.relkind = 'i' AND n.nspname = '"+schema+"';";
  try{
    PostgresClient.getInstance(vertxContext.owner()).select(query, reply -> {
      if(reply.succeeded()){
        int indexes2delete[] = new int[]{ 0 };
        RowSet<Row> rs = reply.result();
        StringBuilder concatIndexNames = new StringBuilder();
        RowIterator<Row> iterator = rs.iterator();
        while (iterator.hasNext()) {
          Row row = iterator.next();
          String indexName = row.getString(0);
          if(!indexName.endsWith("_pkey")){
            indexes2delete[0]++;
            if(concatIndexNames.length() > 0){
              concatIndexNames.append(", ");
            }
            concatIndexNames.append(schema).append(".").append(indexName);
          }
        }

        String dropIndexQuery = "DROP INDEX " + concatIndexNames.toString() + ";";
        if(indexes2delete[0] > 0){
          PostgresClient.getInstance(vertxContext.owner()).select(dropIndexQuery, reply2 -> {
            if(reply2.succeeded()){
              log.info("Deleted " + indexes2delete[0] + " indexes");
              asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutAdminPostgresDropIndexesResponse.respond204()));
            }
            else{
              log.error(reply.cause().getMessage(), reply.cause());
              asyncResultHandler.handle(io.vertx.core.Future.failedFuture(reply2.cause().getMessage()));
            }
          });
        }
        else{
          log.info("No indexes to delete");
          asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
            PutAdminPostgresDropIndexesResponse.respond400WithTextPlain("No indexes to delete, for tenant " + tenantId)));
        }
      }
      else{
        log.error(reply.cause().getMessage(), reply.cause());
        asyncResultHandler.handle(io.vertx.core.Future.failedFuture(reply.cause().getMessage()));
      }
    });
  } catch (Exception e) {
    log.error(e.getMessage(), e);
    asyncResultHandler.handle(io.vertx.core.Future.failedFuture(e.getMessage()));
  }
}